Completed
Branch master (2b8575)
by
unknown
11:34 queued 09:49
created
core/libraries/batch/JobHandlers/PreviewEventDeletion.php 1 patch
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -37,149 +37,149 @@  discard block
 block discarded – undo
37 37
 class PreviewEventDeletion extends JobHandler
38 38
 {
39 39
 
40
-    /**
41
-     * @var NodeGroupDao
42
-     */
43
-    protected $model_obj_node_group_persister;
40
+	/**
41
+	 * @var NodeGroupDao
42
+	 */
43
+	protected $model_obj_node_group_persister;
44 44
 
45
-    public function __construct(NodeGroupDao $model_obj_node_group_persister)
46
-    {
47
-        $this->model_obj_node_group_persister = $model_obj_node_group_persister;
48
-    }
45
+	public function __construct(NodeGroupDao $model_obj_node_group_persister)
46
+	{
47
+		$this->model_obj_node_group_persister = $model_obj_node_group_persister;
48
+	}
49 49
 
50
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
50
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
51 51
 
52
-    /**
53
-     *
54
-     * @param JobParameters $job_parameters
55
-     * @return JobStepResponse
56
-     * @throws EE_Error
57
-     * @throws InvalidDataTypeException
58
-     * @throws InvalidInterfaceException
59
-     * @throws InvalidArgumentException
60
-     * @throws ReflectionException
61
-     */
62
-    public function create_job(JobParameters $job_parameters)
63
-    {
64
-        // Set the "root" model objects we will want to delete (record their ID and model)
65
-        $event_ids = $job_parameters->request_datum('EVT_IDs', array());
66
-        // Find all the root nodes to delete (this isn't just events, because there's other data, like related tickets,
67
-        // prices, message templates, etc, whose model definition doesn't make them dependent on events. But,
68
-        // we have no UI to access them independent of events, so they may as well get deleted too.)
69
-        $roots = [];
70
-        foreach ($event_ids as $event_id) {
71
-            $roots[] = new ModelObjNode(
72
-                $event_id,
73
-                EEM_Event::instance()
74
-            );
75
-            // Also, we want to delete their related, non-global, tickets, prices and message templates
76
-            $related_non_global_tickets = EEM_Ticket::instance()->get_all_deleted_and_undeleted(
77
-                [
78
-                    [
79
-                        'TKT_is_default' => false,
80
-                        'Datetime.EVT_ID' => $event_id
81
-                    ]
82
-                ]
83
-            );
84
-            foreach ($related_non_global_tickets as $ticket) {
85
-                $roots[] = new ModelObjNode(
86
-                    $ticket->ID(),
87
-                    $ticket->get_model(),
88
-                    ['Registration']
89
-                );
90
-            }
91
-            $related_non_global_prices = EEM_Price::instance()->get_all_deleted_and_undeleted(
92
-                [
93
-                    [
94
-                        'PRC_is_default' => false,
95
-                        'Ticket.Datetime.EVT_ID' => $event_id
96
-                    ]
97
-                ]
98
-            );
99
-            foreach ($related_non_global_prices as $price) {
100
-                $roots[] = new ModelObjNode(
101
-                    $price->ID(),
102
-                    $price->get_model()
103
-                );
104
-            }
105
-        }
106
-        $transactions_ids = $this->getTransactionsToDelete($event_ids);
107
-        foreach ($transactions_ids as $transaction_id) {
108
-            $roots[] = new ModelObjNode(
109
-                $transaction_id,
110
-                EEM_Transaction::instance(),
111
-                ['Registration']
112
-            );
113
-        }
114
-        $job_parameters->add_extra_data('roots', $roots);
115
-        // Set an estimate of how long this will take (we're discovering as we go, so it seems impossible to give
116
-        // an accurate count.)
117
-        $estimated_work_per_model_obj = 10;
118
-        $count_regs = EEM_Registration::instance()->count(
119
-            [
120
-                [
121
-                    'EVT_ID' => ['IN', $event_ids]
122
-                ]
123
-            ]
124
-        );
125
-        $job_parameters->set_job_size((count($roots) + $count_regs) * $estimated_work_per_model_obj);
126
-        return new JobStepResponse(
127
-            $job_parameters,
128
-            esc_html__('Generating preview of data to be deleted...', 'event_espresso')
129
-        );
130
-    }
52
+	/**
53
+	 *
54
+	 * @param JobParameters $job_parameters
55
+	 * @return JobStepResponse
56
+	 * @throws EE_Error
57
+	 * @throws InvalidDataTypeException
58
+	 * @throws InvalidInterfaceException
59
+	 * @throws InvalidArgumentException
60
+	 * @throws ReflectionException
61
+	 */
62
+	public function create_job(JobParameters $job_parameters)
63
+	{
64
+		// Set the "root" model objects we will want to delete (record their ID and model)
65
+		$event_ids = $job_parameters->request_datum('EVT_IDs', array());
66
+		// Find all the root nodes to delete (this isn't just events, because there's other data, like related tickets,
67
+		// prices, message templates, etc, whose model definition doesn't make them dependent on events. But,
68
+		// we have no UI to access them independent of events, so they may as well get deleted too.)
69
+		$roots = [];
70
+		foreach ($event_ids as $event_id) {
71
+			$roots[] = new ModelObjNode(
72
+				$event_id,
73
+				EEM_Event::instance()
74
+			);
75
+			// Also, we want to delete their related, non-global, tickets, prices and message templates
76
+			$related_non_global_tickets = EEM_Ticket::instance()->get_all_deleted_and_undeleted(
77
+				[
78
+					[
79
+						'TKT_is_default' => false,
80
+						'Datetime.EVT_ID' => $event_id
81
+					]
82
+				]
83
+			);
84
+			foreach ($related_non_global_tickets as $ticket) {
85
+				$roots[] = new ModelObjNode(
86
+					$ticket->ID(),
87
+					$ticket->get_model(),
88
+					['Registration']
89
+				);
90
+			}
91
+			$related_non_global_prices = EEM_Price::instance()->get_all_deleted_and_undeleted(
92
+				[
93
+					[
94
+						'PRC_is_default' => false,
95
+						'Ticket.Datetime.EVT_ID' => $event_id
96
+					]
97
+				]
98
+			);
99
+			foreach ($related_non_global_prices as $price) {
100
+				$roots[] = new ModelObjNode(
101
+					$price->ID(),
102
+					$price->get_model()
103
+				);
104
+			}
105
+		}
106
+		$transactions_ids = $this->getTransactionsToDelete($event_ids);
107
+		foreach ($transactions_ids as $transaction_id) {
108
+			$roots[] = new ModelObjNode(
109
+				$transaction_id,
110
+				EEM_Transaction::instance(),
111
+				['Registration']
112
+			);
113
+		}
114
+		$job_parameters->add_extra_data('roots', $roots);
115
+		// Set an estimate of how long this will take (we're discovering as we go, so it seems impossible to give
116
+		// an accurate count.)
117
+		$estimated_work_per_model_obj = 10;
118
+		$count_regs = EEM_Registration::instance()->count(
119
+			[
120
+				[
121
+					'EVT_ID' => ['IN', $event_ids]
122
+				]
123
+			]
124
+		);
125
+		$job_parameters->set_job_size((count($roots) + $count_regs) * $estimated_work_per_model_obj);
126
+		return new JobStepResponse(
127
+			$job_parameters,
128
+			esc_html__('Generating preview of data to be deleted...', 'event_espresso')
129
+		);
130
+	}
131 131
 
132
-    /**
133
-     * @since 4.10.12.p
134
-     * @param EE_Base_Class[] $model_objs
135
-     * @param array $dont_traverse_models
136
-     * @return array
137
-     * @throws EE_Error
138
-     * @throws InvalidArgumentException
139
-     * @throws InvalidDataTypeException
140
-     * @throws InvalidInterfaceException
141
-     * @throws ReflectionException
142
-     */
143
-    protected function createModelObjNodes($model_objs, array $dont_traverse_models = [])
144
-    {
145
-        $nodes = [];
146
-        foreach ($model_objs as $model_obj) {
147
-            $nodes[] = new ModelObjNode(
148
-                $model_obj->ID(),
149
-                $model_obj->get_model(),
150
-                $dont_traverse_models
151
-            );
152
-        }
153
-        return $nodes;
154
-    }
132
+	/**
133
+	 * @since 4.10.12.p
134
+	 * @param EE_Base_Class[] $model_objs
135
+	 * @param array $dont_traverse_models
136
+	 * @return array
137
+	 * @throws EE_Error
138
+	 * @throws InvalidArgumentException
139
+	 * @throws InvalidDataTypeException
140
+	 * @throws InvalidInterfaceException
141
+	 * @throws ReflectionException
142
+	 */
143
+	protected function createModelObjNodes($model_objs, array $dont_traverse_models = [])
144
+	{
145
+		$nodes = [];
146
+		foreach ($model_objs as $model_obj) {
147
+			$nodes[] = new ModelObjNode(
148
+				$model_obj->ID(),
149
+				$model_obj->get_model(),
150
+				$dont_traverse_models
151
+			);
152
+		}
153
+		return $nodes;
154
+	}
155 155
 
156
-    /**
157
-     * Gets all the transactions related to these events that aren't related to other events. They'll be deleted too.
158
-     * (Ones that are related to other events can stay around until those other events are deleted too.)
159
-     * @since 4.10.12.p
160
-     * @param $event_ids
161
-     * @return array of transaction IDs
162
-     */
163
-    protected function getTransactionsToDelete($event_ids)
164
-    {
165
-        if (empty($event_ids)) {
166
-            return [];
167
-        }
168
-        global $wpdb;
169
-        $event_ids = array_map(
170
-            'intval',
171
-            $event_ids
172
-        );
173
-        $imploded_sanitized_event_ids = implode(',', $event_ids);
174
-        // Select transactions with registrations for the events $event_ids which also don't have registrations
175
-        // for any events NOT in $event_ids.
176
-        // Notice the outer query searched for transactions whose registrations ARE in $event_ids,
177
-        // whereas the inner query checks if the outer query's transaction has any registrations that are
178
-        // NOT IN $event_ids (ie, don't have registrations for events we're not just about to delete.)
179
-        return array_map(
180
-            'intval',
181
-            $wpdb->get_col(
182
-                "SELECT 
156
+	/**
157
+	 * Gets all the transactions related to these events that aren't related to other events. They'll be deleted too.
158
+	 * (Ones that are related to other events can stay around until those other events are deleted too.)
159
+	 * @since 4.10.12.p
160
+	 * @param $event_ids
161
+	 * @return array of transaction IDs
162
+	 */
163
+	protected function getTransactionsToDelete($event_ids)
164
+	{
165
+		if (empty($event_ids)) {
166
+			return [];
167
+		}
168
+		global $wpdb;
169
+		$event_ids = array_map(
170
+			'intval',
171
+			$event_ids
172
+		);
173
+		$imploded_sanitized_event_ids = implode(',', $event_ids);
174
+		// Select transactions with registrations for the events $event_ids which also don't have registrations
175
+		// for any events NOT in $event_ids.
176
+		// Notice the outer query searched for transactions whose registrations ARE in $event_ids,
177
+		// whereas the inner query checks if the outer query's transaction has any registrations that are
178
+		// NOT IN $event_ids (ie, don't have registrations for events we're not just about to delete.)
179
+		return array_map(
180
+			'intval',
181
+			$wpdb->get_col(
182
+				"SELECT 
183 183
                       DISTINCT t.TXN_ID
184 184
                     FROM 
185 185
                       {$wpdb->prefix}esp_transaction t INNER JOIN 
@@ -197,84 +197,84 @@  discard block
 block discarded – undo
197 197
                            tsub.TXN_ID=t.TXN_ID AND
198 198
                            rsub.EVT_ID NOT IN ({$imploded_sanitized_event_ids})
199 199
                        )"
200
-            )
201
-        );
202
-    }
200
+			)
201
+		);
202
+	}
203 203
 
204
-    /**
205
-     * Performs another step of the job
206
-     * @param JobParameters $job_parameters
207
-     * @param int $batch_size
208
-     * @return JobStepResponse
209
-     * @throws BatchRequestException
210
-     */
211
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
212
-    {
213
-        // Serializing and unserializing is what really makes this drag on (eg on localhost, the ajax requests took
214
-        // about 4 seconds when the batch size was 250, but 3 seconds when the batch size was 50. So like
215
-        // 50% of the request is just serializing and unserializing.) So, make the batches much bigger.
216
-        $batch_size *= 3;
217
-        $units_processed = 0;
218
-        foreach ($job_parameters->extra_datum('roots', array()) as $root_node) {
219
-            if ($units_processed >= $batch_size) {
220
-                break;
221
-            }
222
-            if (!$root_node instanceof ModelObjNode) {
223
-                throw new InvalidClassException('ModelObjNode');
224
-            }
225
-            if ($root_node->isComplete()) {
226
-                continue;
227
-            }
228
-            $units_processed += $root_node->visit($batch_size - $units_processed);
229
-        }
230
-        $job_parameters->mark_processed($units_processed);
231
-        // If the most-recently processed root node is complete, we must be all done because we're doing them
232
-        // sequentially.
233
-        if (isset($root_node) && $root_node instanceof ModelObjNode && $root_node->isComplete()) {
234
-            $job_parameters->set_status(JobParameters::status_complete);
235
-            // Show a full progress bar.
236
-            $job_parameters->set_units_processed($job_parameters->job_size());
237
-            $deletion_job_code = $job_parameters->request_datum('deletion_job_code');
238
-            $this->model_obj_node_group_persister->persistModelObjNodesGroup(
239
-                $job_parameters->extra_datum('roots'),
240
-                $deletion_job_code
241
-            );
242
-            return new JobStepResponse(
243
-                $job_parameters,
244
-                esc_html__('Finished identifying items for deletion.', 'event_espresso'),
245
-                [
246
-                    'deletion_job_code' => $deletion_job_code
247
-                ]
248
-            );
249
-        } else {
250
-            // Because the job size was a guess, it may have likely been provden wrong. We don't want to show more work
251
-            // done than we originally said there would be. So adjust the estimate.
252
-            if (($job_parameters->units_processed() / $job_parameters->job_size()) > .8) {
253
-                $job_parameters->set_job_size($job_parameters->job_size() * 2);
254
-            }
255
-            return new JobStepResponse(
256
-                $job_parameters,
257
-                sprintf(
258
-                    esc_html__('Identified %d items for deletion.', 'event_espresso'),
259
-                    $units_processed
260
-                )
261
-            );
262
-        }
263
-    }
204
+	/**
205
+	 * Performs another step of the job
206
+	 * @param JobParameters $job_parameters
207
+	 * @param int $batch_size
208
+	 * @return JobStepResponse
209
+	 * @throws BatchRequestException
210
+	 */
211
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
212
+	{
213
+		// Serializing and unserializing is what really makes this drag on (eg on localhost, the ajax requests took
214
+		// about 4 seconds when the batch size was 250, but 3 seconds when the batch size was 50. So like
215
+		// 50% of the request is just serializing and unserializing.) So, make the batches much bigger.
216
+		$batch_size *= 3;
217
+		$units_processed = 0;
218
+		foreach ($job_parameters->extra_datum('roots', array()) as $root_node) {
219
+			if ($units_processed >= $batch_size) {
220
+				break;
221
+			}
222
+			if (!$root_node instanceof ModelObjNode) {
223
+				throw new InvalidClassException('ModelObjNode');
224
+			}
225
+			if ($root_node->isComplete()) {
226
+				continue;
227
+			}
228
+			$units_processed += $root_node->visit($batch_size - $units_processed);
229
+		}
230
+		$job_parameters->mark_processed($units_processed);
231
+		// If the most-recently processed root node is complete, we must be all done because we're doing them
232
+		// sequentially.
233
+		if (isset($root_node) && $root_node instanceof ModelObjNode && $root_node->isComplete()) {
234
+			$job_parameters->set_status(JobParameters::status_complete);
235
+			// Show a full progress bar.
236
+			$job_parameters->set_units_processed($job_parameters->job_size());
237
+			$deletion_job_code = $job_parameters->request_datum('deletion_job_code');
238
+			$this->model_obj_node_group_persister->persistModelObjNodesGroup(
239
+				$job_parameters->extra_datum('roots'),
240
+				$deletion_job_code
241
+			);
242
+			return new JobStepResponse(
243
+				$job_parameters,
244
+				esc_html__('Finished identifying items for deletion.', 'event_espresso'),
245
+				[
246
+					'deletion_job_code' => $deletion_job_code
247
+				]
248
+			);
249
+		} else {
250
+			// Because the job size was a guess, it may have likely been provden wrong. We don't want to show more work
251
+			// done than we originally said there would be. So adjust the estimate.
252
+			if (($job_parameters->units_processed() / $job_parameters->job_size()) > .8) {
253
+				$job_parameters->set_job_size($job_parameters->job_size() * 2);
254
+			}
255
+			return new JobStepResponse(
256
+				$job_parameters,
257
+				sprintf(
258
+					esc_html__('Identified %d items for deletion.', 'event_espresso'),
259
+					$units_processed
260
+				)
261
+			);
262
+		}
263
+	}
264 264
 
265
-    /**
266
-     * Performs any clean-up logic when we know the job is completed
267
-     * @param JobParameters $job_parameters
268
-     * @return JobStepResponse
269
-     */
270
-    public function cleanup_job(JobParameters $job_parameters)
271
-    {
272
-        // Nothing much to do. We can't delete the option with the built tree because we may need it in a moment for the deletion
273
-        return new JobStepResponse(
274
-            $job_parameters,
275
-            esc_html__('All done', 'event_espresso')
276
-        );
277
-    }
265
+	/**
266
+	 * Performs any clean-up logic when we know the job is completed
267
+	 * @param JobParameters $job_parameters
268
+	 * @return JobStepResponse
269
+	 */
270
+	public function cleanup_job(JobParameters $job_parameters)
271
+	{
272
+		// Nothing much to do. We can't delete the option with the built tree because we may need it in a moment for the deletion
273
+		return new JobStepResponse(
274
+			$job_parameters,
275
+			esc_html__('All done', 'event_espresso')
276
+		);
277
+	}
278 278
 }
279 279
 // End of file EventDeletion.php
280 280
 // Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6455 added lines, -6455 removed lines patch added patch discarded remove patch
@@ -35,6461 +35,6461 @@
 block discarded – undo
35 35
 abstract class EEM_Base extends EE_Base implements ResettableInterface
36 36
 {
37 37
 
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    private static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    __(
561
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            __(
680
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (isset($query_params['limit'])
872
-            && ! isset($query_params['group_by'])
873
-        ) {
874
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
-        }
876
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
-    }
878
-
879
-
880
-
881
-    /**
882
-     * Modifies the query parameters so we only get back model objects
883
-     * that "belong" to the current user
884
-     *
885
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     */
888
-    public function alter_query_params_to_only_include_mine($query_params = array())
889
-    {
890
-        $wp_user_field_name = $this->wp_user_field_name();
891
-        if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
-        }
894
-        return $query_params;
895
-    }
896
-
897
-
898
-
899
-    /**
900
-     * Returns the name of the field's name that points to the WP_User table
901
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
-     * foreign key to the WP_User table)
903
-     *
904
-     * @return string|boolean string on success, boolean false when there is no
905
-     * foreign key to the WP_User table
906
-     */
907
-    public function wp_user_field_name()
908
-    {
909
-        try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
911
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
-                $last_model_name = end($models_to_follow_to_wp_users);
913
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
-            } else {
916
-                $model_with_fk_to_wp_users = $this;
917
-                $model_chain_to_wp_user = '';
918
-            }
919
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
921
-        } catch (EE_Error $e) {
922
-            return false;
923
-        }
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
930
-     * (or transiently-related model) has a foreign key to the wp_users table;
931
-     * useful for finding if model objects of this type are 'owned' by the current user.
932
-     * This is an empty string when the foreign key is on this model and when it isn't,
933
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
934
-     * (or transiently-related model)
935
-     *
936
-     * @return string
937
-     */
938
-    public function model_chain_to_wp_user()
939
-    {
940
-        return $this->_model_chain_to_wp_user;
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
-     * like how registrations don't have a foreign key to wp_users, but the
948
-     * events they are for are), or is unrelated to wp users.
949
-     * generally available
950
-     *
951
-     * @return boolean
952
-     */
953
-    public function is_owned()
954
-    {
955
-        if ($this->model_chain_to_wp_user()) {
956
-            return true;
957
-        }
958
-        try {
959
-            $this->get_foreign_key_to('WP_User');
960
-            return true;
961
-        } catch (EE_Error $e) {
962
-            return false;
963
-        }
964
-    }
965
-
966
-
967
-    /**
968
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
-     * the model)
971
-     *
972
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
-     *                                  fields on the model, and the models we joined to in the query. However, you can
976
-     *                                  override this and set the select to "*", or a specific column name, like
977
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
-     *                                  the aliases used to refer to this selection, and values are to be
980
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
-     * @throws EE_Error
984
-     * @throws InvalidArgumentException
985
-     */
986
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
-    {
988
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
-        ;
990
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
991
-        $select_expressions = $columns_to_select === null
992
-            ? $this->_construct_default_select_sql($model_query_info)
993
-            : '';
994
-        if ($this->_custom_selections instanceof CustomSelects) {
995
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
-            $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
998
-                : $custom_expressions;
999
-        }
1000
-
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
-     * method of including extra select information.
1010
-     *
1011
-     * @param array             $query_params
1012
-     * @param null|array|string $columns_to_select
1013
-     * @return null|CustomSelects
1014
-     * @throws InvalidArgumentException
1015
-     */
1016
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
-    {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
-            return null;
1020
-        }
1021
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
-        return new CustomSelects($selects);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1030
-     * but you can use the model query params to more easily
1031
-     * take care of joins, field preparation etc.
1032
-     *
1033
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
-    }
1050
-
1051
-
1052
-
1053
-    /**
1054
-     * For creating a custom select statement
1055
-     *
1056
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
-     *                                 SQL, and 1=>is the datatype
1059
-     * @throws EE_Error
1060
-     * @return string
1061
-     */
1062
-    private function _construct_select_from_input($columns_to_select)
1063
-    {
1064
-        if (is_array($columns_to_select)) {
1065
-            $select_sql_array = array();
1066
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
-                    throw new EE_Error(
1069
-                        sprintf(
1070
-                            __(
1071
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
-                                'event_espresso'
1073
-                            ),
1074
-                            $selection_and_datatype,
1075
-                            $alias
1076
-                        )
1077
-                    );
1078
-                }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
-                    throw new EE_Error(
1081
-                        sprintf(
1082
-                            esc_html__(
1083
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
-                                'event_espresso'
1085
-                            ),
1086
-                            $selection_and_datatype[1],
1087
-                            $selection_and_datatype[0],
1088
-                            $alias,
1089
-                            implode(', ', $this->_valid_wpdb_data_types)
1090
-                        )
1091
-                    );
1092
-                }
1093
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
-            }
1095
-            $columns_to_select_string = implode(', ', $select_sql_array);
1096
-        } else {
1097
-            $columns_to_select_string = $columns_to_select;
1098
-        }
1099
-        return $columns_to_select_string;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
-     *
1107
-     * @return string
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function primary_key_name()
1111
-    {
1112
-        return $this->get_primary_key_field()->get_name();
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
-     * If there is no primary key on this model, $id is treated as primary key string
1119
-     *
1120
-     * @param mixed $id int or string, depending on the type of the model's primary key
1121
-     * @return EE_Base_Class
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function get_one_by_ID($id)
1125
-    {
1126
-        if ($this->get_from_entity_map($id)) {
1127
-            return $this->get_from_entity_map($id);
1128
-        }
1129
-        $model_object = $this->get_one(
1130
-            $this->alter_query_params_to_restrict_by_ID(
1131
-                $id,
1132
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
-            )
1134
-        );
1135
-        $className = $this->_get_class_name();
1136
-        if ($model_object instanceof $className) {
1137
-            // make sure valid objects get added to the entity map
1138
-            // so that the next call to this method doesn't trigger another trip to the db
1139
-            $this->add_to_entity_map($model_object);
1140
-        }
1141
-        return $model_object;
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Alters query parameters to only get items with this ID are returned.
1148
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
-     * or could just be a simple primary key ID
1150
-     *
1151
-     * @param int   $id
1152
-     * @param array $query_params
1153
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
-    {
1158
-        if (! isset($query_params[0])) {
1159
-            $query_params[0] = array();
1160
-        }
1161
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1162
-        if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1164
-        } else {
1165
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1166
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
-        }
1168
-        return $query_params;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
-     * array. If no item is found, null is returned.
1176
-     *
1177
-     * @param array $query_params like EEM_Base's $query_params variable.
1178
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
-     * @throws EE_Error
1180
-     */
1181
-    public function get_one($query_params = array())
1182
-    {
1183
-        if (! is_array($query_params)) {
1184
-            EE_Error::doing_it_wrong(
1185
-                'EEM_Base::get_one',
1186
-                sprintf(
1187
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
-                    gettype($query_params)
1189
-                ),
1190
-                '4.6.0'
1191
-            );
1192
-            $query_params = array();
1193
-        }
1194
-        $query_params['limit'] = 1;
1195
-        $items = $this->get_all($query_params);
1196
-        if (empty($items)) {
1197
-            return null;
1198
-        }
1199
-        return array_shift($items);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next x number of items in sequence from the given value as
1206
-     * found in the database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param int   $limit                  How many to return.
1212
-     * @param array $query_params           Extra conditions on the query.
1213
-     * @param null  $columns_to_select      If left null, then an array of
1214
-     *                                      EE_Base_Class objects is returned,
1215
-     *                                      otherwise you can indicate just the
1216
-     *                                      columns you want returned.
1217
-     * @return EE_Base_Class[]|array
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function next_x(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $limit = 1,
1224
-        $query_params = array(),
1225
-        $columns_to_select = null
1226
-    ) {
1227
-        return $this->_get_consecutive(
1228
-            $current_field_value,
1229
-            '>',
1230
-            $field_to_order_by,
1231
-            $limit,
1232
-            $query_params,
1233
-            $columns_to_select
1234
-        );
1235
-    }
1236
-
1237
-
1238
-
1239
-    /**
1240
-     * Returns the previous x number of items in sequence from the given value
1241
-     * as found in the database matching the given query conditions.
1242
-     *
1243
-     * @param mixed $current_field_value    Value used for the reference point.
1244
-     * @param null  $field_to_order_by      What field is used for the
1245
-     *                                      reference point.
1246
-     * @param int   $limit                  How many to return.
1247
-     * @param array $query_params           Extra conditions on the query.
1248
-     * @param null  $columns_to_select      If left null, then an array of
1249
-     *                                      EE_Base_Class objects is returned,
1250
-     *                                      otherwise you can indicate just the
1251
-     *                                      columns you want returned.
1252
-     * @return EE_Base_Class[]|array
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function previous_x(
1256
-        $current_field_value,
1257
-        $field_to_order_by = null,
1258
-        $limit = 1,
1259
-        $query_params = array(),
1260
-        $columns_to_select = null
1261
-    ) {
1262
-        return $this->_get_consecutive(
1263
-            $current_field_value,
1264
-            '<',
1265
-            $field_to_order_by,
1266
-            $limit,
1267
-            $query_params,
1268
-            $columns_to_select
1269
-        );
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Returns the next item in sequence from the given value as found in the
1276
-     * database matching the given query conditions.
1277
-     *
1278
-     * @param mixed $current_field_value    Value used for the reference point.
1279
-     * @param null  $field_to_order_by      What field is used for the
1280
-     *                                      reference point.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
-     *                                      object is returned, otherwise you
1284
-     *                                      can indicate just the columns you
1285
-     *                                      want and a single array indexed by
1286
-     *                                      the columns will be returned.
1287
-     * @return EE_Base_Class|null|array()
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function next(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $query_params = array(),
1294
-        $columns_to_select = null
1295
-    ) {
1296
-        $results = $this->_get_consecutive(
1297
-            $current_field_value,
1298
-            '>',
1299
-            $field_to_order_by,
1300
-            1,
1301
-            $query_params,
1302
-            $columns_to_select
1303
-        );
1304
-        return empty($results) ? null : reset($results);
1305
-    }
1306
-
1307
-
1308
-
1309
-    /**
1310
-     * Returns the previous item in sequence from the given value as found in
1311
-     * the database matching the given query conditions.
1312
-     *
1313
-     * @param mixed $current_field_value    Value used for the reference point.
1314
-     * @param null  $field_to_order_by      What field is used for the
1315
-     *                                      reference point.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
-     *                                      object is returned, otherwise you
1319
-     *                                      can indicate just the columns you
1320
-     *                                      want and a single array indexed by
1321
-     *                                      the columns will be returned.
1322
-     * @return EE_Base_Class|null|array()
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function previous(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $query_params = array(),
1329
-        $columns_to_select = null
1330
-    ) {
1331
-        $results = $this->_get_consecutive(
1332
-            $current_field_value,
1333
-            '<',
1334
-            $field_to_order_by,
1335
-            1,
1336
-            $query_params,
1337
-            $columns_to_select
1338
-        );
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__(
1373
-                        'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1374
-                        'event_espresso'
1375
-                    ));
1376
-                }
1377
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
-                return array();
1379
-            }
1380
-        }
1381
-        if (! is_array($query_params)) {
1382
-            EE_Error::doing_it_wrong(
1383
-                'EEM_Base::_get_consecutive',
1384
-                sprintf(
1385
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
-                    gettype($query_params)
1387
-                ),
1388
-                '4.6.0'
1389
-            );
1390
-            $query_params = array();
1391
-        }
1392
-        // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
-        $query_params['limit'] = $limit;
1395
-        // set direction
1396
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
-        $query_params['order_by'] = $operand === '>'
1398
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
-        if (empty($columns_to_select)) {
1402
-            return $this->get_all($query_params);
1403
-        }
1404
-        // getting just the fields
1405
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
-    }
1407
-
1408
-
1409
-
1410
-    /**
1411
-     * This sets the _timezone property after model object has been instantiated.
1412
-     *
1413
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
-     */
1415
-    public function set_timezone($timezone)
1416
-    {
1417
-        if ($timezone !== null) {
1418
-            $this->_timezone = $timezone;
1419
-        }
1420
-        // note we need to loop through relations and set the timezone on those objects as well.
1421
-        foreach ($this->_model_relations as $relation) {
1422
-            $relation->set_timezone($timezone);
1423
-        }
1424
-        // and finally we do the same for any datetime fields
1425
-        foreach ($this->_fields as $field) {
1426
-            if ($field instanceof EE_Datetime_Field) {
1427
-                $field->set_timezone($timezone);
1428
-            }
1429
-        }
1430
-    }
1431
-
1432
-
1433
-
1434
-    /**
1435
-     * This just returns whatever is set for the current timezone.
1436
-     *
1437
-     * @access public
1438
-     * @return string
1439
-     */
1440
-    public function get_timezone()
1441
-    {
1442
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
-        if (empty($this->_timezone)) {
1444
-            foreach ($this->_fields as $field) {
1445
-                if ($field instanceof EE_Datetime_Field) {
1446
-                    $this->set_timezone($field->get_timezone());
1447
-                    break;
1448
-                }
1449
-            }
1450
-        }
1451
-        // if timezone STILL empty then return the default timezone for the site.
1452
-        if (empty($this->_timezone)) {
1453
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
-        }
1455
-        return $this->_timezone;
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This returns the date formats set for the given field name and also ensures that
1462
-     * $this->_timezone property is set correctly.
1463
-     *
1464
-     * @since 4.6.x
1465
-     * @param string $field_name The name of the field the formats are being retrieved for.
1466
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
-     * @return array formats in an array with the date format first, and the time format last.
1469
-     */
1470
-    public function get_formats_for($field_name, $pretty = false)
1471
-    {
1472
-        $field_settings = $this->field_settings_for($field_name);
1473
-        // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1475
-            throw new EE_Error(sprintf(__(
1476
-                'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1477
-                'event_espresso'
1478
-            ), $field_name));
1479
-        }
1480
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
-        // the field.
1482
-        $this->_timezone = $field_settings->get_timezone();
1483
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * This returns the current time in a format setup for a query on this model.
1490
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
-     * it will return:
1492
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
-     *  NOW
1494
-     *  - or a unix timestamp (equivalent to time())
1495
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
-     * @since 4.6.x
1499
-     * @param string $field_name       The field the current time is needed for.
1500
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
-     *                                 formatted string matching the set format for the field in the set timezone will
1502
-     *                                 be returned.
1503
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
-     *                                 exception is triggered.
1507
-     */
1508
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
-    {
1510
-        $formats = $this->get_formats_for($field_name);
1511
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
-        if ($timestamp) {
1513
-            return $DateTime->format('U');
1514
-        }
1515
-        // not returning timestamp, so return formatted string in timezone.
1516
-        switch ($what) {
1517
-            case 'time':
1518
-                return $DateTime->format($formats[1]);
1519
-                break;
1520
-            case 'date':
1521
-                return $DateTime->format($formats[0]);
1522
-                break;
1523
-            default:
1524
-                return $DateTime->format(implode(' ', $formats));
1525
-                break;
1526
-        }
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
-     * for the model are.  Returns a DateTime object.
1534
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
-     * ignored.
1537
-     *
1538
-     * @param string $field_name      The field being setup.
1539
-     * @param string $timestring      The date time string being used.
1540
-     * @param string $incoming_format The format for the time string.
1541
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
-     *                                format is
1544
-     *                                'U', this is ignored.
1545
-     * @return DateTime
1546
-     * @throws EE_Error
1547
-     */
1548
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
-    {
1550
-        // just using this to ensure the timezone is set correctly internally
1551
-        $this->get_formats_for($field_name);
1552
-        // load EEH_DTT_Helper
1553
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
-     *
1564
-     * @return EE_Table_Base[]
1565
-     */
1566
-    public function get_tables()
1567
-    {
1568
-        return $this->_tables;
1569
-    }
1570
-
1571
-
1572
-
1573
-    /**
1574
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
-     * model object with EVT_ID = 1
1580
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
-     * are not specified)
1585
-     *
1586
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1591
-     *                                         ID=34, we'd use this method as follows:
1592
-     *                                         EEM_Transaction::instance()->update(
1593
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
-     *                                         array(array('TXN_ID'=>34)));
1595
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
-     *                                         TRUE, it is assumed that you've already called
1602
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
-     *                                         malicious javascript. However, if
1604
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
-     *                                         and every other field, before insertion. We provide this parameter
1607
-     *                                         because model objects perform their prepare_for_set function on all
1608
-     *                                         their values, and so don't need to be called again (and in many cases,
1609
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
-     *                                         prepare_for_set method...)
1611
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
-     *                                         in this model's entity map according to $fields_n_values that match
1613
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1614
-     *                                         by setting this to FALSE, but be aware that model objects being used
1615
-     *                                         could get out-of-sync with the database
1616
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
-     *                                         bad)
1619
-     * @throws EE_Error
1620
-     */
1621
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
-    {
1623
-        if (! is_array($query_params)) {
1624
-            EE_Error::doing_it_wrong(
1625
-                'EEM_Base::update',
1626
-                sprintf(
1627
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
-                    gettype($query_params)
1629
-                ),
1630
-                '4.6.0'
1631
-            );
1632
-            $query_params = array();
1633
-        }
1634
-        /**
1635
-         * Action called before a model update call has been made.
1636
-         *
1637
-         * @param EEM_Base $model
1638
-         * @param array    $fields_n_values the updated fields and their new values
1639
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
-         */
1641
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
-        /**
1643
-         * Filters the fields about to be updated given the query parameters. You can provide the
1644
-         * $query_params to $this->get_all() to find exactly which records will be updated
1645
-         *
1646
-         * @param array    $fields_n_values fields and their new values
1647
-         * @param EEM_Base $model           the model being queried
1648
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
-         */
1650
-        $fields_n_values = (array) apply_filters(
1651
-            'FHEE__EEM_Base__update__fields_n_values',
1652
-            $fields_n_values,
1653
-            $this,
1654
-            $query_params
1655
-        );
1656
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
-        // to do that, for each table, verify that it's PK isn't null.
1658
-        $tables = $this->get_tables();
1659
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
-        // NOTE: we should make this code more efficient by NOT querying twice
1661
-        // before the real update, but that needs to first go through ALPHA testing
1662
-        // as it's dangerous. says Mike August 8 2014
1663
-        // we want to make sure the default_where strategy is ignored
1664
-        $this->_ignore_where_strategy = true;
1665
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
-        foreach ($wpdb_select_results as $wpdb_result) {
1667
-            // type cast stdClass as array
1668
-            $wpdb_result = (array) $wpdb_result;
1669
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
-            if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
-            } else {
1673
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1674
-                $main_table_pk_value = null;
1675
-            }
1676
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1677
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1678
-            if (count($tables) > 1) {
1679
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
-                // in that table, and so we'll want to insert one
1681
-                foreach ($tables as $table_obj) {
1682
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
-                    // if there is no private key for this table on the results, it means there's no entry
1684
-                    // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1687
-                    ) {
1688
-                        $success = $this->_insert_into_specific_table(
1689
-                            $table_obj,
1690
-                            $fields_n_values,
1691
-                            $main_table_pk_value
1692
-                        );
1693
-                        // if we died here, report the error
1694
-                        if (! $success) {
1695
-                            return false;
1696
-                        }
1697
-                    }
1698
-                }
1699
-            }
1700
-            //              //and now check that if we have cached any models by that ID on the model, that
1701
-            //              //they also get updated properly
1702
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
-            //              if( $model_object ){
1704
-            //                  foreach( $fields_n_values as $field => $value ){
1705
-            //                      $model_object->set($field, $value);
1706
-            // let's make sure default_where strategy is followed now
1707
-            $this->_ignore_where_strategy = false;
1708
-        }
1709
-        // if we want to keep model objects in sync, AND
1710
-        // if this wasn't called from a model object (to update itself)
1711
-        // then we want to make sure we keep all the existing
1712
-        // model objects in sync with the db
1713
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
-            if ($this->has_primary_key_field()) {
1715
-                $model_objs_affected_ids = $this->get_col($query_params);
1716
-            } else {
1717
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
-                $model_objs_affected_ids = array();
1720
-                foreach ($models_affected_key_columns as $row) {
1721
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
-                }
1724
-            }
1725
-            if (! $model_objs_affected_ids) {
1726
-                // wait wait wait- if nothing was affected let's stop here
1727
-                return 0;
1728
-            }
1729
-            foreach ($model_objs_affected_ids as $id) {
1730
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
-                if ($model_obj_in_entity_map) {
1732
-                    foreach ($fields_n_values as $field => $new_value) {
1733
-                        $model_obj_in_entity_map->set($field, $new_value);
1734
-                    }
1735
-                }
1736
-            }
1737
-            // if there is a primary key on this model, we can now do a slight optimization
1738
-            if ($this->has_primary_key_field()) {
1739
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
-                $query_params = array(
1741
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
-                    'limit'                    => count($model_objs_affected_ids),
1743
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
-                );
1745
-            }
1746
-        }
1747
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
-        $SQL = "UPDATE "
1749
-               . $model_query_info->get_full_join_sql()
1750
-               . " SET "
1751
-               . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
-        /**
1755
-         * Action called after a model update call has been made.
1756
-         *
1757
-         * @param EEM_Base $model
1758
-         * @param array    $fields_n_values the updated fields and their new values
1759
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
-         * @param int      $rows_affected
1761
-         */
1762
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1764
-    }
1765
-
1766
-
1767
-
1768
-    /**
1769
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
-     * are teh values of the field specified (or by default the primary key field)
1771
-     * that matched the query params. Note that you should pass the name of the
1772
-     * model FIELD, not the database table's column name.
1773
-     *
1774
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
-     * @param string $field_to_select
1776
-     * @return array just like $wpdb->get_col()
1777
-     * @throws EE_Error
1778
-     */
1779
-    public function get_col($query_params = array(), $field_to_select = null)
1780
-    {
1781
-        if ($field_to_select) {
1782
-            $field = $this->field_settings_for($field_to_select);
1783
-        } elseif ($this->has_primary_key_field()) {
1784
-            $field = $this->get_primary_key_field();
1785
-        } else {
1786
-            // no primary key, just grab the first column
1787
-            $field = reset($this->field_settings());
1788
-        }
1789
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
-        $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
-        return $this->_do_wpdb_query('get_col', array($SQL));
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Returns a single column value for a single row from the database
1799
-     *
1800
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
-     * @param string $field_to_select @see EEM_Base::get_col()
1802
-     * @return string
1803
-     * @throws EE_Error
1804
-     */
1805
-    public function get_var($query_params = array(), $field_to_select = null)
1806
-    {
1807
-        $query_params['limit'] = 1;
1808
-        $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1810
-            return reset($col);
1811
-        }
1812
-        return null;
1813
-    }
1814
-
1815
-
1816
-
1817
-    /**
1818
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
-     * injection, but currently no further filtering is done
1821
-     *
1822
-     * @global      $wpdb
1823
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
-     *                               be updated to in the DB
1825
-     * @return string of SQL
1826
-     * @throws EE_Error
1827
-     */
1828
-    public function _construct_update_sql($fields_n_values)
1829
-    {
1830
-        /** @type WPDB $wpdb */
1831
-        global $wpdb;
1832
-        $cols_n_values = array();
1833
-        foreach ($fields_n_values as $field_name => $value) {
1834
-            $field_obj = $this->field_settings_for($field_name);
1835
-            // if the value is NULL, we want to assign the value to that.
1836
-            // wpdb->prepare doesn't really handle that properly
1837
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
-            $value_sql = $prepared_value === null ? 'NULL'
1839
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
-        }
1842
-        return implode(",", $cols_n_values);
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Performs a HARD delete, meaning the database row should always be removed,
1850
-     * not just have a flag field on it switched
1851
-     * Wrapper for EEM_Base::delete_permanently()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @param boolean $allow_blocking
1855
-     * @return int the number of rows deleted
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
-    {
1860
-        return $this->delete_permanently(
1861
-            array(
1862
-                array($this->get_primary_key_field()->get_name() => $id),
1863
-                'limit' => 1,
1864
-            ),
1865
-            $allow_blocking
1866
-        );
1867
-    }
1868
-
1869
-
1870
-
1871
-    /**
1872
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
-     * Wrapper for EEM_Base::delete()
1874
-     *
1875
-     * @param mixed $id
1876
-     * @param boolean $allow_blocking
1877
-     * @return int the number of rows deleted
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function delete_by_ID($id, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete(
1883
-            array(
1884
-                array($this->get_primary_key_field()->get_name() => $id),
1885
-                'limit' => 1,
1886
-            ),
1887
-            $allow_blocking
1888
-        );
1889
-    }
1890
-
1891
-
1892
-
1893
-    /**
1894
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1895
-     * meaning if the model has a field that indicates its been "trashed" or
1896
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1897
-     *
1898
-     * @see EEM_Base::delete_permanently
1899
-     * @param array   $query_params
1900
-     * @param boolean $allow_blocking
1901
-     * @return int how many rows got deleted
1902
-     * @throws EE_Error
1903
-     */
1904
-    public function delete($query_params, $allow_blocking = true)
1905
-    {
1906
-        return $this->delete_permanently($query_params, $allow_blocking);
1907
-    }
1908
-
1909
-
1910
-
1911
-    /**
1912
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1913
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
-     * as archived, not actually deleted
1915
-     *
1916
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
-     *                                deletes regardless of other objects which may depend on it. Its generally
1920
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
-     *                                DB
1922
-     * @return int how many rows got deleted
1923
-     * @throws EE_Error
1924
-     */
1925
-    public function delete_permanently($query_params, $allow_blocking = true)
1926
-    {
1927
-        /**
1928
-         * Action called just before performing a real deletion query. You can use the
1929
-         * model and its $query_params to find exactly which items will be deleted
1930
-         *
1931
-         * @param EEM_Base $model
1932
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1934
-         *                                 to block (prevent) this deletion
1935
-         */
1936
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
-        // some MySQL databases may be running safe mode, which may restrict
1938
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
-        // to delete them
1941
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
-            $columns_and_ids_for_deleting
1945
-        );
1946
-        /**
1947
-         * Allows client code to act on the items being deleted before the query is actually executed.
1948
-         *
1949
-         * @param EEM_Base $this  The model instance being acted on.
1950
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
-         *                                                  derived from the incoming query parameters.
1954
-         *                                                  @see details on the structure of this array in the phpdocs
1955
-         *                                                  for the `_get_ids_for_delete_method`
1956
-         *
1957
-         */
1958
-        do_action(
1959
-            'AHEE__EEM_Base__delete__before_query',
1960
-            $this,
1961
-            $query_params,
1962
-            $allow_blocking,
1963
-            $columns_and_ids_for_deleting
1964
-        );
1965
-        if ($deletion_where_query_part) {
1966
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
-            $table_aliases = array_keys($this->_tables);
1968
-            $SQL = "DELETE "
1969
-                   . implode(", ", $table_aliases)
1970
-                   . " FROM "
1971
-                   . $model_query_info->get_full_join_sql()
1972
-                   . " WHERE "
1973
-                   . $deletion_where_query_part;
1974
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
-        } else {
1976
-            $rows_deleted = 0;
1977
-        }
1978
-
1979
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
-        // there was no error with the delete query.
1981
-        if ($this->has_primary_key_field()
1982
-            && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
-        ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
-            foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
-                }
1990
-            }
1991
-
1992
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
-            // (although it is possible).
1996
-            // Note this can be skipped by using the provided filter and returning false.
1997
-            if (apply_filters(
1998
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
-                ! $this instanceof EEM_Extra_Meta,
2000
-                $this
2001
-            )) {
2002
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2003
-                    0 => array(
2004
-                        'EXM_type' => $this->get_this_model_name(),
2005
-                        'OBJ_ID'   => array(
2006
-                            'IN',
2007
-                            $ids_for_removal
2008
-                        )
2009
-                    )
2010
-                ));
2011
-            }
2012
-        }
2013
-
2014
-        /**
2015
-         * Action called just after performing a real deletion query. Although at this point the
2016
-         * items should have been deleted
2017
-         *
2018
-         * @param EEM_Base $model
2019
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
-         * @param int      $rows_deleted
2021
-         */
2022
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2024
-    }
2025
-
2026
-
2027
-
2028
-    /**
2029
-     * Checks all the relations that throw error messages when there are blocking related objects
2030
-     * for related model objects. If there are any related model objects on those relations,
2031
-     * adds an EE_Error, and return true
2032
-     *
2033
-     * @param EE_Base_Class|int $this_model_obj_or_id
2034
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
-     *                                                 should be ignored when determining whether there are related
2036
-     *                                                 model objects which block this model object's deletion. Useful
2037
-     *                                                 if you know A is related to B and are considering deleting A,
2038
-     *                                                 but want to see if A has any other objects blocking its deletion
2039
-     *                                                 before removing the relation between A and B
2040
-     * @return boolean
2041
-     * @throws EE_Error
2042
-     */
2043
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
-    {
2045
-        // first, if $ignore_this_model_obj was supplied, get its model
2046
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
-            $ignored_model = $ignore_this_model_obj->get_model();
2048
-        } else {
2049
-            $ignored_model = null;
2050
-        }
2051
-        // now check all the relations of $this_model_obj_or_id and see if there
2052
-        // are any related model objects blocking it?
2053
-        $is_blocked = false;
2054
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2056
-                // if $ignore_this_model_obj was supplied, then for the query
2057
-                // on that model needs to be told to ignore $ignore_this_model_obj
2058
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
-                        array(
2061
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2062
-                                '!=',
2063
-                                $ignore_this_model_obj->ID(),
2064
-                            ),
2065
-                        ),
2066
-                    ));
2067
-                } else {
2068
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
-                }
2070
-                if ($related_model_objects) {
2071
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
-                    $is_blocked = true;
2073
-                }
2074
-            }
2075
-        }
2076
-        return $is_blocked;
2077
-    }
2078
-
2079
-
2080
-    /**
2081
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
-     * @param array $row_results_for_deleting
2083
-     * @param bool  $allow_blocking
2084
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
-     *                 deleted. Example:
2088
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2089
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
-     *                 where each element is a group of columns and values that get deleted. Example:
2091
-     *                      array(
2092
-     *                          0 => array(
2093
-     *                              'Term_Relationship.object_id' => 1
2094
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2095
-     *                          ),
2096
-     *                          1 => array(
2097
-     *                              'Term_Relationship.object_id' => 1
2098
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2099
-     *                          )
2100
-     *                      )
2101
-     * @throws EE_Error
2102
-     */
2103
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
-    {
2105
-        $ids_to_delete_indexed_by_column = array();
2106
-        if ($this->has_primary_key_field()) {
2107
-            $primary_table = $this->_get_main_table();
2108
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
-            $other_tables = $this->_get_other_tables();
2110
-            $ids_to_delete_indexed_by_column = $query = array();
2111
-            foreach ($row_results_for_deleting as $item_to_delete) {
2112
-                // before we mark this item for deletion,
2113
-                // make sure there's no related entities blocking its deletion (if we're checking)
2114
-                if ($allow_blocking
2115
-                    && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
-                    )
2118
-                ) {
2119
-                    continue;
2120
-                }
2121
-                // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
-                }
2126
-            }
2127
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
-            $fields = $this->get_combined_primary_key_fields();
2129
-            foreach ($row_results_for_deleting as $item_to_delete) {
2130
-                $ids_to_delete_indexed_by_column_for_row = array();
2131
-                foreach ($fields as $cpk_field) {
2132
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2135
-                    }
2136
-                }
2137
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
-            }
2139
-        } else {
2140
-            // so there's no primary key and no combined key...
2141
-            // sorry, can't help you
2142
-            throw new EE_Error(
2143
-                sprintf(
2144
-                    __(
2145
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
-                        "event_espresso"
2147
-                    ),
2148
-                    get_class($this)
2149
-                )
2150
-            );
2151
-        }
2152
-        return $ids_to_delete_indexed_by_column;
2153
-    }
2154
-
2155
-
2156
-    /**
2157
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
-     * the corresponding query_part for the query performing the delete.
2159
-     *
2160
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
-     * @return string
2162
-     * @throws EE_Error
2163
-     */
2164
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
-    {
2166
-        $query_part = '';
2167
-        if (empty($ids_to_delete_indexed_by_column)) {
2168
-            return $query_part;
2169
-        } elseif ($this->has_primary_key_field()) {
2170
-            $query = array();
2171
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2173
-            }
2174
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2175
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2176
-            $ways_to_identify_a_row = array();
2177
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2178
-                $values_for_each_combined_primary_key_for_a_row = array();
2179
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2180
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2181
-                }
2182
-                $ways_to_identify_a_row[] = '('
2183
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2184
-                                            . ')';
2185
-            }
2186
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2187
-        }
2188
-        return $query_part;
2189
-    }
2190
-
2191
-
2192
-
2193
-    /**
2194
-     * Gets the model field by the fully qualified name
2195
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2196
-     * @return EE_Model_Field_Base
2197
-     */
2198
-    public function get_field_by_column($qualified_column_name)
2199
-    {
2200
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2201
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2202
-                return $field_obj;
2203
-            }
2204
-        }
2205
-        throw new EE_Error(
2206
-            sprintf(
2207
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2208
-                $this->get_this_model_name(),
2209
-                $qualified_column_name
2210
-            )
2211
-        );
2212
-    }
2213
-
2214
-
2215
-
2216
-    /**
2217
-     * Count all the rows that match criteria the model query params.
2218
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2219
-     * column
2220
-     *
2221
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2222
-     * @param string $field_to_count field on model to count by (not column name)
2223
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2224
-     *                               that by the setting $distinct to TRUE;
2225
-     * @return int
2226
-     * @throws EE_Error
2227
-     */
2228
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2229
-    {
2230
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2231
-        if ($field_to_count) {
2232
-            $field_obj = $this->field_settings_for($field_to_count);
2233
-            $column_to_count = $field_obj->get_qualified_column();
2234
-        } elseif ($this->has_primary_key_field()) {
2235
-            $pk_field_obj = $this->get_primary_key_field();
2236
-            $column_to_count = $pk_field_obj->get_qualified_column();
2237
-        } else {
2238
-            // there's no primary key
2239
-            // if we're counting distinct items, and there's no primary key,
2240
-            // we need to list out the columns for distinction;
2241
-            // otherwise we can just use star
2242
-            if ($distinct) {
2243
-                $columns_to_use = array();
2244
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2245
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2246
-                }
2247
-                $column_to_count = implode(',', $columns_to_use);
2248
-            } else {
2249
-                $column_to_count = '*';
2250
-            }
2251
-        }
2252
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2253
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2254
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2255
-    }
2256
-
2257
-
2258
-
2259
-    /**
2260
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2261
-     *
2262
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2263
-     * @param string $field_to_sum name of field (array key in $_fields array)
2264
-     * @return float
2265
-     * @throws EE_Error
2266
-     */
2267
-    public function sum($query_params, $field_to_sum = null)
2268
-    {
2269
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2270
-        if ($field_to_sum) {
2271
-            $field_obj = $this->field_settings_for($field_to_sum);
2272
-        } else {
2273
-            $field_obj = $this->get_primary_key_field();
2274
-        }
2275
-        $column_to_count = $field_obj->get_qualified_column();
2276
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2277
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2278
-        $data_type = $field_obj->get_wpdb_data_type();
2279
-        if ($data_type === '%d' || $data_type === '%s') {
2280
-            return (float) $return_value;
2281
-        }
2282
-        // must be %f
2283
-        return (float) $return_value;
2284
-    }
2285
-
2286
-
2287
-
2288
-    /**
2289
-     * Just calls the specified method on $wpdb with the given arguments
2290
-     * Consolidates a little extra error handling code
2291
-     *
2292
-     * @param string $wpdb_method
2293
-     * @param array  $arguments_to_provide
2294
-     * @throws EE_Error
2295
-     * @global wpdb  $wpdb
2296
-     * @return mixed
2297
-     */
2298
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2299
-    {
2300
-        // if we're in maintenance mode level 2, DON'T run any queries
2301
-        // because level 2 indicates the database needs updating and
2302
-        // is probably out of sync with the code
2303
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2304
-            throw new EE_Error(sprintf(__(
2305
-                "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2306
-                "event_espresso"
2307
-            )));
2308
-        }
2309
-        /** @type WPDB $wpdb */
2310
-        global $wpdb;
2311
-        if (! method_exists($wpdb, $wpdb_method)) {
2312
-            throw new EE_Error(sprintf(__(
2313
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2314
-                'event_espresso'
2315
-            ), $wpdb_method));
2316
-        }
2317
-        if (WP_DEBUG) {
2318
-            $old_show_errors_value = $wpdb->show_errors;
2319
-            $wpdb->show_errors(false);
2320
-        }
2321
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2322
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2323
-        if (WP_DEBUG) {
2324
-            $wpdb->show_errors($old_show_errors_value);
2325
-            if (! empty($wpdb->last_error)) {
2326
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2327
-            }
2328
-            if ($result === false) {
2329
-                throw new EE_Error(sprintf(__(
2330
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2331
-                    'event_espresso'
2332
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2333
-            }
2334
-        } elseif ($result === false) {
2335
-            EE_Error::add_error(
2336
-                sprintf(
2337
-                    __(
2338
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2339
-                        'event_espresso'
2340
-                    ),
2341
-                    $wpdb_method,
2342
-                    var_export($arguments_to_provide, true),
2343
-                    $wpdb->last_error
2344
-                ),
2345
-                __FILE__,
2346
-                __FUNCTION__,
2347
-                __LINE__
2348
-            );
2349
-        }
2350
-        return $result;
2351
-    }
2352
-
2353
-
2354
-
2355
-    /**
2356
-     * Attempts to run the indicated WPDB method with the provided arguments,
2357
-     * and if there's an error tries to verify the DB is correct. Uses
2358
-     * the static property EEM_Base::$_db_verification_level to determine whether
2359
-     * we should try to fix the EE core db, the addons, or just give up
2360
-     *
2361
-     * @param string $wpdb_method
2362
-     * @param array  $arguments_to_provide
2363
-     * @return mixed
2364
-     */
2365
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2366
-    {
2367
-        /** @type WPDB $wpdb */
2368
-        global $wpdb;
2369
-        $wpdb->last_error = null;
2370
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2371
-        // was there an error running the query? but we don't care on new activations
2372
-        // (we're going to setup the DB anyway on new activations)
2373
-        if (($result === false || ! empty($wpdb->last_error))
2374
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2375
-        ) {
2376
-            switch (EEM_Base::$_db_verification_level) {
2377
-                case EEM_Base::db_verified_none:
2378
-                    // let's double-check core's DB
2379
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2380
-                    break;
2381
-                case EEM_Base::db_verified_core:
2382
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2383
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2384
-                    break;
2385
-                case EEM_Base::db_verified_addons:
2386
-                    // ummmm... you in trouble
2387
-                    return $result;
2388
-                    break;
2389
-            }
2390
-            if (! empty($error_message)) {
2391
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2392
-                trigger_error($error_message);
2393
-            }
2394
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2395
-        }
2396
-        return $result;
2397
-    }
2398
-
2399
-
2400
-
2401
-    /**
2402
-     * Verifies the EE core database is up-to-date and records that we've done it on
2403
-     * EEM_Base::$_db_verification_level
2404
-     *
2405
-     * @param string $wpdb_method
2406
-     * @param array  $arguments_to_provide
2407
-     * @return string
2408
-     */
2409
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2410
-    {
2411
-        /** @type WPDB $wpdb */
2412
-        global $wpdb;
2413
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2414
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2415
-        $error_message = sprintf(
2416
-            __(
2417
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2418
-                'event_espresso'
2419
-            ),
2420
-            $wpdb->last_error,
2421
-            $wpdb_method,
2422
-            wp_json_encode($arguments_to_provide)
2423
-        );
2424
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2425
-        return $error_message;
2426
-    }
2427
-
2428
-
2429
-
2430
-    /**
2431
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2432
-     * EEM_Base::$_db_verification_level
2433
-     *
2434
-     * @param $wpdb_method
2435
-     * @param $arguments_to_provide
2436
-     * @return string
2437
-     */
2438
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2439
-    {
2440
-        /** @type WPDB $wpdb */
2441
-        global $wpdb;
2442
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2443
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2444
-        $error_message = sprintf(
2445
-            __(
2446
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2447
-                'event_espresso'
2448
-            ),
2449
-            $wpdb->last_error,
2450
-            $wpdb_method,
2451
-            wp_json_encode($arguments_to_provide)
2452
-        );
2453
-        EE_System::instance()->initialize_addons();
2454
-        return $error_message;
2455
-    }
2456
-
2457
-
2458
-
2459
-    /**
2460
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2461
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2462
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2463
-     * ..."
2464
-     *
2465
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2466
-     * @return string
2467
-     */
2468
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2469
-    {
2470
-        return " FROM " . $model_query_info->get_full_join_sql() .
2471
-               $model_query_info->get_where_sql() .
2472
-               $model_query_info->get_group_by_sql() .
2473
-               $model_query_info->get_having_sql() .
2474
-               $model_query_info->get_order_by_sql() .
2475
-               $model_query_info->get_limit_sql();
2476
-    }
2477
-
2478
-
2479
-
2480
-    /**
2481
-     * Set to easily debug the next X queries ran from this model.
2482
-     *
2483
-     * @param int $count
2484
-     */
2485
-    public function show_next_x_db_queries($count = 1)
2486
-    {
2487
-        $this->_show_next_x_db_queries = $count;
2488
-    }
2489
-
2490
-
2491
-
2492
-    /**
2493
-     * @param $sql_query
2494
-     */
2495
-    public function show_db_query_if_previously_requested($sql_query)
2496
-    {
2497
-        if ($this->_show_next_x_db_queries > 0) {
2498
-            echo $sql_query;
2499
-            $this->_show_next_x_db_queries--;
2500
-        }
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2507
-     * There are the 3 cases:
2508
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2509
-     * $otherModelObject has no ID, it is first saved.
2510
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2511
-     * has no ID, it is first saved.
2512
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2513
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2514
-     * join table
2515
-     *
2516
-     * @param        EE_Base_Class                     /int $thisModelObject
2517
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2518
-     * @param string $relationName                     , key in EEM_Base::_relations
2519
-     *                                                 an attendee to a group, you also want to specify which role they
2520
-     *                                                 will have in that group. So you would use this parameter to
2521
-     *                                                 specify array('role-column-name'=>'role-id')
2522
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2523
-     *                                                 to for relation to methods that allow you to further specify
2524
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2525
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2526
-     *                                                 because these will be inserted in any new rows created as well.
2527
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2528
-     * @throws EE_Error
2529
-     */
2530
-    public function add_relationship_to(
2531
-        $id_or_obj,
2532
-        $other_model_id_or_obj,
2533
-        $relationName,
2534
-        $extra_join_model_fields_n_values = array()
2535
-    ) {
2536
-        $relation_obj = $this->related_settings_for($relationName);
2537
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2538
-    }
2539
-
2540
-
2541
-
2542
-    /**
2543
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2544
-     * There are the 3 cases:
2545
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2546
-     * error
2547
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2548
-     * an error
2549
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2550
-     *
2551
-     * @param        EE_Base_Class /int $id_or_obj
2552
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2553
-     * @param string $relationName key in EEM_Base::_relations
2554
-     * @return boolean of success
2555
-     * @throws EE_Error
2556
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2557
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2558
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2559
-     *                             because these will be inserted in any new rows created as well.
2560
-     */
2561
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2562
-    {
2563
-        $relation_obj = $this->related_settings_for($relationName);
2564
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2565
-    }
2566
-
2567
-
2568
-
2569
-    /**
2570
-     * @param mixed           $id_or_obj
2571
-     * @param string          $relationName
2572
-     * @param array           $where_query_params
2573
-     * @param EE_Base_Class[] objects to which relations were removed
2574
-     * @return \EE_Base_Class[]
2575
-     * @throws EE_Error
2576
-     */
2577
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2578
-    {
2579
-        $relation_obj = $this->related_settings_for($relationName);
2580
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2581
-    }
2582
-
2583
-
2584
-
2585
-    /**
2586
-     * Gets all the related items of the specified $model_name, using $query_params.
2587
-     * Note: by default, we remove the "default query params"
2588
-     * because we want to get even deleted items etc.
2589
-     *
2590
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2591
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2592
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2593
-     * @return EE_Base_Class[]
2594
-     * @throws EE_Error
2595
-     */
2596
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2597
-    {
2598
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2599
-        $relation_settings = $this->related_settings_for($model_name);
2600
-        return $relation_settings->get_all_related($model_obj, $query_params);
2601
-    }
2602
-
2603
-
2604
-
2605
-    /**
2606
-     * Deletes all the model objects across the relation indicated by $model_name
2607
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2608
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2609
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2610
-     *
2611
-     * @param EE_Base_Class|int|string $id_or_obj
2612
-     * @param string                   $model_name
2613
-     * @param array                    $query_params
2614
-     * @return int how many deleted
2615
-     * @throws EE_Error
2616
-     */
2617
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2618
-    {
2619
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2620
-        $relation_settings = $this->related_settings_for($model_name);
2621
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2622
-    }
2623
-
2624
-
2625
-
2626
-    /**
2627
-     * Hard deletes all the model objects across the relation indicated by $model_name
2628
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2629
-     * the model objects can't be hard deleted because of blocking related model objects,
2630
-     * just does a soft-delete on them instead.
2631
-     *
2632
-     * @param EE_Base_Class|int|string $id_or_obj
2633
-     * @param string                   $model_name
2634
-     * @param array                    $query_params
2635
-     * @return int how many deleted
2636
-     * @throws EE_Error
2637
-     */
2638
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2639
-    {
2640
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2641
-        $relation_settings = $this->related_settings_for($model_name);
2642
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2643
-    }
2644
-
2645
-
2646
-
2647
-    /**
2648
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2649
-     * unless otherwise specified in the $query_params
2650
-     *
2651
-     * @param        int             /EE_Base_Class $id_or_obj
2652
-     * @param string $model_name     like 'Event', or 'Registration'
2653
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2654
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2655
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2656
-     *                               that by the setting $distinct to TRUE;
2657
-     * @return int
2658
-     * @throws EE_Error
2659
-     */
2660
-    public function count_related(
2661
-        $id_or_obj,
2662
-        $model_name,
2663
-        $query_params = array(),
2664
-        $field_to_count = null,
2665
-        $distinct = false
2666
-    ) {
2667
-        $related_model = $this->get_related_model_obj($model_name);
2668
-        // we're just going to use the query params on the related model's normal get_all query,
2669
-        // except add a condition to say to match the current mod
2670
-        if (! isset($query_params['default_where_conditions'])) {
2671
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2672
-        }
2673
-        $this_model_name = $this->get_this_model_name();
2674
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2675
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2676
-        return $related_model->count($query_params, $field_to_count, $distinct);
2677
-    }
2678
-
2679
-
2680
-
2681
-    /**
2682
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2683
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2684
-     *
2685
-     * @param        int           /EE_Base_Class $id_or_obj
2686
-     * @param string $model_name   like 'Event', or 'Registration'
2687
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2688
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2689
-     * @return float
2690
-     * @throws EE_Error
2691
-     */
2692
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2693
-    {
2694
-        $related_model = $this->get_related_model_obj($model_name);
2695
-        if (! is_array($query_params)) {
2696
-            EE_Error::doing_it_wrong(
2697
-                'EEM_Base::sum_related',
2698
-                sprintf(
2699
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2700
-                    gettype($query_params)
2701
-                ),
2702
-                '4.6.0'
2703
-            );
2704
-            $query_params = array();
2705
-        }
2706
-        // we're just going to use the query params on the related model's normal get_all query,
2707
-        // except add a condition to say to match the current mod
2708
-        if (! isset($query_params['default_where_conditions'])) {
2709
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2710
-        }
2711
-        $this_model_name = $this->get_this_model_name();
2712
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2713
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2714
-        return $related_model->sum($query_params, $field_to_sum);
2715
-    }
2716
-
2717
-
2718
-
2719
-    /**
2720
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2721
-     * $modelObject
2722
-     *
2723
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2724
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2725
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2726
-     * @return EE_Base_Class
2727
-     * @throws EE_Error
2728
-     */
2729
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2730
-    {
2731
-        $query_params['limit'] = 1;
2732
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2733
-        if ($results) {
2734
-            return array_shift($results);
2735
-        }
2736
-        return null;
2737
-    }
2738
-
2739
-
2740
-
2741
-    /**
2742
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2743
-     *
2744
-     * @return string
2745
-     */
2746
-    public function get_this_model_name()
2747
-    {
2748
-        return str_replace("EEM_", "", get_class($this));
2749
-    }
2750
-
2751
-
2752
-
2753
-    /**
2754
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2755
-     *
2756
-     * @return EE_Any_Foreign_Model_Name_Field
2757
-     * @throws EE_Error
2758
-     */
2759
-    public function get_field_containing_related_model_name()
2760
-    {
2761
-        foreach ($this->field_settings(true) as $field) {
2762
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2763
-                $field_with_model_name = $field;
2764
-            }
2765
-        }
2766
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2767
-            throw new EE_Error(sprintf(
2768
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2769
-                $this->get_this_model_name()
2770
-            ));
2771
-        }
2772
-        return $field_with_model_name;
2773
-    }
2774
-
2775
-
2776
-
2777
-    /**
2778
-     * Inserts a new entry into the database, for each table.
2779
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2780
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2781
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2782
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2783
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2784
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2785
-     *
2786
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2787
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2788
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2789
-     *                              of EEM_Base)
2790
-     * @return int|string new primary key on main table that got inserted
2791
-     * @throws EE_Error
2792
-     */
2793
-    public function insert($field_n_values)
2794
-    {
2795
-        /**
2796
-         * Filters the fields and their values before inserting an item using the models
2797
-         *
2798
-         * @param array    $fields_n_values keys are the fields and values are their new values
2799
-         * @param EEM_Base $model           the model used
2800
-         */
2801
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2803
-            $main_table = $this->_get_main_table();
2804
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2805
-            if ($new_id !== false) {
2806
-                foreach ($this->_get_other_tables() as $other_table) {
2807
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2808
-                }
2809
-            }
2810
-            /**
2811
-             * Done just after attempting to insert a new model object
2812
-             *
2813
-             * @param EEM_Base   $model           used
2814
-             * @param array      $fields_n_values fields and their values
2815
-             * @param int|string the              ID of the newly-inserted model object
2816
-             */
2817
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2818
-            return $new_id;
2819
-        }
2820
-        return false;
2821
-    }
2822
-
2823
-
2824
-
2825
-    /**
2826
-     * Checks that the result would satisfy the unique indexes on this model
2827
-     *
2828
-     * @param array  $field_n_values
2829
-     * @param string $action
2830
-     * @return boolean
2831
-     * @throws EE_Error
2832
-     */
2833
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2834
-    {
2835
-        foreach ($this->unique_indexes() as $index_name => $index) {
2836
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2837
-            if ($this->exists(array($uniqueness_where_params))) {
2838
-                EE_Error::add_error(
2839
-                    sprintf(
2840
-                        __(
2841
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2842
-                            "event_espresso"
2843
-                        ),
2844
-                        $action,
2845
-                        $this->_get_class_name(),
2846
-                        $index_name,
2847
-                        implode(",", $index->field_names()),
2848
-                        http_build_query($uniqueness_where_params)
2849
-                    ),
2850
-                    __FILE__,
2851
-                    __FUNCTION__,
2852
-                    __LINE__
2853
-                );
2854
-                return false;
2855
-            }
2856
-        }
2857
-        return true;
2858
-    }
2859
-
2860
-
2861
-
2862
-    /**
2863
-     * Checks the database for an item that conflicts (ie, if this item were
2864
-     * saved to the DB would break some uniqueness requirement, like a primary key
2865
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2866
-     * can be either an EE_Base_Class or an array of fields n values
2867
-     *
2868
-     * @param EE_Base_Class|array $obj_or_fields_array
2869
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2870
-     *                                                 when looking for conflicts
2871
-     *                                                 (ie, if false, we ignore the model object's primary key
2872
-     *                                                 when finding "conflicts". If true, it's also considered).
2873
-     *                                                 Only works for INT primary key,
2874
-     *                                                 STRING primary keys cannot be ignored
2875
-     * @throws EE_Error
2876
-     * @return EE_Base_Class|array
2877
-     */
2878
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2879
-    {
2880
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2881
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2882
-        } elseif (is_array($obj_or_fields_array)) {
2883
-            $fields_n_values = $obj_or_fields_array;
2884
-        } else {
2885
-            throw new EE_Error(
2886
-                sprintf(
2887
-                    __(
2888
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2889
-                        "event_espresso"
2890
-                    ),
2891
-                    get_class($this),
2892
-                    $obj_or_fields_array
2893
-                )
2894
-            );
2895
-        }
2896
-        $query_params = array();
2897
-        if ($this->has_primary_key_field()
2898
-            && ($include_primary_key
2899
-                || $this->get_primary_key_field()
2900
-                   instanceof
2901
-                   EE_Primary_Key_String_Field)
2902
-            && isset($fields_n_values[ $this->primary_key_name() ])
2903
-        ) {
2904
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2905
-        }
2906
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2909
-        }
2910
-        // if there is nothing to base this search on, then we shouldn't find anything
2911
-        if (empty($query_params)) {
2912
-            return array();
2913
-        }
2914
-        return $this->get_one($query_params);
2915
-    }
2916
-
2917
-
2918
-
2919
-    /**
2920
-     * Like count, but is optimized and returns a boolean instead of an int
2921
-     *
2922
-     * @param array $query_params
2923
-     * @return boolean
2924
-     * @throws EE_Error
2925
-     */
2926
-    public function exists($query_params)
2927
-    {
2928
-        $query_params['limit'] = 1;
2929
-        return $this->count($query_params) > 0;
2930
-    }
2931
-
2932
-
2933
-
2934
-    /**
2935
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2936
-     *
2937
-     * @param int|string $id
2938
-     * @return boolean
2939
-     * @throws EE_Error
2940
-     */
2941
-    public function exists_by_ID($id)
2942
-    {
2943
-        return $this->exists(
2944
-            array(
2945
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2946
-                array(
2947
-                    $this->primary_key_name() => $id,
2948
-                ),
2949
-            )
2950
-        );
2951
-    }
2952
-
2953
-
2954
-
2955
-    /**
2956
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2957
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2958
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2959
-     * on the main table)
2960
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2961
-     * cases where we want to call it directly rather than via insert().
2962
-     *
2963
-     * @access   protected
2964
-     * @param EE_Table_Base $table
2965
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2966
-     *                                       float
2967
-     * @param int           $new_id          for now we assume only int keys
2968
-     * @throws EE_Error
2969
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2970
-     * @return int ID of new row inserted, or FALSE on failure
2971
-     */
2972
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2973
-    {
2974
-        global $wpdb;
2975
-        $insertion_col_n_values = array();
2976
-        $format_for_insertion = array();
2977
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2978
-        foreach ($fields_on_table as $field_name => $field_obj) {
2979
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2980
-            if ($field_obj->is_auto_increment()) {
2981
-                continue;
2982
-            }
2983
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2985
-            if ($prepared_value !== null) {
2986
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2987
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988
-            }
2989
-        }
2990
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2991
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2992
-            // so add the fk to the main table as a column
2993
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2994
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2995
-        }
2996
-        // insert the new entry
2997
-        $result = $this->_do_wpdb_query(
2998
-            'insert',
2999
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3000
-        );
3001
-        if ($result === false) {
3002
-            return false;
3003
-        }
3004
-        // ok, now what do we return for the ID of the newly-inserted thing?
3005
-        if ($this->has_primary_key_field()) {
3006
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3007
-                return $wpdb->insert_id;
3008
-            }
3009
-            // it's not an auto-increment primary key, so
3010
-            // it must have been supplied
3011
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3012
-        }
3013
-        // we can't return a  primary key because there is none. instead return
3014
-        // a unique string indicating this model
3015
-        return $this->get_index_primary_key_string($fields_n_values);
3016
-    }
3017
-
3018
-
3019
-
3020
-    /**
3021
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3022
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3023
-     * and there is no default, we pass it along. WPDB will take care of it)
3024
-     *
3025
-     * @param EE_Model_Field_Base $field_obj
3026
-     * @param array               $fields_n_values
3027
-     * @return mixed string|int|float depending on what the table column will be expecting
3028
-     * @throws EE_Error
3029
-     */
3030
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3031
-    {
3032
-        // if this field doesn't allow nullable, don't allow it
3033
-        if (! $field_obj->is_nullable()
3034
-            && (
3035
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3036
-                || $fields_n_values[ $field_obj->get_name() ] === null
3037
-            )
3038
-        ) {
3039
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3040
-        }
3041
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3042
-            ? $fields_n_values[ $field_obj->get_name() ]
3043
-            : null;
3044
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3045
-    }
3046
-
3047
-
3048
-
3049
-    /**
3050
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3051
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3052
-     * the field's prepare_for_set() method.
3053
-     *
3054
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3055
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3056
-     *                                   top of file)
3057
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3058
-     *                                   $value is a custom selection
3059
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3060
-     */
3061
-    private function _prepare_value_for_use_in_db($value, $field)
3062
-    {
3063
-        if ($field && $field instanceof EE_Model_Field_Base) {
3064
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3065
-            switch ($this->_values_already_prepared_by_model_object) {
3066
-                /** @noinspection PhpMissingBreakStatementInspection */
3067
-                case self::not_prepared_by_model_object:
3068
-                    $value = $field->prepare_for_set($value);
3069
-                // purposefully left out "return"
3070
-                case self::prepared_by_model_object:
3071
-                    /** @noinspection SuspiciousAssignmentsInspection */
3072
-                    $value = $field->prepare_for_use_in_db($value);
3073
-                case self::prepared_for_use_in_db:
3074
-                    // leave the value alone
3075
-            }
3076
-            return $value;
3077
-            // phpcs:enable
3078
-        }
3079
-        return $value;
3080
-    }
3081
-
3082
-
3083
-
3084
-    /**
3085
-     * Returns the main table on this model
3086
-     *
3087
-     * @return EE_Primary_Table
3088
-     * @throws EE_Error
3089
-     */
3090
-    protected function _get_main_table()
3091
-    {
3092
-        foreach ($this->_tables as $table) {
3093
-            if ($table instanceof EE_Primary_Table) {
3094
-                return $table;
3095
-            }
3096
-        }
3097
-        throw new EE_Error(sprintf(__(
3098
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3099
-            'event_espresso'
3100
-        ), get_class($this)));
3101
-    }
3102
-
3103
-
3104
-
3105
-    /**
3106
-     * table
3107
-     * returns EE_Primary_Table table name
3108
-     *
3109
-     * @return string
3110
-     * @throws EE_Error
3111
-     */
3112
-    public function table()
3113
-    {
3114
-        return $this->_get_main_table()->get_table_name();
3115
-    }
3116
-
3117
-
3118
-
3119
-    /**
3120
-     * table
3121
-     * returns first EE_Secondary_Table table name
3122
-     *
3123
-     * @return string
3124
-     */
3125
-    public function second_table()
3126
-    {
3127
-        // grab second table from tables array
3128
-        $second_table = end($this->_tables);
3129
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3130
-    }
3131
-
3132
-
3133
-
3134
-    /**
3135
-     * get_table_obj_by_alias
3136
-     * returns table name given it's alias
3137
-     *
3138
-     * @param string $table_alias
3139
-     * @return EE_Primary_Table | EE_Secondary_Table
3140
-     */
3141
-    public function get_table_obj_by_alias($table_alias = '')
3142
-    {
3143
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3144
-    }
3145
-
3146
-
3147
-
3148
-    /**
3149
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3150
-     *
3151
-     * @return EE_Secondary_Table[]
3152
-     */
3153
-    protected function _get_other_tables()
3154
-    {
3155
-        $other_tables = array();
3156
-        foreach ($this->_tables as $table_alias => $table) {
3157
-            if ($table instanceof EE_Secondary_Table) {
3158
-                $other_tables[ $table_alias ] = $table;
3159
-            }
3160
-        }
3161
-        return $other_tables;
3162
-    }
3163
-
3164
-
3165
-
3166
-    /**
3167
-     * Finds all the fields that correspond to the given table
3168
-     *
3169
-     * @param string $table_alias , array key in EEM_Base::_tables
3170
-     * @return EE_Model_Field_Base[]
3171
-     */
3172
-    public function _get_fields_for_table($table_alias)
3173
-    {
3174
-        return $this->_fields[ $table_alias ];
3175
-    }
3176
-
3177
-
3178
-
3179
-    /**
3180
-     * Recurses through all the where parameters, and finds all the related models we'll need
3181
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3182
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3183
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3184
-     * related Registration, Transaction, and Payment models.
3185
-     *
3186
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3187
-     * @return EE_Model_Query_Info_Carrier
3188
-     * @throws EE_Error
3189
-     */
3190
-    public function _extract_related_models_from_query($query_params)
3191
-    {
3192
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3193
-        if (array_key_exists(0, $query_params)) {
3194
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3195
-        }
3196
-        if (array_key_exists('group_by', $query_params)) {
3197
-            if (is_array($query_params['group_by'])) {
3198
-                $this->_extract_related_models_from_sub_params_array_values(
3199
-                    $query_params['group_by'],
3200
-                    $query_info_carrier,
3201
-                    'group_by'
3202
-                );
3203
-            } elseif (! empty($query_params['group_by'])) {
3204
-                $this->_extract_related_model_info_from_query_param(
3205
-                    $query_params['group_by'],
3206
-                    $query_info_carrier,
3207
-                    'group_by'
3208
-                );
3209
-            }
3210
-        }
3211
-        if (array_key_exists('having', $query_params)) {
3212
-            $this->_extract_related_models_from_sub_params_array_keys(
3213
-                $query_params[0],
3214
-                $query_info_carrier,
3215
-                'having'
3216
-            );
3217
-        }
3218
-        if (array_key_exists('order_by', $query_params)) {
3219
-            if (is_array($query_params['order_by'])) {
3220
-                $this->_extract_related_models_from_sub_params_array_keys(
3221
-                    $query_params['order_by'],
3222
-                    $query_info_carrier,
3223
-                    'order_by'
3224
-                );
3225
-            } elseif (! empty($query_params['order_by'])) {
3226
-                $this->_extract_related_model_info_from_query_param(
3227
-                    $query_params['order_by'],
3228
-                    $query_info_carrier,
3229
-                    'order_by'
3230
-                );
3231
-            }
3232
-        }
3233
-        if (array_key_exists('force_join', $query_params)) {
3234
-            $this->_extract_related_models_from_sub_params_array_values(
3235
-                $query_params['force_join'],
3236
-                $query_info_carrier,
3237
-                'force_join'
3238
-            );
3239
-        }
3240
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3241
-        return $query_info_carrier;
3242
-    }
3243
-
3244
-
3245
-
3246
-    /**
3247
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3248
-     *
3249
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3250
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3251
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3252
-     * @throws EE_Error
3253
-     * @return \EE_Model_Query_Info_Carrier
3254
-     */
3255
-    private function _extract_related_models_from_sub_params_array_keys(
3256
-        $sub_query_params,
3257
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3258
-        $query_param_type
3259
-    ) {
3260
-        if (! empty($sub_query_params)) {
3261
-            $sub_query_params = (array) $sub_query_params;
3262
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3263
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3264
-                $this->_extract_related_model_info_from_query_param(
3265
-                    $param,
3266
-                    $model_query_info_carrier,
3267
-                    $query_param_type
3268
-                );
3269
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3270
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3271
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3272
-                // of array('Registration.TXN_ID'=>23)
3273
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3274
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3275
-                    if (! is_array($possibly_array_of_params)) {
3276
-                        throw new EE_Error(sprintf(
3277
-                            __(
3278
-                                "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3279
-                                "event_espresso"
3280
-                            ),
3281
-                            $param,
3282
-                            $possibly_array_of_params
3283
-                        ));
3284
-                    }
3285
-                    $this->_extract_related_models_from_sub_params_array_keys(
3286
-                        $possibly_array_of_params,
3287
-                        $model_query_info_carrier,
3288
-                        $query_param_type
3289
-                    );
3290
-                } elseif ($query_param_type === 0 // ie WHERE
3291
-                          && is_array($possibly_array_of_params)
3292
-                          && isset($possibly_array_of_params[2])
3293
-                          && $possibly_array_of_params[2] == true
3294
-                ) {
3295
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3296
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3297
-                    // from which we should extract query parameters!
3298
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3299
-                        throw new EE_Error(sprintf(__(
3300
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3301
-                            "event_espresso"
3302
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3303
-                    }
3304
-                    $this->_extract_related_model_info_from_query_param(
3305
-                        $possibly_array_of_params[1],
3306
-                        $model_query_info_carrier,
3307
-                        $query_param_type
3308
-                    );
3309
-                }
3310
-            }
3311
-        }
3312
-        return $model_query_info_carrier;
3313
-    }
3314
-
3315
-
3316
-
3317
-    /**
3318
-     * For extracting related models from forced_joins, where the array values contain the info about what
3319
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
-     *
3321
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3322
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3324
-     * @throws EE_Error
3325
-     * @return \EE_Model_Query_Info_Carrier
3326
-     */
3327
-    private function _extract_related_models_from_sub_params_array_values(
3328
-        $sub_query_params,
3329
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
-        $query_param_type
3331
-    ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3334
-                throw new EE_Error(sprintf(
3335
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
-                    $sub_query_params
3337
-                ));
3338
-            }
3339
-            foreach ($sub_query_params as $param) {
3340
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3341
-                $this->_extract_related_model_info_from_query_param(
3342
-                    $param,
3343
-                    $model_query_info_carrier,
3344
-                    $query_param_type
3345
-                );
3346
-            }
3347
-        }
3348
-        return $model_query_info_carrier;
3349
-    }
3350
-
3351
-
3352
-    /**
3353
-     * Extract all the query parts from  model query params
3354
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3355
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3356
-     * but use them in a different order. Eg, we need to know what models we are querying
3357
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3358
-     * other models before we can finalize the where clause SQL.
3359
-     *
3360
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3361
-     * @throws EE_Error
3362
-     * @return EE_Model_Query_Info_Carrier
3363
-     * @throws ModelConfigurationException
3364
-     */
3365
-    public function _create_model_query_info_carrier($query_params)
3366
-    {
3367
-        if (! is_array($query_params)) {
3368
-            EE_Error::doing_it_wrong(
3369
-                'EEM_Base::_create_model_query_info_carrier',
3370
-                sprintf(
3371
-                    __(
3372
-                        '$query_params should be an array, you passed a variable of type %s',
3373
-                        'event_espresso'
3374
-                    ),
3375
-                    gettype($query_params)
3376
-                ),
3377
-                '4.6.0'
3378
-            );
3379
-            $query_params = array();
3380
-        }
3381
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3382
-        // first check if we should alter the query to account for caps or not
3383
-        // because the caps might require us to do extra joins
3384
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3385
-            $query_params[0] = array_replace_recursive(
3386
-                $query_params[0],
3387
-                $this->caps_where_conditions(
3388
-                    $query_params['caps']
3389
-                )
3390
-            );
3391
-        }
3392
-
3393
-        // check if we should alter the query to remove data related to protected
3394
-        // custom post types
3395
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3396
-            $where_param_key_for_password = $this->modelChainAndPassword();
3397
-            // only include if related to a cpt where no password has been set
3398
-            $query_params[0]['OR*nopassword'] = array(
3399
-                $where_param_key_for_password => '',
3400
-                $where_param_key_for_password . '*' => array('IS_NULL')
3401
-            );
3402
-        }
3403
-        $query_object = $this->_extract_related_models_from_query($query_params);
3404
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3405
-        foreach ($query_params[0] as $key => $value) {
3406
-            if (is_int($key)) {
3407
-                throw new EE_Error(
3408
-                    sprintf(
3409
-                        __(
3410
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3411
-                            "event_espresso"
3412
-                        ),
3413
-                        $key,
3414
-                        var_export($value, true),
3415
-                        var_export($query_params, true),
3416
-                        get_class($this)
3417
-                    )
3418
-                );
3419
-            }
3420
-        }
3421
-        if (array_key_exists('default_where_conditions', $query_params)
3422
-            && ! empty($query_params['default_where_conditions'])
3423
-        ) {
3424
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3425
-        } else {
3426
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3427
-        }
3428
-        $query_params[0] = array_merge(
3429
-            $this->_get_default_where_conditions_for_models_in_query(
3430
-                $query_object,
3431
-                $use_default_where_conditions,
3432
-                $query_params[0]
3433
-            ),
3434
-            $query_params[0]
3435
-        );
3436
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3437
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3438
-        // So we need to setup a subquery and use that for the main join.
3439
-        // Note for now this only works on the primary table for the model.
3440
-        // So for instance, you could set the limit array like this:
3441
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3442
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3443
-            $query_object->set_main_model_join_sql(
3444
-                $this->_construct_limit_join_select(
3445
-                    $query_params['on_join_limit'][0],
3446
-                    $query_params['on_join_limit'][1]
3447
-                )
3448
-            );
3449
-        }
3450
-        // set limit
3451
-        if (array_key_exists('limit', $query_params)) {
3452
-            if (is_array($query_params['limit'])) {
3453
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3454
-                    $e = sprintf(
3455
-                        __(
3456
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3457
-                            "event_espresso"
3458
-                        ),
3459
-                        http_build_query($query_params['limit'])
3460
-                    );
3461
-                    throw new EE_Error($e . "|" . $e);
3462
-                }
3463
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3464
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3465
-            } elseif (! empty($query_params['limit'])) {
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3467
-            }
3468
-        }
3469
-        // set order by
3470
-        if (array_key_exists('order_by', $query_params)) {
3471
-            if (is_array($query_params['order_by'])) {
3472
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3473
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3474
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3475
-                if (array_key_exists('order', $query_params)) {
3476
-                    throw new EE_Error(
3477
-                        sprintf(
3478
-                            __(
3479
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3480
-                                "event_espresso"
3481
-                            ),
3482
-                            get_class($this),
3483
-                            implode(", ", array_keys($query_params['order_by'])),
3484
-                            implode(", ", $query_params['order_by']),
3485
-                            $query_params['order']
3486
-                        )
3487
-                    );
3488
-                }
3489
-                $this->_extract_related_models_from_sub_params_array_keys(
3490
-                    $query_params['order_by'],
3491
-                    $query_object,
3492
-                    'order_by'
3493
-                );
3494
-                // assume it's an array of fields to order by
3495
-                $order_array = array();
3496
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3497
-                    $order = $this->_extract_order($order);
3498
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3499
-                }
3500
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3501
-            } elseif (! empty($query_params['order_by'])) {
3502
-                $this->_extract_related_model_info_from_query_param(
3503
-                    $query_params['order_by'],
3504
-                    $query_object,
3505
-                    'order',
3506
-                    $query_params['order_by']
3507
-                );
3508
-                $order = isset($query_params['order'])
3509
-                    ? $this->_extract_order($query_params['order'])
3510
-                    : 'DESC';
3511
-                $query_object->set_order_by_sql(
3512
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3513
-                );
3514
-            }
3515
-        }
3516
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3517
-        if (! array_key_exists('order_by', $query_params)
3518
-            && array_key_exists('order', $query_params)
3519
-            && ! empty($query_params['order'])
3520
-        ) {
3521
-            $pk_field = $this->get_primary_key_field();
3522
-            $order = $this->_extract_order($query_params['order']);
3523
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3524
-        }
3525
-        // set group by
3526
-        if (array_key_exists('group_by', $query_params)) {
3527
-            if (is_array($query_params['group_by'])) {
3528
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3529
-                $group_by_array = array();
3530
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3531
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3532
-                }
3533
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3534
-            } elseif (! empty($query_params['group_by'])) {
3535
-                $query_object->set_group_by_sql(
3536
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3537
-                );
3538
-            }
3539
-        }
3540
-        // set having
3541
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3542
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3543
-        }
3544
-        // now, just verify they didn't pass anything wack
3545
-        foreach ($query_params as $query_key => $query_value) {
3546
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3547
-                throw new EE_Error(
3548
-                    sprintf(
3549
-                        __(
3550
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3551
-                            'event_espresso'
3552
-                        ),
3553
-                        $query_key,
3554
-                        get_class($this),
3555
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3556
-                        implode(',', $this->_allowed_query_params)
3557
-                    )
3558
-                );
3559
-            }
3560
-        }
3561
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3562
-        if (empty($main_model_join_sql)) {
3563
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3564
-        }
3565
-        return $query_object;
3566
-    }
3567
-
3568
-
3569
-
3570
-    /**
3571
-     * Gets the where conditions that should be imposed on the query based on the
3572
-     * context (eg reading frontend, backend, edit or delete).
3573
-     *
3574
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3575
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3576
-     * @throws EE_Error
3577
-     */
3578
-    public function caps_where_conditions($context = self::caps_read)
3579
-    {
3580
-        EEM_Base::verify_is_valid_cap_context($context);
3581
-        $cap_where_conditions = array();
3582
-        $cap_restrictions = $this->caps_missing($context);
3583
-        /**
3584
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3585
-         */
3586
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3587
-            $cap_where_conditions = array_replace_recursive(
3588
-                $cap_where_conditions,
3589
-                $restriction_if_no_cap->get_default_where_conditions()
3590
-            );
3591
-        }
3592
-        return apply_filters(
3593
-            'FHEE__EEM_Base__caps_where_conditions__return',
3594
-            $cap_where_conditions,
3595
-            $this,
3596
-            $context,
3597
-            $cap_restrictions
3598
-        );
3599
-    }
3600
-
3601
-
3602
-
3603
-    /**
3604
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3605
-     * otherwise throws an exception
3606
-     *
3607
-     * @param string $should_be_order_string
3608
-     * @return string either ASC, asc, DESC or desc
3609
-     * @throws EE_Error
3610
-     */
3611
-    private function _extract_order($should_be_order_string)
3612
-    {
3613
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3614
-            return $should_be_order_string;
3615
-        }
3616
-        throw new EE_Error(
3617
-            sprintf(
3618
-                __(
3619
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3620
-                    "event_espresso"
3621
-                ),
3622
-                get_class($this),
3623
-                $should_be_order_string
3624
-            )
3625
-        );
3626
-    }
3627
-
3628
-
3629
-
3630
-    /**
3631
-     * Looks at all the models which are included in this query, and asks each
3632
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3633
-     * so they can be merged
3634
-     *
3635
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3636
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3637
-     *                                                                  'none' means NO default where conditions will
3638
-     *                                                                  be used AT ALL during this query.
3639
-     *                                                                  'other_models_only' means default where
3640
-     *                                                                  conditions from other models will be used, but
3641
-     *                                                                  not for this primary model. 'all', the default,
3642
-     *                                                                  means default where conditions will apply as
3643
-     *                                                                  normal
3644
-     * @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
3645
-     * @throws EE_Error
3646
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3647
-     */
3648
-    private function _get_default_where_conditions_for_models_in_query(
3649
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3650
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3651
-        $where_query_params = array()
3652
-    ) {
3653
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3654
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3655
-            throw new EE_Error(sprintf(
3656
-                __(
3657
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3658
-                    "event_espresso"
3659
-                ),
3660
-                $use_default_where_conditions,
3661
-                implode(", ", $allowed_used_default_where_conditions_values)
3662
-            ));
3663
-        }
3664
-        $universal_query_params = array();
3665
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3666
-            $universal_query_params = $this->_get_default_where_conditions();
3667
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3668
-            $universal_query_params = $this->_get_minimum_where_conditions();
3669
-        }
3670
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3671
-            $related_model = $this->get_related_model_obj($model_name);
3672
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3673
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3674
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3675
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3676
-            } else {
3677
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3678
-                continue;
3679
-            }
3680
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3681
-                $related_model_universal_where_params,
3682
-                $where_query_params,
3683
-                $related_model,
3684
-                $model_relation_path
3685
-            );
3686
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3687
-                $universal_query_params,
3688
-                $overrides
3689
-            );
3690
-        }
3691
-        return $universal_query_params;
3692
-    }
3693
-
3694
-
3695
-
3696
-    /**
3697
-     * Determines whether or not we should use default where conditions for the model in question
3698
-     * (this model, or other related models).
3699
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3700
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3701
-     * We should use default where conditions on related models when they requested to use default where conditions
3702
-     * on all models, or specifically just on other related models
3703
-     * @param      $default_where_conditions_value
3704
-     * @param bool $for_this_model false means this is for OTHER related models
3705
-     * @return bool
3706
-     */
3707
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3708
-    {
3709
-        return (
3710
-                   $for_this_model
3711
-                   && in_array(
3712
-                       $default_where_conditions_value,
3713
-                       array(
3714
-                           EEM_Base::default_where_conditions_all,
3715
-                           EEM_Base::default_where_conditions_this_only,
3716
-                           EEM_Base::default_where_conditions_minimum_others,
3717
-                       ),
3718
-                       true
3719
-                   )
3720
-               )
3721
-               || (
3722
-                   ! $for_this_model
3723
-                   && in_array(
3724
-                       $default_where_conditions_value,
3725
-                       array(
3726
-                           EEM_Base::default_where_conditions_all,
3727
-                           EEM_Base::default_where_conditions_others_only,
3728
-                       ),
3729
-                       true
3730
-                   )
3731
-               );
3732
-    }
3733
-
3734
-    /**
3735
-     * Determines whether or not we should use default minimum conditions for the model in question
3736
-     * (this model, or other related models).
3737
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3738
-     * where conditions.
3739
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3740
-     * on this model or others
3741
-     * @param      $default_where_conditions_value
3742
-     * @param bool $for_this_model false means this is for OTHER related models
3743
-     * @return bool
3744
-     */
3745
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3746
-    {
3747
-        return (
3748
-                   $for_this_model
3749
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3750
-               )
3751
-               || (
3752
-                   ! $for_this_model
3753
-                   && in_array(
3754
-                       $default_where_conditions_value,
3755
-                       array(
3756
-                           EEM_Base::default_where_conditions_minimum_others,
3757
-                           EEM_Base::default_where_conditions_minimum_all,
3758
-                       ),
3759
-                       true
3760
-                   )
3761
-               );
3762
-    }
3763
-
3764
-
3765
-    /**
3766
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3767
-     * then we also add a special where condition which allows for that model's primary key
3768
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3769
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3770
-     *
3771
-     * @param array    $default_where_conditions
3772
-     * @param array    $provided_where_conditions
3773
-     * @param EEM_Base $model
3774
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3775
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3776
-     * @throws EE_Error
3777
-     */
3778
-    private function _override_defaults_or_make_null_friendly(
3779
-        $default_where_conditions,
3780
-        $provided_where_conditions,
3781
-        $model,
3782
-        $model_relation_path
3783
-    ) {
3784
-        $null_friendly_where_conditions = array();
3785
-        $none_overridden = true;
3786
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3787
-        foreach ($default_where_conditions as $key => $val) {
3788
-            if (isset($provided_where_conditions[ $key ])) {
3789
-                $none_overridden = false;
3790
-            } else {
3791
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3792
-            }
3793
-        }
3794
-        if ($none_overridden && $default_where_conditions) {
3795
-            if ($model->has_primary_key_field()) {
3796
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3797
-                                                                                . "."
3798
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3799
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	private static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					__(
561
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							__(
680
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (isset($query_params['limit'])
872
+			&& ! isset($query_params['group_by'])
873
+		) {
874
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
+		}
876
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
+	}
878
+
879
+
880
+
881
+	/**
882
+	 * Modifies the query parameters so we only get back model objects
883
+	 * that "belong" to the current user
884
+	 *
885
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 */
888
+	public function alter_query_params_to_only_include_mine($query_params = array())
889
+	{
890
+		$wp_user_field_name = $this->wp_user_field_name();
891
+		if ($wp_user_field_name) {
892
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
+		}
894
+		return $query_params;
895
+	}
896
+
897
+
898
+
899
+	/**
900
+	 * Returns the name of the field's name that points to the WP_User table
901
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
+	 * foreign key to the WP_User table)
903
+	 *
904
+	 * @return string|boolean string on success, boolean false when there is no
905
+	 * foreign key to the WP_User table
906
+	 */
907
+	public function wp_user_field_name()
908
+	{
909
+		try {
910
+			if (! empty($this->_model_chain_to_wp_user)) {
911
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
+				$last_model_name = end($models_to_follow_to_wp_users);
913
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
+			} else {
916
+				$model_with_fk_to_wp_users = $this;
917
+				$model_chain_to_wp_user = '';
918
+			}
919
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
921
+		} catch (EE_Error $e) {
922
+			return false;
923
+		}
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
930
+	 * (or transiently-related model) has a foreign key to the wp_users table;
931
+	 * useful for finding if model objects of this type are 'owned' by the current user.
932
+	 * This is an empty string when the foreign key is on this model and when it isn't,
933
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
934
+	 * (or transiently-related model)
935
+	 *
936
+	 * @return string
937
+	 */
938
+	public function model_chain_to_wp_user()
939
+	{
940
+		return $this->_model_chain_to_wp_user;
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
+	 * like how registrations don't have a foreign key to wp_users, but the
948
+	 * events they are for are), or is unrelated to wp users.
949
+	 * generally available
950
+	 *
951
+	 * @return boolean
952
+	 */
953
+	public function is_owned()
954
+	{
955
+		if ($this->model_chain_to_wp_user()) {
956
+			return true;
957
+		}
958
+		try {
959
+			$this->get_foreign_key_to('WP_User');
960
+			return true;
961
+		} catch (EE_Error $e) {
962
+			return false;
963
+		}
964
+	}
965
+
966
+
967
+	/**
968
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
+	 * the model)
971
+	 *
972
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
976
+	 *                                  override this and set the select to "*", or a specific column name, like
977
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
+	 *                                  the aliases used to refer to this selection, and values are to be
980
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
+	 * @throws EE_Error
984
+	 * @throws InvalidArgumentException
985
+	 */
986
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
+	{
988
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
+		;
990
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
991
+		$select_expressions = $columns_to_select === null
992
+			? $this->_construct_default_select_sql($model_query_info)
993
+			: '';
994
+		if ($this->_custom_selections instanceof CustomSelects) {
995
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
+			$select_expressions .= $select_expressions
997
+				? ', ' . $custom_expressions
998
+				: $custom_expressions;
999
+		}
1000
+
1001
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
+	 * method of including extra select information.
1010
+	 *
1011
+	 * @param array             $query_params
1012
+	 * @param null|array|string $columns_to_select
1013
+	 * @return null|CustomSelects
1014
+	 * @throws InvalidArgumentException
1015
+	 */
1016
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
+	{
1018
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
+			return null;
1020
+		}
1021
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
+		return new CustomSelects($selects);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1030
+	 * but you can use the model query params to more easily
1031
+	 * take care of joins, field preparation etc.
1032
+	 *
1033
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
+	}
1050
+
1051
+
1052
+
1053
+	/**
1054
+	 * For creating a custom select statement
1055
+	 *
1056
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
+	 *                                 SQL, and 1=>is the datatype
1059
+	 * @throws EE_Error
1060
+	 * @return string
1061
+	 */
1062
+	private function _construct_select_from_input($columns_to_select)
1063
+	{
1064
+		if (is_array($columns_to_select)) {
1065
+			$select_sql_array = array();
1066
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
+					throw new EE_Error(
1069
+						sprintf(
1070
+							__(
1071
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
+								'event_espresso'
1073
+							),
1074
+							$selection_and_datatype,
1075
+							$alias
1076
+						)
1077
+					);
1078
+				}
1079
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
+					throw new EE_Error(
1081
+						sprintf(
1082
+							esc_html__(
1083
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
+								'event_espresso'
1085
+							),
1086
+							$selection_and_datatype[1],
1087
+							$selection_and_datatype[0],
1088
+							$alias,
1089
+							implode(', ', $this->_valid_wpdb_data_types)
1090
+						)
1091
+					);
1092
+				}
1093
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
+			}
1095
+			$columns_to_select_string = implode(', ', $select_sql_array);
1096
+		} else {
1097
+			$columns_to_select_string = $columns_to_select;
1098
+		}
1099
+		return $columns_to_select_string;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
+	 *
1107
+	 * @return string
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function primary_key_name()
1111
+	{
1112
+		return $this->get_primary_key_field()->get_name();
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
+	 * If there is no primary key on this model, $id is treated as primary key string
1119
+	 *
1120
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1121
+	 * @return EE_Base_Class
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function get_one_by_ID($id)
1125
+	{
1126
+		if ($this->get_from_entity_map($id)) {
1127
+			return $this->get_from_entity_map($id);
1128
+		}
1129
+		$model_object = $this->get_one(
1130
+			$this->alter_query_params_to_restrict_by_ID(
1131
+				$id,
1132
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
+			)
1134
+		);
1135
+		$className = $this->_get_class_name();
1136
+		if ($model_object instanceof $className) {
1137
+			// make sure valid objects get added to the entity map
1138
+			// so that the next call to this method doesn't trigger another trip to the db
1139
+			$this->add_to_entity_map($model_object);
1140
+		}
1141
+		return $model_object;
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Alters query parameters to only get items with this ID are returned.
1148
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
+	 * or could just be a simple primary key ID
1150
+	 *
1151
+	 * @param int   $id
1152
+	 * @param array $query_params
1153
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
+	{
1158
+		if (! isset($query_params[0])) {
1159
+			$query_params[0] = array();
1160
+		}
1161
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1162
+		if ($conditions_from_id === null) {
1163
+			$query_params[0][ $this->primary_key_name() ] = $id;
1164
+		} else {
1165
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1166
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
+		}
1168
+		return $query_params;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
+	 * array. If no item is found, null is returned.
1176
+	 *
1177
+	 * @param array $query_params like EEM_Base's $query_params variable.
1178
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
+	 * @throws EE_Error
1180
+	 */
1181
+	public function get_one($query_params = array())
1182
+	{
1183
+		if (! is_array($query_params)) {
1184
+			EE_Error::doing_it_wrong(
1185
+				'EEM_Base::get_one',
1186
+				sprintf(
1187
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
+					gettype($query_params)
1189
+				),
1190
+				'4.6.0'
1191
+			);
1192
+			$query_params = array();
1193
+		}
1194
+		$query_params['limit'] = 1;
1195
+		$items = $this->get_all($query_params);
1196
+		if (empty($items)) {
1197
+			return null;
1198
+		}
1199
+		return array_shift($items);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next x number of items in sequence from the given value as
1206
+	 * found in the database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param int   $limit                  How many to return.
1212
+	 * @param array $query_params           Extra conditions on the query.
1213
+	 * @param null  $columns_to_select      If left null, then an array of
1214
+	 *                                      EE_Base_Class objects is returned,
1215
+	 *                                      otherwise you can indicate just the
1216
+	 *                                      columns you want returned.
1217
+	 * @return EE_Base_Class[]|array
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function next_x(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$limit = 1,
1224
+		$query_params = array(),
1225
+		$columns_to_select = null
1226
+	) {
1227
+		return $this->_get_consecutive(
1228
+			$current_field_value,
1229
+			'>',
1230
+			$field_to_order_by,
1231
+			$limit,
1232
+			$query_params,
1233
+			$columns_to_select
1234
+		);
1235
+	}
1236
+
1237
+
1238
+
1239
+	/**
1240
+	 * Returns the previous x number of items in sequence from the given value
1241
+	 * as found in the database matching the given query conditions.
1242
+	 *
1243
+	 * @param mixed $current_field_value    Value used for the reference point.
1244
+	 * @param null  $field_to_order_by      What field is used for the
1245
+	 *                                      reference point.
1246
+	 * @param int   $limit                  How many to return.
1247
+	 * @param array $query_params           Extra conditions on the query.
1248
+	 * @param null  $columns_to_select      If left null, then an array of
1249
+	 *                                      EE_Base_Class objects is returned,
1250
+	 *                                      otherwise you can indicate just the
1251
+	 *                                      columns you want returned.
1252
+	 * @return EE_Base_Class[]|array
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function previous_x(
1256
+		$current_field_value,
1257
+		$field_to_order_by = null,
1258
+		$limit = 1,
1259
+		$query_params = array(),
1260
+		$columns_to_select = null
1261
+	) {
1262
+		return $this->_get_consecutive(
1263
+			$current_field_value,
1264
+			'<',
1265
+			$field_to_order_by,
1266
+			$limit,
1267
+			$query_params,
1268
+			$columns_to_select
1269
+		);
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Returns the next item in sequence from the given value as found in the
1276
+	 * database matching the given query conditions.
1277
+	 *
1278
+	 * @param mixed $current_field_value    Value used for the reference point.
1279
+	 * @param null  $field_to_order_by      What field is used for the
1280
+	 *                                      reference point.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
+	 *                                      object is returned, otherwise you
1284
+	 *                                      can indicate just the columns you
1285
+	 *                                      want and a single array indexed by
1286
+	 *                                      the columns will be returned.
1287
+	 * @return EE_Base_Class|null|array()
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function next(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$query_params = array(),
1294
+		$columns_to_select = null
1295
+	) {
1296
+		$results = $this->_get_consecutive(
1297
+			$current_field_value,
1298
+			'>',
1299
+			$field_to_order_by,
1300
+			1,
1301
+			$query_params,
1302
+			$columns_to_select
1303
+		);
1304
+		return empty($results) ? null : reset($results);
1305
+	}
1306
+
1307
+
1308
+
1309
+	/**
1310
+	 * Returns the previous item in sequence from the given value as found in
1311
+	 * the database matching the given query conditions.
1312
+	 *
1313
+	 * @param mixed $current_field_value    Value used for the reference point.
1314
+	 * @param null  $field_to_order_by      What field is used for the
1315
+	 *                                      reference point.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
+	 *                                      object is returned, otherwise you
1319
+	 *                                      can indicate just the columns you
1320
+	 *                                      want and a single array indexed by
1321
+	 *                                      the columns will be returned.
1322
+	 * @return EE_Base_Class|null|array()
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function previous(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$query_params = array(),
1329
+		$columns_to_select = null
1330
+	) {
1331
+		$results = $this->_get_consecutive(
1332
+			$current_field_value,
1333
+			'<',
1334
+			$field_to_order_by,
1335
+			1,
1336
+			$query_params,
1337
+			$columns_to_select
1338
+		);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__(
1373
+						'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1374
+						'event_espresso'
1375
+					));
1376
+				}
1377
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
+				return array();
1379
+			}
1380
+		}
1381
+		if (! is_array($query_params)) {
1382
+			EE_Error::doing_it_wrong(
1383
+				'EEM_Base::_get_consecutive',
1384
+				sprintf(
1385
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
+					gettype($query_params)
1387
+				),
1388
+				'4.6.0'
1389
+			);
1390
+			$query_params = array();
1391
+		}
1392
+		// let's add the where query param for consecutive look up.
1393
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
+		$query_params['limit'] = $limit;
1395
+		// set direction
1396
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
+		$query_params['order_by'] = $operand === '>'
1398
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
+		if (empty($columns_to_select)) {
1402
+			return $this->get_all($query_params);
1403
+		}
1404
+		// getting just the fields
1405
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
+	}
1407
+
1408
+
1409
+
1410
+	/**
1411
+	 * This sets the _timezone property after model object has been instantiated.
1412
+	 *
1413
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
+	 */
1415
+	public function set_timezone($timezone)
1416
+	{
1417
+		if ($timezone !== null) {
1418
+			$this->_timezone = $timezone;
1419
+		}
1420
+		// note we need to loop through relations and set the timezone on those objects as well.
1421
+		foreach ($this->_model_relations as $relation) {
1422
+			$relation->set_timezone($timezone);
1423
+		}
1424
+		// and finally we do the same for any datetime fields
1425
+		foreach ($this->_fields as $field) {
1426
+			if ($field instanceof EE_Datetime_Field) {
1427
+				$field->set_timezone($timezone);
1428
+			}
1429
+		}
1430
+	}
1431
+
1432
+
1433
+
1434
+	/**
1435
+	 * This just returns whatever is set for the current timezone.
1436
+	 *
1437
+	 * @access public
1438
+	 * @return string
1439
+	 */
1440
+	public function get_timezone()
1441
+	{
1442
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
+		if (empty($this->_timezone)) {
1444
+			foreach ($this->_fields as $field) {
1445
+				if ($field instanceof EE_Datetime_Field) {
1446
+					$this->set_timezone($field->get_timezone());
1447
+					break;
1448
+				}
1449
+			}
1450
+		}
1451
+		// if timezone STILL empty then return the default timezone for the site.
1452
+		if (empty($this->_timezone)) {
1453
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
+		}
1455
+		return $this->_timezone;
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This returns the date formats set for the given field name and also ensures that
1462
+	 * $this->_timezone property is set correctly.
1463
+	 *
1464
+	 * @since 4.6.x
1465
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1466
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
+	 * @return array formats in an array with the date format first, and the time format last.
1469
+	 */
1470
+	public function get_formats_for($field_name, $pretty = false)
1471
+	{
1472
+		$field_settings = $this->field_settings_for($field_name);
1473
+		// if not a valid EE_Datetime_Field then throw error
1474
+		if (! $field_settings instanceof EE_Datetime_Field) {
1475
+			throw new EE_Error(sprintf(__(
1476
+				'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1477
+				'event_espresso'
1478
+			), $field_name));
1479
+		}
1480
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
+		// the field.
1482
+		$this->_timezone = $field_settings->get_timezone();
1483
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * This returns the current time in a format setup for a query on this model.
1490
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
+	 * it will return:
1492
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
+	 *  NOW
1494
+	 *  - or a unix timestamp (equivalent to time())
1495
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
+	 * @since 4.6.x
1499
+	 * @param string $field_name       The field the current time is needed for.
1500
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
+	 *                                 formatted string matching the set format for the field in the set timezone will
1502
+	 *                                 be returned.
1503
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
+	 *                                 exception is triggered.
1507
+	 */
1508
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
+	{
1510
+		$formats = $this->get_formats_for($field_name);
1511
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
+		if ($timestamp) {
1513
+			return $DateTime->format('U');
1514
+		}
1515
+		// not returning timestamp, so return formatted string in timezone.
1516
+		switch ($what) {
1517
+			case 'time':
1518
+				return $DateTime->format($formats[1]);
1519
+				break;
1520
+			case 'date':
1521
+				return $DateTime->format($formats[0]);
1522
+				break;
1523
+			default:
1524
+				return $DateTime->format(implode(' ', $formats));
1525
+				break;
1526
+		}
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
+	 * for the model are.  Returns a DateTime object.
1534
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
+	 * ignored.
1537
+	 *
1538
+	 * @param string $field_name      The field being setup.
1539
+	 * @param string $timestring      The date time string being used.
1540
+	 * @param string $incoming_format The format for the time string.
1541
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
+	 *                                format is
1544
+	 *                                'U', this is ignored.
1545
+	 * @return DateTime
1546
+	 * @throws EE_Error
1547
+	 */
1548
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
+	{
1550
+		// just using this to ensure the timezone is set correctly internally
1551
+		$this->get_formats_for($field_name);
1552
+		// load EEH_DTT_Helper
1553
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
+	 *
1564
+	 * @return EE_Table_Base[]
1565
+	 */
1566
+	public function get_tables()
1567
+	{
1568
+		return $this->_tables;
1569
+	}
1570
+
1571
+
1572
+
1573
+	/**
1574
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
+	 * model object with EVT_ID = 1
1580
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
+	 * are not specified)
1585
+	 *
1586
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1591
+	 *                                         ID=34, we'd use this method as follows:
1592
+	 *                                         EEM_Transaction::instance()->update(
1593
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
+	 *                                         array(array('TXN_ID'=>34)));
1595
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
+	 *                                         TRUE, it is assumed that you've already called
1602
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
+	 *                                         malicious javascript. However, if
1604
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
+	 *                                         and every other field, before insertion. We provide this parameter
1607
+	 *                                         because model objects perform their prepare_for_set function on all
1608
+	 *                                         their values, and so don't need to be called again (and in many cases,
1609
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
+	 *                                         prepare_for_set method...)
1611
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
+	 *                                         in this model's entity map according to $fields_n_values that match
1613
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1614
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1615
+	 *                                         could get out-of-sync with the database
1616
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
+	 *                                         bad)
1619
+	 * @throws EE_Error
1620
+	 */
1621
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
+	{
1623
+		if (! is_array($query_params)) {
1624
+			EE_Error::doing_it_wrong(
1625
+				'EEM_Base::update',
1626
+				sprintf(
1627
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
+					gettype($query_params)
1629
+				),
1630
+				'4.6.0'
1631
+			);
1632
+			$query_params = array();
1633
+		}
1634
+		/**
1635
+		 * Action called before a model update call has been made.
1636
+		 *
1637
+		 * @param EEM_Base $model
1638
+		 * @param array    $fields_n_values the updated fields and their new values
1639
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
+		 */
1641
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
+		/**
1643
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1644
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1645
+		 *
1646
+		 * @param array    $fields_n_values fields and their new values
1647
+		 * @param EEM_Base $model           the model being queried
1648
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
+		 */
1650
+		$fields_n_values = (array) apply_filters(
1651
+			'FHEE__EEM_Base__update__fields_n_values',
1652
+			$fields_n_values,
1653
+			$this,
1654
+			$query_params
1655
+		);
1656
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
+		// to do that, for each table, verify that it's PK isn't null.
1658
+		$tables = $this->get_tables();
1659
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
+		// NOTE: we should make this code more efficient by NOT querying twice
1661
+		// before the real update, but that needs to first go through ALPHA testing
1662
+		// as it's dangerous. says Mike August 8 2014
1663
+		// we want to make sure the default_where strategy is ignored
1664
+		$this->_ignore_where_strategy = true;
1665
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
+		foreach ($wpdb_select_results as $wpdb_result) {
1667
+			// type cast stdClass as array
1668
+			$wpdb_result = (array) $wpdb_result;
1669
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
+			if ($this->has_primary_key_field()) {
1671
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
+			} else {
1673
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1674
+				$main_table_pk_value = null;
1675
+			}
1676
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1677
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1678
+			if (count($tables) > 1) {
1679
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
+				// in that table, and so we'll want to insert one
1681
+				foreach ($tables as $table_obj) {
1682
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
+					// if there is no private key for this table on the results, it means there's no entry
1684
+					// in this table, right? so insert a row in the current table, using any fields available
1685
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+						   && $wpdb_result[ $this_table_pk_column ])
1687
+					) {
1688
+						$success = $this->_insert_into_specific_table(
1689
+							$table_obj,
1690
+							$fields_n_values,
1691
+							$main_table_pk_value
1692
+						);
1693
+						// if we died here, report the error
1694
+						if (! $success) {
1695
+							return false;
1696
+						}
1697
+					}
1698
+				}
1699
+			}
1700
+			//              //and now check that if we have cached any models by that ID on the model, that
1701
+			//              //they also get updated properly
1702
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
+			//              if( $model_object ){
1704
+			//                  foreach( $fields_n_values as $field => $value ){
1705
+			//                      $model_object->set($field, $value);
1706
+			// let's make sure default_where strategy is followed now
1707
+			$this->_ignore_where_strategy = false;
1708
+		}
1709
+		// if we want to keep model objects in sync, AND
1710
+		// if this wasn't called from a model object (to update itself)
1711
+		// then we want to make sure we keep all the existing
1712
+		// model objects in sync with the db
1713
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
+			if ($this->has_primary_key_field()) {
1715
+				$model_objs_affected_ids = $this->get_col($query_params);
1716
+			} else {
1717
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
+				$model_objs_affected_ids = array();
1720
+				foreach ($models_affected_key_columns as $row) {
1721
+					$combined_index_key = $this->get_index_primary_key_string($row);
1722
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
+				}
1724
+			}
1725
+			if (! $model_objs_affected_ids) {
1726
+				// wait wait wait- if nothing was affected let's stop here
1727
+				return 0;
1728
+			}
1729
+			foreach ($model_objs_affected_ids as $id) {
1730
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
+				if ($model_obj_in_entity_map) {
1732
+					foreach ($fields_n_values as $field => $new_value) {
1733
+						$model_obj_in_entity_map->set($field, $new_value);
1734
+					}
1735
+				}
1736
+			}
1737
+			// if there is a primary key on this model, we can now do a slight optimization
1738
+			if ($this->has_primary_key_field()) {
1739
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
+				$query_params = array(
1741
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
+					'limit'                    => count($model_objs_affected_ids),
1743
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
+				);
1745
+			}
1746
+		}
1747
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
+		$SQL = "UPDATE "
1749
+			   . $model_query_info->get_full_join_sql()
1750
+			   . " SET "
1751
+			   . $this->_construct_update_sql($fields_n_values)
1752
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
+		/**
1755
+		 * Action called after a model update call has been made.
1756
+		 *
1757
+		 * @param EEM_Base $model
1758
+		 * @param array    $fields_n_values the updated fields and their new values
1759
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
+		 * @param int      $rows_affected
1761
+		 */
1762
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
+		return $rows_affected;// how many supposedly got updated
1764
+	}
1765
+
1766
+
1767
+
1768
+	/**
1769
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
+	 * are teh values of the field specified (or by default the primary key field)
1771
+	 * that matched the query params. Note that you should pass the name of the
1772
+	 * model FIELD, not the database table's column name.
1773
+	 *
1774
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
+	 * @param string $field_to_select
1776
+	 * @return array just like $wpdb->get_col()
1777
+	 * @throws EE_Error
1778
+	 */
1779
+	public function get_col($query_params = array(), $field_to_select = null)
1780
+	{
1781
+		if ($field_to_select) {
1782
+			$field = $this->field_settings_for($field_to_select);
1783
+		} elseif ($this->has_primary_key_field()) {
1784
+			$field = $this->get_primary_key_field();
1785
+		} else {
1786
+			// no primary key, just grab the first column
1787
+			$field = reset($this->field_settings());
1788
+		}
1789
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
+		$select_expressions = $field->get_qualified_column();
1791
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
+		return $this->_do_wpdb_query('get_col', array($SQL));
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Returns a single column value for a single row from the database
1799
+	 *
1800
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
+	 * @param string $field_to_select @see EEM_Base::get_col()
1802
+	 * @return string
1803
+	 * @throws EE_Error
1804
+	 */
1805
+	public function get_var($query_params = array(), $field_to_select = null)
1806
+	{
1807
+		$query_params['limit'] = 1;
1808
+		$col = $this->get_col($query_params, $field_to_select);
1809
+		if (! empty($col)) {
1810
+			return reset($col);
1811
+		}
1812
+		return null;
1813
+	}
1814
+
1815
+
1816
+
1817
+	/**
1818
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
+	 * injection, but currently no further filtering is done
1821
+	 *
1822
+	 * @global      $wpdb
1823
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
+	 *                               be updated to in the DB
1825
+	 * @return string of SQL
1826
+	 * @throws EE_Error
1827
+	 */
1828
+	public function _construct_update_sql($fields_n_values)
1829
+	{
1830
+		/** @type WPDB $wpdb */
1831
+		global $wpdb;
1832
+		$cols_n_values = array();
1833
+		foreach ($fields_n_values as $field_name => $value) {
1834
+			$field_obj = $this->field_settings_for($field_name);
1835
+			// if the value is NULL, we want to assign the value to that.
1836
+			// wpdb->prepare doesn't really handle that properly
1837
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
+			$value_sql = $prepared_value === null ? 'NULL'
1839
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
+		}
1842
+		return implode(",", $cols_n_values);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Performs a HARD delete, meaning the database row should always be removed,
1850
+	 * not just have a flag field on it switched
1851
+	 * Wrapper for EEM_Base::delete_permanently()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @param boolean $allow_blocking
1855
+	 * @return int the number of rows deleted
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
+	{
1860
+		return $this->delete_permanently(
1861
+			array(
1862
+				array($this->get_primary_key_field()->get_name() => $id),
1863
+				'limit' => 1,
1864
+			),
1865
+			$allow_blocking
1866
+		);
1867
+	}
1868
+
1869
+
1870
+
1871
+	/**
1872
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
+	 * Wrapper for EEM_Base::delete()
1874
+	 *
1875
+	 * @param mixed $id
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int the number of rows deleted
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function delete_by_ID($id, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete(
1883
+			array(
1884
+				array($this->get_primary_key_field()->get_name() => $id),
1885
+				'limit' => 1,
1886
+			),
1887
+			$allow_blocking
1888
+		);
1889
+	}
1890
+
1891
+
1892
+
1893
+	/**
1894
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1895
+	 * meaning if the model has a field that indicates its been "trashed" or
1896
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1897
+	 *
1898
+	 * @see EEM_Base::delete_permanently
1899
+	 * @param array   $query_params
1900
+	 * @param boolean $allow_blocking
1901
+	 * @return int how many rows got deleted
1902
+	 * @throws EE_Error
1903
+	 */
1904
+	public function delete($query_params, $allow_blocking = true)
1905
+	{
1906
+		return $this->delete_permanently($query_params, $allow_blocking);
1907
+	}
1908
+
1909
+
1910
+
1911
+	/**
1912
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1913
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
+	 * as archived, not actually deleted
1915
+	 *
1916
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1920
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
+	 *                                DB
1922
+	 * @return int how many rows got deleted
1923
+	 * @throws EE_Error
1924
+	 */
1925
+	public function delete_permanently($query_params, $allow_blocking = true)
1926
+	{
1927
+		/**
1928
+		 * Action called just before performing a real deletion query. You can use the
1929
+		 * model and its $query_params to find exactly which items will be deleted
1930
+		 *
1931
+		 * @param EEM_Base $model
1932
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1934
+		 *                                 to block (prevent) this deletion
1935
+		 */
1936
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
+		// some MySQL databases may be running safe mode, which may restrict
1938
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
+		// to delete them
1941
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
+			$columns_and_ids_for_deleting
1945
+		);
1946
+		/**
1947
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1948
+		 *
1949
+		 * @param EEM_Base $this  The model instance being acted on.
1950
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
+		 *                                                  derived from the incoming query parameters.
1954
+		 *                                                  @see details on the structure of this array in the phpdocs
1955
+		 *                                                  for the `_get_ids_for_delete_method`
1956
+		 *
1957
+		 */
1958
+		do_action(
1959
+			'AHEE__EEM_Base__delete__before_query',
1960
+			$this,
1961
+			$query_params,
1962
+			$allow_blocking,
1963
+			$columns_and_ids_for_deleting
1964
+		);
1965
+		if ($deletion_where_query_part) {
1966
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
+			$table_aliases = array_keys($this->_tables);
1968
+			$SQL = "DELETE "
1969
+				   . implode(", ", $table_aliases)
1970
+				   . " FROM "
1971
+				   . $model_query_info->get_full_join_sql()
1972
+				   . " WHERE "
1973
+				   . $deletion_where_query_part;
1974
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
+		} else {
1976
+			$rows_deleted = 0;
1977
+		}
1978
+
1979
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
+		// there was no error with the delete query.
1981
+		if ($this->has_primary_key_field()
1982
+			&& $rows_deleted !== false
1983
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
+		) {
1985
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
+			foreach ($ids_for_removal as $id) {
1987
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
+				}
1990
+			}
1991
+
1992
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
+			// (although it is possible).
1996
+			// Note this can be skipped by using the provided filter and returning false.
1997
+			if (apply_filters(
1998
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
+				! $this instanceof EEM_Extra_Meta,
2000
+				$this
2001
+			)) {
2002
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2003
+					0 => array(
2004
+						'EXM_type' => $this->get_this_model_name(),
2005
+						'OBJ_ID'   => array(
2006
+							'IN',
2007
+							$ids_for_removal
2008
+						)
2009
+					)
2010
+				));
2011
+			}
2012
+		}
2013
+
2014
+		/**
2015
+		 * Action called just after performing a real deletion query. Although at this point the
2016
+		 * items should have been deleted
2017
+		 *
2018
+		 * @param EEM_Base $model
2019
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
+		 * @param int      $rows_deleted
2021
+		 */
2022
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
+		return $rows_deleted;// how many supposedly got deleted
2024
+	}
2025
+
2026
+
2027
+
2028
+	/**
2029
+	 * Checks all the relations that throw error messages when there are blocking related objects
2030
+	 * for related model objects. If there are any related model objects on those relations,
2031
+	 * adds an EE_Error, and return true
2032
+	 *
2033
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2034
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
+	 *                                                 should be ignored when determining whether there are related
2036
+	 *                                                 model objects which block this model object's deletion. Useful
2037
+	 *                                                 if you know A is related to B and are considering deleting A,
2038
+	 *                                                 but want to see if A has any other objects blocking its deletion
2039
+	 *                                                 before removing the relation between A and B
2040
+	 * @return boolean
2041
+	 * @throws EE_Error
2042
+	 */
2043
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
+	{
2045
+		// first, if $ignore_this_model_obj was supplied, get its model
2046
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
+			$ignored_model = $ignore_this_model_obj->get_model();
2048
+		} else {
2049
+			$ignored_model = null;
2050
+		}
2051
+		// now check all the relations of $this_model_obj_or_id and see if there
2052
+		// are any related model objects blocking it?
2053
+		$is_blocked = false;
2054
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2056
+				// if $ignore_this_model_obj was supplied, then for the query
2057
+				// on that model needs to be told to ignore $ignore_this_model_obj
2058
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
+						array(
2061
+							$ignored_model->get_primary_key_field()->get_name() => array(
2062
+								'!=',
2063
+								$ignore_this_model_obj->ID(),
2064
+							),
2065
+						),
2066
+					));
2067
+				} else {
2068
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
+				}
2070
+				if ($related_model_objects) {
2071
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
+					$is_blocked = true;
2073
+				}
2074
+			}
2075
+		}
2076
+		return $is_blocked;
2077
+	}
2078
+
2079
+
2080
+	/**
2081
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
+	 * @param array $row_results_for_deleting
2083
+	 * @param bool  $allow_blocking
2084
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
+	 *                 deleted. Example:
2088
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2089
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
+	 *                 where each element is a group of columns and values that get deleted. Example:
2091
+	 *                      array(
2092
+	 *                          0 => array(
2093
+	 *                              'Term_Relationship.object_id' => 1
2094
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2095
+	 *                          ),
2096
+	 *                          1 => array(
2097
+	 *                              'Term_Relationship.object_id' => 1
2098
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2099
+	 *                          )
2100
+	 *                      )
2101
+	 * @throws EE_Error
2102
+	 */
2103
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
+	{
2105
+		$ids_to_delete_indexed_by_column = array();
2106
+		if ($this->has_primary_key_field()) {
2107
+			$primary_table = $this->_get_main_table();
2108
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
+			$other_tables = $this->_get_other_tables();
2110
+			$ids_to_delete_indexed_by_column = $query = array();
2111
+			foreach ($row_results_for_deleting as $item_to_delete) {
2112
+				// before we mark this item for deletion,
2113
+				// make sure there's no related entities blocking its deletion (if we're checking)
2114
+				if ($allow_blocking
2115
+					&& $this->delete_is_blocked_by_related_models(
2116
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
+					)
2118
+				) {
2119
+					continue;
2120
+				}
2121
+				// primary table deletes
2122
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
+				}
2126
+			}
2127
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
+			$fields = $this->get_combined_primary_key_fields();
2129
+			foreach ($row_results_for_deleting as $item_to_delete) {
2130
+				$ids_to_delete_indexed_by_column_for_row = array();
2131
+				foreach ($fields as $cpk_field) {
2132
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2133
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2135
+					}
2136
+				}
2137
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
+			}
2139
+		} else {
2140
+			// so there's no primary key and no combined key...
2141
+			// sorry, can't help you
2142
+			throw new EE_Error(
2143
+				sprintf(
2144
+					__(
2145
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
+						"event_espresso"
2147
+					),
2148
+					get_class($this)
2149
+				)
2150
+			);
2151
+		}
2152
+		return $ids_to_delete_indexed_by_column;
2153
+	}
2154
+
2155
+
2156
+	/**
2157
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
+	 * the corresponding query_part for the query performing the delete.
2159
+	 *
2160
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
+	 * @return string
2162
+	 * @throws EE_Error
2163
+	 */
2164
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
+	{
2166
+		$query_part = '';
2167
+		if (empty($ids_to_delete_indexed_by_column)) {
2168
+			return $query_part;
2169
+		} elseif ($this->has_primary_key_field()) {
2170
+			$query = array();
2171
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2173
+			}
2174
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2175
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2176
+			$ways_to_identify_a_row = array();
2177
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2178
+				$values_for_each_combined_primary_key_for_a_row = array();
2179
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2180
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2181
+				}
2182
+				$ways_to_identify_a_row[] = '('
2183
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2184
+											. ')';
2185
+			}
2186
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2187
+		}
2188
+		return $query_part;
2189
+	}
2190
+
2191
+
2192
+
2193
+	/**
2194
+	 * Gets the model field by the fully qualified name
2195
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2196
+	 * @return EE_Model_Field_Base
2197
+	 */
2198
+	public function get_field_by_column($qualified_column_name)
2199
+	{
2200
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2201
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2202
+				return $field_obj;
2203
+			}
2204
+		}
2205
+		throw new EE_Error(
2206
+			sprintf(
2207
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2208
+				$this->get_this_model_name(),
2209
+				$qualified_column_name
2210
+			)
2211
+		);
2212
+	}
2213
+
2214
+
2215
+
2216
+	/**
2217
+	 * Count all the rows that match criteria the model query params.
2218
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2219
+	 * column
2220
+	 *
2221
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2222
+	 * @param string $field_to_count field on model to count by (not column name)
2223
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2224
+	 *                               that by the setting $distinct to TRUE;
2225
+	 * @return int
2226
+	 * @throws EE_Error
2227
+	 */
2228
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2229
+	{
2230
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2231
+		if ($field_to_count) {
2232
+			$field_obj = $this->field_settings_for($field_to_count);
2233
+			$column_to_count = $field_obj->get_qualified_column();
2234
+		} elseif ($this->has_primary_key_field()) {
2235
+			$pk_field_obj = $this->get_primary_key_field();
2236
+			$column_to_count = $pk_field_obj->get_qualified_column();
2237
+		} else {
2238
+			// there's no primary key
2239
+			// if we're counting distinct items, and there's no primary key,
2240
+			// we need to list out the columns for distinction;
2241
+			// otherwise we can just use star
2242
+			if ($distinct) {
2243
+				$columns_to_use = array();
2244
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2245
+					$columns_to_use[] = $field_obj->get_qualified_column();
2246
+				}
2247
+				$column_to_count = implode(',', $columns_to_use);
2248
+			} else {
2249
+				$column_to_count = '*';
2250
+			}
2251
+		}
2252
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2253
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2254
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2255
+	}
2256
+
2257
+
2258
+
2259
+	/**
2260
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2261
+	 *
2262
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2263
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2264
+	 * @return float
2265
+	 * @throws EE_Error
2266
+	 */
2267
+	public function sum($query_params, $field_to_sum = null)
2268
+	{
2269
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2270
+		if ($field_to_sum) {
2271
+			$field_obj = $this->field_settings_for($field_to_sum);
2272
+		} else {
2273
+			$field_obj = $this->get_primary_key_field();
2274
+		}
2275
+		$column_to_count = $field_obj->get_qualified_column();
2276
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2277
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2278
+		$data_type = $field_obj->get_wpdb_data_type();
2279
+		if ($data_type === '%d' || $data_type === '%s') {
2280
+			return (float) $return_value;
2281
+		}
2282
+		// must be %f
2283
+		return (float) $return_value;
2284
+	}
2285
+
2286
+
2287
+
2288
+	/**
2289
+	 * Just calls the specified method on $wpdb with the given arguments
2290
+	 * Consolidates a little extra error handling code
2291
+	 *
2292
+	 * @param string $wpdb_method
2293
+	 * @param array  $arguments_to_provide
2294
+	 * @throws EE_Error
2295
+	 * @global wpdb  $wpdb
2296
+	 * @return mixed
2297
+	 */
2298
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2299
+	{
2300
+		// if we're in maintenance mode level 2, DON'T run any queries
2301
+		// because level 2 indicates the database needs updating and
2302
+		// is probably out of sync with the code
2303
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2304
+			throw new EE_Error(sprintf(__(
2305
+				"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2306
+				"event_espresso"
2307
+			)));
2308
+		}
2309
+		/** @type WPDB $wpdb */
2310
+		global $wpdb;
2311
+		if (! method_exists($wpdb, $wpdb_method)) {
2312
+			throw new EE_Error(sprintf(__(
2313
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2314
+				'event_espresso'
2315
+			), $wpdb_method));
2316
+		}
2317
+		if (WP_DEBUG) {
2318
+			$old_show_errors_value = $wpdb->show_errors;
2319
+			$wpdb->show_errors(false);
2320
+		}
2321
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2322
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2323
+		if (WP_DEBUG) {
2324
+			$wpdb->show_errors($old_show_errors_value);
2325
+			if (! empty($wpdb->last_error)) {
2326
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2327
+			}
2328
+			if ($result === false) {
2329
+				throw new EE_Error(sprintf(__(
2330
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2331
+					'event_espresso'
2332
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2333
+			}
2334
+		} elseif ($result === false) {
2335
+			EE_Error::add_error(
2336
+				sprintf(
2337
+					__(
2338
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2339
+						'event_espresso'
2340
+					),
2341
+					$wpdb_method,
2342
+					var_export($arguments_to_provide, true),
2343
+					$wpdb->last_error
2344
+				),
2345
+				__FILE__,
2346
+				__FUNCTION__,
2347
+				__LINE__
2348
+			);
2349
+		}
2350
+		return $result;
2351
+	}
2352
+
2353
+
2354
+
2355
+	/**
2356
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2357
+	 * and if there's an error tries to verify the DB is correct. Uses
2358
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2359
+	 * we should try to fix the EE core db, the addons, or just give up
2360
+	 *
2361
+	 * @param string $wpdb_method
2362
+	 * @param array  $arguments_to_provide
2363
+	 * @return mixed
2364
+	 */
2365
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2366
+	{
2367
+		/** @type WPDB $wpdb */
2368
+		global $wpdb;
2369
+		$wpdb->last_error = null;
2370
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2371
+		// was there an error running the query? but we don't care on new activations
2372
+		// (we're going to setup the DB anyway on new activations)
2373
+		if (($result === false || ! empty($wpdb->last_error))
2374
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2375
+		) {
2376
+			switch (EEM_Base::$_db_verification_level) {
2377
+				case EEM_Base::db_verified_none:
2378
+					// let's double-check core's DB
2379
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2380
+					break;
2381
+				case EEM_Base::db_verified_core:
2382
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2383
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2384
+					break;
2385
+				case EEM_Base::db_verified_addons:
2386
+					// ummmm... you in trouble
2387
+					return $result;
2388
+					break;
2389
+			}
2390
+			if (! empty($error_message)) {
2391
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2392
+				trigger_error($error_message);
2393
+			}
2394
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2395
+		}
2396
+		return $result;
2397
+	}
2398
+
2399
+
2400
+
2401
+	/**
2402
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2403
+	 * EEM_Base::$_db_verification_level
2404
+	 *
2405
+	 * @param string $wpdb_method
2406
+	 * @param array  $arguments_to_provide
2407
+	 * @return string
2408
+	 */
2409
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2410
+	{
2411
+		/** @type WPDB $wpdb */
2412
+		global $wpdb;
2413
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2414
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2415
+		$error_message = sprintf(
2416
+			__(
2417
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2418
+				'event_espresso'
2419
+			),
2420
+			$wpdb->last_error,
2421
+			$wpdb_method,
2422
+			wp_json_encode($arguments_to_provide)
2423
+		);
2424
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2425
+		return $error_message;
2426
+	}
2427
+
2428
+
2429
+
2430
+	/**
2431
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2432
+	 * EEM_Base::$_db_verification_level
2433
+	 *
2434
+	 * @param $wpdb_method
2435
+	 * @param $arguments_to_provide
2436
+	 * @return string
2437
+	 */
2438
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2439
+	{
2440
+		/** @type WPDB $wpdb */
2441
+		global $wpdb;
2442
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2443
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2444
+		$error_message = sprintf(
2445
+			__(
2446
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2447
+				'event_espresso'
2448
+			),
2449
+			$wpdb->last_error,
2450
+			$wpdb_method,
2451
+			wp_json_encode($arguments_to_provide)
2452
+		);
2453
+		EE_System::instance()->initialize_addons();
2454
+		return $error_message;
2455
+	}
2456
+
2457
+
2458
+
2459
+	/**
2460
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2461
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2462
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2463
+	 * ..."
2464
+	 *
2465
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2466
+	 * @return string
2467
+	 */
2468
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2469
+	{
2470
+		return " FROM " . $model_query_info->get_full_join_sql() .
2471
+			   $model_query_info->get_where_sql() .
2472
+			   $model_query_info->get_group_by_sql() .
2473
+			   $model_query_info->get_having_sql() .
2474
+			   $model_query_info->get_order_by_sql() .
2475
+			   $model_query_info->get_limit_sql();
2476
+	}
2477
+
2478
+
2479
+
2480
+	/**
2481
+	 * Set to easily debug the next X queries ran from this model.
2482
+	 *
2483
+	 * @param int $count
2484
+	 */
2485
+	public function show_next_x_db_queries($count = 1)
2486
+	{
2487
+		$this->_show_next_x_db_queries = $count;
2488
+	}
2489
+
2490
+
2491
+
2492
+	/**
2493
+	 * @param $sql_query
2494
+	 */
2495
+	public function show_db_query_if_previously_requested($sql_query)
2496
+	{
2497
+		if ($this->_show_next_x_db_queries > 0) {
2498
+			echo $sql_query;
2499
+			$this->_show_next_x_db_queries--;
2500
+		}
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2507
+	 * There are the 3 cases:
2508
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2509
+	 * $otherModelObject has no ID, it is first saved.
2510
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2511
+	 * has no ID, it is first saved.
2512
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2513
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2514
+	 * join table
2515
+	 *
2516
+	 * @param        EE_Base_Class                     /int $thisModelObject
2517
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2518
+	 * @param string $relationName                     , key in EEM_Base::_relations
2519
+	 *                                                 an attendee to a group, you also want to specify which role they
2520
+	 *                                                 will have in that group. So you would use this parameter to
2521
+	 *                                                 specify array('role-column-name'=>'role-id')
2522
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2523
+	 *                                                 to for relation to methods that allow you to further specify
2524
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2525
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2526
+	 *                                                 because these will be inserted in any new rows created as well.
2527
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2528
+	 * @throws EE_Error
2529
+	 */
2530
+	public function add_relationship_to(
2531
+		$id_or_obj,
2532
+		$other_model_id_or_obj,
2533
+		$relationName,
2534
+		$extra_join_model_fields_n_values = array()
2535
+	) {
2536
+		$relation_obj = $this->related_settings_for($relationName);
2537
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2538
+	}
2539
+
2540
+
2541
+
2542
+	/**
2543
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2544
+	 * There are the 3 cases:
2545
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2546
+	 * error
2547
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2548
+	 * an error
2549
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2550
+	 *
2551
+	 * @param        EE_Base_Class /int $id_or_obj
2552
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2553
+	 * @param string $relationName key in EEM_Base::_relations
2554
+	 * @return boolean of success
2555
+	 * @throws EE_Error
2556
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2557
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2558
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2559
+	 *                             because these will be inserted in any new rows created as well.
2560
+	 */
2561
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2562
+	{
2563
+		$relation_obj = $this->related_settings_for($relationName);
2564
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2565
+	}
2566
+
2567
+
2568
+
2569
+	/**
2570
+	 * @param mixed           $id_or_obj
2571
+	 * @param string          $relationName
2572
+	 * @param array           $where_query_params
2573
+	 * @param EE_Base_Class[] objects to which relations were removed
2574
+	 * @return \EE_Base_Class[]
2575
+	 * @throws EE_Error
2576
+	 */
2577
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2578
+	{
2579
+		$relation_obj = $this->related_settings_for($relationName);
2580
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2581
+	}
2582
+
2583
+
2584
+
2585
+	/**
2586
+	 * Gets all the related items of the specified $model_name, using $query_params.
2587
+	 * Note: by default, we remove the "default query params"
2588
+	 * because we want to get even deleted items etc.
2589
+	 *
2590
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2591
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2592
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2593
+	 * @return EE_Base_Class[]
2594
+	 * @throws EE_Error
2595
+	 */
2596
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2597
+	{
2598
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2599
+		$relation_settings = $this->related_settings_for($model_name);
2600
+		return $relation_settings->get_all_related($model_obj, $query_params);
2601
+	}
2602
+
2603
+
2604
+
2605
+	/**
2606
+	 * Deletes all the model objects across the relation indicated by $model_name
2607
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2608
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2609
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2610
+	 *
2611
+	 * @param EE_Base_Class|int|string $id_or_obj
2612
+	 * @param string                   $model_name
2613
+	 * @param array                    $query_params
2614
+	 * @return int how many deleted
2615
+	 * @throws EE_Error
2616
+	 */
2617
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2618
+	{
2619
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2620
+		$relation_settings = $this->related_settings_for($model_name);
2621
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2622
+	}
2623
+
2624
+
2625
+
2626
+	/**
2627
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2628
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2629
+	 * the model objects can't be hard deleted because of blocking related model objects,
2630
+	 * just does a soft-delete on them instead.
2631
+	 *
2632
+	 * @param EE_Base_Class|int|string $id_or_obj
2633
+	 * @param string                   $model_name
2634
+	 * @param array                    $query_params
2635
+	 * @return int how many deleted
2636
+	 * @throws EE_Error
2637
+	 */
2638
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2639
+	{
2640
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2641
+		$relation_settings = $this->related_settings_for($model_name);
2642
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2643
+	}
2644
+
2645
+
2646
+
2647
+	/**
2648
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2649
+	 * unless otherwise specified in the $query_params
2650
+	 *
2651
+	 * @param        int             /EE_Base_Class $id_or_obj
2652
+	 * @param string $model_name     like 'Event', or 'Registration'
2653
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2654
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2655
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2656
+	 *                               that by the setting $distinct to TRUE;
2657
+	 * @return int
2658
+	 * @throws EE_Error
2659
+	 */
2660
+	public function count_related(
2661
+		$id_or_obj,
2662
+		$model_name,
2663
+		$query_params = array(),
2664
+		$field_to_count = null,
2665
+		$distinct = false
2666
+	) {
2667
+		$related_model = $this->get_related_model_obj($model_name);
2668
+		// we're just going to use the query params on the related model's normal get_all query,
2669
+		// except add a condition to say to match the current mod
2670
+		if (! isset($query_params['default_where_conditions'])) {
2671
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2672
+		}
2673
+		$this_model_name = $this->get_this_model_name();
2674
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2675
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2676
+		return $related_model->count($query_params, $field_to_count, $distinct);
2677
+	}
2678
+
2679
+
2680
+
2681
+	/**
2682
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2683
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2684
+	 *
2685
+	 * @param        int           /EE_Base_Class $id_or_obj
2686
+	 * @param string $model_name   like 'Event', or 'Registration'
2687
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2688
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2689
+	 * @return float
2690
+	 * @throws EE_Error
2691
+	 */
2692
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2693
+	{
2694
+		$related_model = $this->get_related_model_obj($model_name);
2695
+		if (! is_array($query_params)) {
2696
+			EE_Error::doing_it_wrong(
2697
+				'EEM_Base::sum_related',
2698
+				sprintf(
2699
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2700
+					gettype($query_params)
2701
+				),
2702
+				'4.6.0'
2703
+			);
2704
+			$query_params = array();
2705
+		}
2706
+		// we're just going to use the query params on the related model's normal get_all query,
2707
+		// except add a condition to say to match the current mod
2708
+		if (! isset($query_params['default_where_conditions'])) {
2709
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2710
+		}
2711
+		$this_model_name = $this->get_this_model_name();
2712
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2713
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2714
+		return $related_model->sum($query_params, $field_to_sum);
2715
+	}
2716
+
2717
+
2718
+
2719
+	/**
2720
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2721
+	 * $modelObject
2722
+	 *
2723
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2724
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2725
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2726
+	 * @return EE_Base_Class
2727
+	 * @throws EE_Error
2728
+	 */
2729
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2730
+	{
2731
+		$query_params['limit'] = 1;
2732
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2733
+		if ($results) {
2734
+			return array_shift($results);
2735
+		}
2736
+		return null;
2737
+	}
2738
+
2739
+
2740
+
2741
+	/**
2742
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2743
+	 *
2744
+	 * @return string
2745
+	 */
2746
+	public function get_this_model_name()
2747
+	{
2748
+		return str_replace("EEM_", "", get_class($this));
2749
+	}
2750
+
2751
+
2752
+
2753
+	/**
2754
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2755
+	 *
2756
+	 * @return EE_Any_Foreign_Model_Name_Field
2757
+	 * @throws EE_Error
2758
+	 */
2759
+	public function get_field_containing_related_model_name()
2760
+	{
2761
+		foreach ($this->field_settings(true) as $field) {
2762
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2763
+				$field_with_model_name = $field;
2764
+			}
2765
+		}
2766
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2767
+			throw new EE_Error(sprintf(
2768
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2769
+				$this->get_this_model_name()
2770
+			));
2771
+		}
2772
+		return $field_with_model_name;
2773
+	}
2774
+
2775
+
2776
+
2777
+	/**
2778
+	 * Inserts a new entry into the database, for each table.
2779
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2780
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2781
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2782
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2783
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2784
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2785
+	 *
2786
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2787
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2788
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2789
+	 *                              of EEM_Base)
2790
+	 * @return int|string new primary key on main table that got inserted
2791
+	 * @throws EE_Error
2792
+	 */
2793
+	public function insert($field_n_values)
2794
+	{
2795
+		/**
2796
+		 * Filters the fields and their values before inserting an item using the models
2797
+		 *
2798
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2799
+		 * @param EEM_Base $model           the model used
2800
+		 */
2801
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2803
+			$main_table = $this->_get_main_table();
2804
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2805
+			if ($new_id !== false) {
2806
+				foreach ($this->_get_other_tables() as $other_table) {
2807
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2808
+				}
2809
+			}
2810
+			/**
2811
+			 * Done just after attempting to insert a new model object
2812
+			 *
2813
+			 * @param EEM_Base   $model           used
2814
+			 * @param array      $fields_n_values fields and their values
2815
+			 * @param int|string the              ID of the newly-inserted model object
2816
+			 */
2817
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2818
+			return $new_id;
2819
+		}
2820
+		return false;
2821
+	}
2822
+
2823
+
2824
+
2825
+	/**
2826
+	 * Checks that the result would satisfy the unique indexes on this model
2827
+	 *
2828
+	 * @param array  $field_n_values
2829
+	 * @param string $action
2830
+	 * @return boolean
2831
+	 * @throws EE_Error
2832
+	 */
2833
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2834
+	{
2835
+		foreach ($this->unique_indexes() as $index_name => $index) {
2836
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2837
+			if ($this->exists(array($uniqueness_where_params))) {
2838
+				EE_Error::add_error(
2839
+					sprintf(
2840
+						__(
2841
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2842
+							"event_espresso"
2843
+						),
2844
+						$action,
2845
+						$this->_get_class_name(),
2846
+						$index_name,
2847
+						implode(",", $index->field_names()),
2848
+						http_build_query($uniqueness_where_params)
2849
+					),
2850
+					__FILE__,
2851
+					__FUNCTION__,
2852
+					__LINE__
2853
+				);
2854
+				return false;
2855
+			}
2856
+		}
2857
+		return true;
2858
+	}
2859
+
2860
+
2861
+
2862
+	/**
2863
+	 * Checks the database for an item that conflicts (ie, if this item were
2864
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2865
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2866
+	 * can be either an EE_Base_Class or an array of fields n values
2867
+	 *
2868
+	 * @param EE_Base_Class|array $obj_or_fields_array
2869
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2870
+	 *                                                 when looking for conflicts
2871
+	 *                                                 (ie, if false, we ignore the model object's primary key
2872
+	 *                                                 when finding "conflicts". If true, it's also considered).
2873
+	 *                                                 Only works for INT primary key,
2874
+	 *                                                 STRING primary keys cannot be ignored
2875
+	 * @throws EE_Error
2876
+	 * @return EE_Base_Class|array
2877
+	 */
2878
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2879
+	{
2880
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2881
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2882
+		} elseif (is_array($obj_or_fields_array)) {
2883
+			$fields_n_values = $obj_or_fields_array;
2884
+		} else {
2885
+			throw new EE_Error(
2886
+				sprintf(
2887
+					__(
2888
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2889
+						"event_espresso"
2890
+					),
2891
+					get_class($this),
2892
+					$obj_or_fields_array
2893
+				)
2894
+			);
2895
+		}
2896
+		$query_params = array();
2897
+		if ($this->has_primary_key_field()
2898
+			&& ($include_primary_key
2899
+				|| $this->get_primary_key_field()
2900
+				   instanceof
2901
+				   EE_Primary_Key_String_Field)
2902
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2903
+		) {
2904
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2905
+		}
2906
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2909
+		}
2910
+		// if there is nothing to base this search on, then we shouldn't find anything
2911
+		if (empty($query_params)) {
2912
+			return array();
2913
+		}
2914
+		return $this->get_one($query_params);
2915
+	}
2916
+
2917
+
2918
+
2919
+	/**
2920
+	 * Like count, but is optimized and returns a boolean instead of an int
2921
+	 *
2922
+	 * @param array $query_params
2923
+	 * @return boolean
2924
+	 * @throws EE_Error
2925
+	 */
2926
+	public function exists($query_params)
2927
+	{
2928
+		$query_params['limit'] = 1;
2929
+		return $this->count($query_params) > 0;
2930
+	}
2931
+
2932
+
2933
+
2934
+	/**
2935
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2936
+	 *
2937
+	 * @param int|string $id
2938
+	 * @return boolean
2939
+	 * @throws EE_Error
2940
+	 */
2941
+	public function exists_by_ID($id)
2942
+	{
2943
+		return $this->exists(
2944
+			array(
2945
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2946
+				array(
2947
+					$this->primary_key_name() => $id,
2948
+				),
2949
+			)
2950
+		);
2951
+	}
2952
+
2953
+
2954
+
2955
+	/**
2956
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2957
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2958
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2959
+	 * on the main table)
2960
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2961
+	 * cases where we want to call it directly rather than via insert().
2962
+	 *
2963
+	 * @access   protected
2964
+	 * @param EE_Table_Base $table
2965
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2966
+	 *                                       float
2967
+	 * @param int           $new_id          for now we assume only int keys
2968
+	 * @throws EE_Error
2969
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2970
+	 * @return int ID of new row inserted, or FALSE on failure
2971
+	 */
2972
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2973
+	{
2974
+		global $wpdb;
2975
+		$insertion_col_n_values = array();
2976
+		$format_for_insertion = array();
2977
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2978
+		foreach ($fields_on_table as $field_name => $field_obj) {
2979
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2980
+			if ($field_obj->is_auto_increment()) {
2981
+				continue;
2982
+			}
2983
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2985
+			if ($prepared_value !== null) {
2986
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2987
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988
+			}
2989
+		}
2990
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2991
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2992
+			// so add the fk to the main table as a column
2993
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2994
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2995
+		}
2996
+		// insert the new entry
2997
+		$result = $this->_do_wpdb_query(
2998
+			'insert',
2999
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3000
+		);
3001
+		if ($result === false) {
3002
+			return false;
3003
+		}
3004
+		// ok, now what do we return for the ID of the newly-inserted thing?
3005
+		if ($this->has_primary_key_field()) {
3006
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3007
+				return $wpdb->insert_id;
3008
+			}
3009
+			// it's not an auto-increment primary key, so
3010
+			// it must have been supplied
3011
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3012
+		}
3013
+		// we can't return a  primary key because there is none. instead return
3014
+		// a unique string indicating this model
3015
+		return $this->get_index_primary_key_string($fields_n_values);
3016
+	}
3017
+
3018
+
3019
+
3020
+	/**
3021
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3022
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3023
+	 * and there is no default, we pass it along. WPDB will take care of it)
3024
+	 *
3025
+	 * @param EE_Model_Field_Base $field_obj
3026
+	 * @param array               $fields_n_values
3027
+	 * @return mixed string|int|float depending on what the table column will be expecting
3028
+	 * @throws EE_Error
3029
+	 */
3030
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3031
+	{
3032
+		// if this field doesn't allow nullable, don't allow it
3033
+		if (! $field_obj->is_nullable()
3034
+			&& (
3035
+				! isset($fields_n_values[ $field_obj->get_name() ])
3036
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3037
+			)
3038
+		) {
3039
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3040
+		}
3041
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3042
+			? $fields_n_values[ $field_obj->get_name() ]
3043
+			: null;
3044
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3045
+	}
3046
+
3047
+
3048
+
3049
+	/**
3050
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3051
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3052
+	 * the field's prepare_for_set() method.
3053
+	 *
3054
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3055
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3056
+	 *                                   top of file)
3057
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3058
+	 *                                   $value is a custom selection
3059
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3060
+	 */
3061
+	private function _prepare_value_for_use_in_db($value, $field)
3062
+	{
3063
+		if ($field && $field instanceof EE_Model_Field_Base) {
3064
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3065
+			switch ($this->_values_already_prepared_by_model_object) {
3066
+				/** @noinspection PhpMissingBreakStatementInspection */
3067
+				case self::not_prepared_by_model_object:
3068
+					$value = $field->prepare_for_set($value);
3069
+				// purposefully left out "return"
3070
+				case self::prepared_by_model_object:
3071
+					/** @noinspection SuspiciousAssignmentsInspection */
3072
+					$value = $field->prepare_for_use_in_db($value);
3073
+				case self::prepared_for_use_in_db:
3074
+					// leave the value alone
3075
+			}
3076
+			return $value;
3077
+			// phpcs:enable
3078
+		}
3079
+		return $value;
3080
+	}
3081
+
3082
+
3083
+
3084
+	/**
3085
+	 * Returns the main table on this model
3086
+	 *
3087
+	 * @return EE_Primary_Table
3088
+	 * @throws EE_Error
3089
+	 */
3090
+	protected function _get_main_table()
3091
+	{
3092
+		foreach ($this->_tables as $table) {
3093
+			if ($table instanceof EE_Primary_Table) {
3094
+				return $table;
3095
+			}
3096
+		}
3097
+		throw new EE_Error(sprintf(__(
3098
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3099
+			'event_espresso'
3100
+		), get_class($this)));
3101
+	}
3102
+
3103
+
3104
+
3105
+	/**
3106
+	 * table
3107
+	 * returns EE_Primary_Table table name
3108
+	 *
3109
+	 * @return string
3110
+	 * @throws EE_Error
3111
+	 */
3112
+	public function table()
3113
+	{
3114
+		return $this->_get_main_table()->get_table_name();
3115
+	}
3116
+
3117
+
3118
+
3119
+	/**
3120
+	 * table
3121
+	 * returns first EE_Secondary_Table table name
3122
+	 *
3123
+	 * @return string
3124
+	 */
3125
+	public function second_table()
3126
+	{
3127
+		// grab second table from tables array
3128
+		$second_table = end($this->_tables);
3129
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3130
+	}
3131
+
3132
+
3133
+
3134
+	/**
3135
+	 * get_table_obj_by_alias
3136
+	 * returns table name given it's alias
3137
+	 *
3138
+	 * @param string $table_alias
3139
+	 * @return EE_Primary_Table | EE_Secondary_Table
3140
+	 */
3141
+	public function get_table_obj_by_alias($table_alias = '')
3142
+	{
3143
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3144
+	}
3145
+
3146
+
3147
+
3148
+	/**
3149
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3150
+	 *
3151
+	 * @return EE_Secondary_Table[]
3152
+	 */
3153
+	protected function _get_other_tables()
3154
+	{
3155
+		$other_tables = array();
3156
+		foreach ($this->_tables as $table_alias => $table) {
3157
+			if ($table instanceof EE_Secondary_Table) {
3158
+				$other_tables[ $table_alias ] = $table;
3159
+			}
3160
+		}
3161
+		return $other_tables;
3162
+	}
3163
+
3164
+
3165
+
3166
+	/**
3167
+	 * Finds all the fields that correspond to the given table
3168
+	 *
3169
+	 * @param string $table_alias , array key in EEM_Base::_tables
3170
+	 * @return EE_Model_Field_Base[]
3171
+	 */
3172
+	public function _get_fields_for_table($table_alias)
3173
+	{
3174
+		return $this->_fields[ $table_alias ];
3175
+	}
3176
+
3177
+
3178
+
3179
+	/**
3180
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3181
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3182
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3183
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3184
+	 * related Registration, Transaction, and Payment models.
3185
+	 *
3186
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3187
+	 * @return EE_Model_Query_Info_Carrier
3188
+	 * @throws EE_Error
3189
+	 */
3190
+	public function _extract_related_models_from_query($query_params)
3191
+	{
3192
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3193
+		if (array_key_exists(0, $query_params)) {
3194
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3195
+		}
3196
+		if (array_key_exists('group_by', $query_params)) {
3197
+			if (is_array($query_params['group_by'])) {
3198
+				$this->_extract_related_models_from_sub_params_array_values(
3199
+					$query_params['group_by'],
3200
+					$query_info_carrier,
3201
+					'group_by'
3202
+				);
3203
+			} elseif (! empty($query_params['group_by'])) {
3204
+				$this->_extract_related_model_info_from_query_param(
3205
+					$query_params['group_by'],
3206
+					$query_info_carrier,
3207
+					'group_by'
3208
+				);
3209
+			}
3210
+		}
3211
+		if (array_key_exists('having', $query_params)) {
3212
+			$this->_extract_related_models_from_sub_params_array_keys(
3213
+				$query_params[0],
3214
+				$query_info_carrier,
3215
+				'having'
3216
+			);
3217
+		}
3218
+		if (array_key_exists('order_by', $query_params)) {
3219
+			if (is_array($query_params['order_by'])) {
3220
+				$this->_extract_related_models_from_sub_params_array_keys(
3221
+					$query_params['order_by'],
3222
+					$query_info_carrier,
3223
+					'order_by'
3224
+				);
3225
+			} elseif (! empty($query_params['order_by'])) {
3226
+				$this->_extract_related_model_info_from_query_param(
3227
+					$query_params['order_by'],
3228
+					$query_info_carrier,
3229
+					'order_by'
3230
+				);
3231
+			}
3232
+		}
3233
+		if (array_key_exists('force_join', $query_params)) {
3234
+			$this->_extract_related_models_from_sub_params_array_values(
3235
+				$query_params['force_join'],
3236
+				$query_info_carrier,
3237
+				'force_join'
3238
+			);
3239
+		}
3240
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3241
+		return $query_info_carrier;
3242
+	}
3243
+
3244
+
3245
+
3246
+	/**
3247
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3248
+	 *
3249
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3250
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3251
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3252
+	 * @throws EE_Error
3253
+	 * @return \EE_Model_Query_Info_Carrier
3254
+	 */
3255
+	private function _extract_related_models_from_sub_params_array_keys(
3256
+		$sub_query_params,
3257
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3258
+		$query_param_type
3259
+	) {
3260
+		if (! empty($sub_query_params)) {
3261
+			$sub_query_params = (array) $sub_query_params;
3262
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3263
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3264
+				$this->_extract_related_model_info_from_query_param(
3265
+					$param,
3266
+					$model_query_info_carrier,
3267
+					$query_param_type
3268
+				);
3269
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3270
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3271
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3272
+				// of array('Registration.TXN_ID'=>23)
3273
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3274
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3275
+					if (! is_array($possibly_array_of_params)) {
3276
+						throw new EE_Error(sprintf(
3277
+							__(
3278
+								"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3279
+								"event_espresso"
3280
+							),
3281
+							$param,
3282
+							$possibly_array_of_params
3283
+						));
3284
+					}
3285
+					$this->_extract_related_models_from_sub_params_array_keys(
3286
+						$possibly_array_of_params,
3287
+						$model_query_info_carrier,
3288
+						$query_param_type
3289
+					);
3290
+				} elseif ($query_param_type === 0 // ie WHERE
3291
+						  && is_array($possibly_array_of_params)
3292
+						  && isset($possibly_array_of_params[2])
3293
+						  && $possibly_array_of_params[2] == true
3294
+				) {
3295
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3296
+					// indicating that $possible_array_of_params[1] is actually a field name,
3297
+					// from which we should extract query parameters!
3298
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3299
+						throw new EE_Error(sprintf(__(
3300
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3301
+							"event_espresso"
3302
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3303
+					}
3304
+					$this->_extract_related_model_info_from_query_param(
3305
+						$possibly_array_of_params[1],
3306
+						$model_query_info_carrier,
3307
+						$query_param_type
3308
+					);
3309
+				}
3310
+			}
3311
+		}
3312
+		return $model_query_info_carrier;
3313
+	}
3314
+
3315
+
3316
+
3317
+	/**
3318
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3319
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
+	 *
3321
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3322
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3324
+	 * @throws EE_Error
3325
+	 * @return \EE_Model_Query_Info_Carrier
3326
+	 */
3327
+	private function _extract_related_models_from_sub_params_array_values(
3328
+		$sub_query_params,
3329
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
+		$query_param_type
3331
+	) {
3332
+		if (! empty($sub_query_params)) {
3333
+			if (! is_array($sub_query_params)) {
3334
+				throw new EE_Error(sprintf(
3335
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
+					$sub_query_params
3337
+				));
3338
+			}
3339
+			foreach ($sub_query_params as $param) {
3340
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3341
+				$this->_extract_related_model_info_from_query_param(
3342
+					$param,
3343
+					$model_query_info_carrier,
3344
+					$query_param_type
3345
+				);
3346
+			}
3347
+		}
3348
+		return $model_query_info_carrier;
3349
+	}
3350
+
3351
+
3352
+	/**
3353
+	 * Extract all the query parts from  model query params
3354
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3355
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3356
+	 * but use them in a different order. Eg, we need to know what models we are querying
3357
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3358
+	 * other models before we can finalize the where clause SQL.
3359
+	 *
3360
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3361
+	 * @throws EE_Error
3362
+	 * @return EE_Model_Query_Info_Carrier
3363
+	 * @throws ModelConfigurationException
3364
+	 */
3365
+	public function _create_model_query_info_carrier($query_params)
3366
+	{
3367
+		if (! is_array($query_params)) {
3368
+			EE_Error::doing_it_wrong(
3369
+				'EEM_Base::_create_model_query_info_carrier',
3370
+				sprintf(
3371
+					__(
3372
+						'$query_params should be an array, you passed a variable of type %s',
3373
+						'event_espresso'
3374
+					),
3375
+					gettype($query_params)
3376
+				),
3377
+				'4.6.0'
3378
+			);
3379
+			$query_params = array();
3380
+		}
3381
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3382
+		// first check if we should alter the query to account for caps or not
3383
+		// because the caps might require us to do extra joins
3384
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3385
+			$query_params[0] = array_replace_recursive(
3386
+				$query_params[0],
3387
+				$this->caps_where_conditions(
3388
+					$query_params['caps']
3389
+				)
3390
+			);
3391
+		}
3392
+
3393
+		// check if we should alter the query to remove data related to protected
3394
+		// custom post types
3395
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3396
+			$where_param_key_for_password = $this->modelChainAndPassword();
3397
+			// only include if related to a cpt where no password has been set
3398
+			$query_params[0]['OR*nopassword'] = array(
3399
+				$where_param_key_for_password => '',
3400
+				$where_param_key_for_password . '*' => array('IS_NULL')
3401
+			);
3402
+		}
3403
+		$query_object = $this->_extract_related_models_from_query($query_params);
3404
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3405
+		foreach ($query_params[0] as $key => $value) {
3406
+			if (is_int($key)) {
3407
+				throw new EE_Error(
3408
+					sprintf(
3409
+						__(
3410
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3411
+							"event_espresso"
3412
+						),
3413
+						$key,
3414
+						var_export($value, true),
3415
+						var_export($query_params, true),
3416
+						get_class($this)
3417
+					)
3418
+				);
3419
+			}
3420
+		}
3421
+		if (array_key_exists('default_where_conditions', $query_params)
3422
+			&& ! empty($query_params['default_where_conditions'])
3423
+		) {
3424
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3425
+		} else {
3426
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3427
+		}
3428
+		$query_params[0] = array_merge(
3429
+			$this->_get_default_where_conditions_for_models_in_query(
3430
+				$query_object,
3431
+				$use_default_where_conditions,
3432
+				$query_params[0]
3433
+			),
3434
+			$query_params[0]
3435
+		);
3436
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3437
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3438
+		// So we need to setup a subquery and use that for the main join.
3439
+		// Note for now this only works on the primary table for the model.
3440
+		// So for instance, you could set the limit array like this:
3441
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3442
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3443
+			$query_object->set_main_model_join_sql(
3444
+				$this->_construct_limit_join_select(
3445
+					$query_params['on_join_limit'][0],
3446
+					$query_params['on_join_limit'][1]
3447
+				)
3448
+			);
3449
+		}
3450
+		// set limit
3451
+		if (array_key_exists('limit', $query_params)) {
3452
+			if (is_array($query_params['limit'])) {
3453
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3454
+					$e = sprintf(
3455
+						__(
3456
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3457
+							"event_espresso"
3458
+						),
3459
+						http_build_query($query_params['limit'])
3460
+					);
3461
+					throw new EE_Error($e . "|" . $e);
3462
+				}
3463
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3464
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3465
+			} elseif (! empty($query_params['limit'])) {
3466
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3467
+			}
3468
+		}
3469
+		// set order by
3470
+		if (array_key_exists('order_by', $query_params)) {
3471
+			if (is_array($query_params['order_by'])) {
3472
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3473
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3474
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3475
+				if (array_key_exists('order', $query_params)) {
3476
+					throw new EE_Error(
3477
+						sprintf(
3478
+							__(
3479
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3480
+								"event_espresso"
3481
+							),
3482
+							get_class($this),
3483
+							implode(", ", array_keys($query_params['order_by'])),
3484
+							implode(", ", $query_params['order_by']),
3485
+							$query_params['order']
3486
+						)
3487
+					);
3488
+				}
3489
+				$this->_extract_related_models_from_sub_params_array_keys(
3490
+					$query_params['order_by'],
3491
+					$query_object,
3492
+					'order_by'
3493
+				);
3494
+				// assume it's an array of fields to order by
3495
+				$order_array = array();
3496
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3497
+					$order = $this->_extract_order($order);
3498
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3499
+				}
3500
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3501
+			} elseif (! empty($query_params['order_by'])) {
3502
+				$this->_extract_related_model_info_from_query_param(
3503
+					$query_params['order_by'],
3504
+					$query_object,
3505
+					'order',
3506
+					$query_params['order_by']
3507
+				);
3508
+				$order = isset($query_params['order'])
3509
+					? $this->_extract_order($query_params['order'])
3510
+					: 'DESC';
3511
+				$query_object->set_order_by_sql(
3512
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3513
+				);
3514
+			}
3515
+		}
3516
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3517
+		if (! array_key_exists('order_by', $query_params)
3518
+			&& array_key_exists('order', $query_params)
3519
+			&& ! empty($query_params['order'])
3520
+		) {
3521
+			$pk_field = $this->get_primary_key_field();
3522
+			$order = $this->_extract_order($query_params['order']);
3523
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3524
+		}
3525
+		// set group by
3526
+		if (array_key_exists('group_by', $query_params)) {
3527
+			if (is_array($query_params['group_by'])) {
3528
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3529
+				$group_by_array = array();
3530
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3531
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3532
+				}
3533
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3534
+			} elseif (! empty($query_params['group_by'])) {
3535
+				$query_object->set_group_by_sql(
3536
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3537
+				);
3538
+			}
3539
+		}
3540
+		// set having
3541
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3542
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3543
+		}
3544
+		// now, just verify they didn't pass anything wack
3545
+		foreach ($query_params as $query_key => $query_value) {
3546
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3547
+				throw new EE_Error(
3548
+					sprintf(
3549
+						__(
3550
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3551
+							'event_espresso'
3552
+						),
3553
+						$query_key,
3554
+						get_class($this),
3555
+						//                      print_r( $this->_allowed_query_params, TRUE )
3556
+						implode(',', $this->_allowed_query_params)
3557
+					)
3558
+				);
3559
+			}
3560
+		}
3561
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3562
+		if (empty($main_model_join_sql)) {
3563
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3564
+		}
3565
+		return $query_object;
3566
+	}
3567
+
3568
+
3569
+
3570
+	/**
3571
+	 * Gets the where conditions that should be imposed on the query based on the
3572
+	 * context (eg reading frontend, backend, edit or delete).
3573
+	 *
3574
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3575
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3576
+	 * @throws EE_Error
3577
+	 */
3578
+	public function caps_where_conditions($context = self::caps_read)
3579
+	{
3580
+		EEM_Base::verify_is_valid_cap_context($context);
3581
+		$cap_where_conditions = array();
3582
+		$cap_restrictions = $this->caps_missing($context);
3583
+		/**
3584
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3585
+		 */
3586
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3587
+			$cap_where_conditions = array_replace_recursive(
3588
+				$cap_where_conditions,
3589
+				$restriction_if_no_cap->get_default_where_conditions()
3590
+			);
3591
+		}
3592
+		return apply_filters(
3593
+			'FHEE__EEM_Base__caps_where_conditions__return',
3594
+			$cap_where_conditions,
3595
+			$this,
3596
+			$context,
3597
+			$cap_restrictions
3598
+		);
3599
+	}
3600
+
3601
+
3602
+
3603
+	/**
3604
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3605
+	 * otherwise throws an exception
3606
+	 *
3607
+	 * @param string $should_be_order_string
3608
+	 * @return string either ASC, asc, DESC or desc
3609
+	 * @throws EE_Error
3610
+	 */
3611
+	private function _extract_order($should_be_order_string)
3612
+	{
3613
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3614
+			return $should_be_order_string;
3615
+		}
3616
+		throw new EE_Error(
3617
+			sprintf(
3618
+				__(
3619
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3620
+					"event_espresso"
3621
+				),
3622
+				get_class($this),
3623
+				$should_be_order_string
3624
+			)
3625
+		);
3626
+	}
3627
+
3628
+
3629
+
3630
+	/**
3631
+	 * Looks at all the models which are included in this query, and asks each
3632
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3633
+	 * so they can be merged
3634
+	 *
3635
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3636
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3637
+	 *                                                                  'none' means NO default where conditions will
3638
+	 *                                                                  be used AT ALL during this query.
3639
+	 *                                                                  'other_models_only' means default where
3640
+	 *                                                                  conditions from other models will be used, but
3641
+	 *                                                                  not for this primary model. 'all', the default,
3642
+	 *                                                                  means default where conditions will apply as
3643
+	 *                                                                  normal
3644
+	 * @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
3645
+	 * @throws EE_Error
3646
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3647
+	 */
3648
+	private function _get_default_where_conditions_for_models_in_query(
3649
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3650
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3651
+		$where_query_params = array()
3652
+	) {
3653
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3654
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3655
+			throw new EE_Error(sprintf(
3656
+				__(
3657
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3658
+					"event_espresso"
3659
+				),
3660
+				$use_default_where_conditions,
3661
+				implode(", ", $allowed_used_default_where_conditions_values)
3662
+			));
3663
+		}
3664
+		$universal_query_params = array();
3665
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3666
+			$universal_query_params = $this->_get_default_where_conditions();
3667
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3668
+			$universal_query_params = $this->_get_minimum_where_conditions();
3669
+		}
3670
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3671
+			$related_model = $this->get_related_model_obj($model_name);
3672
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3673
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3674
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3675
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3676
+			} else {
3677
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3678
+				continue;
3679
+			}
3680
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3681
+				$related_model_universal_where_params,
3682
+				$where_query_params,
3683
+				$related_model,
3684
+				$model_relation_path
3685
+			);
3686
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3687
+				$universal_query_params,
3688
+				$overrides
3689
+			);
3690
+		}
3691
+		return $universal_query_params;
3692
+	}
3693
+
3694
+
3695
+
3696
+	/**
3697
+	 * Determines whether or not we should use default where conditions for the model in question
3698
+	 * (this model, or other related models).
3699
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3700
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3701
+	 * We should use default where conditions on related models when they requested to use default where conditions
3702
+	 * on all models, or specifically just on other related models
3703
+	 * @param      $default_where_conditions_value
3704
+	 * @param bool $for_this_model false means this is for OTHER related models
3705
+	 * @return bool
3706
+	 */
3707
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3708
+	{
3709
+		return (
3710
+				   $for_this_model
3711
+				   && in_array(
3712
+					   $default_where_conditions_value,
3713
+					   array(
3714
+						   EEM_Base::default_where_conditions_all,
3715
+						   EEM_Base::default_where_conditions_this_only,
3716
+						   EEM_Base::default_where_conditions_minimum_others,
3717
+					   ),
3718
+					   true
3719
+				   )
3720
+			   )
3721
+			   || (
3722
+				   ! $for_this_model
3723
+				   && in_array(
3724
+					   $default_where_conditions_value,
3725
+					   array(
3726
+						   EEM_Base::default_where_conditions_all,
3727
+						   EEM_Base::default_where_conditions_others_only,
3728
+					   ),
3729
+					   true
3730
+				   )
3731
+			   );
3732
+	}
3733
+
3734
+	/**
3735
+	 * Determines whether or not we should use default minimum conditions for the model in question
3736
+	 * (this model, or other related models).
3737
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3738
+	 * where conditions.
3739
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3740
+	 * on this model or others
3741
+	 * @param      $default_where_conditions_value
3742
+	 * @param bool $for_this_model false means this is for OTHER related models
3743
+	 * @return bool
3744
+	 */
3745
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3746
+	{
3747
+		return (
3748
+				   $for_this_model
3749
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3750
+			   )
3751
+			   || (
3752
+				   ! $for_this_model
3753
+				   && in_array(
3754
+					   $default_where_conditions_value,
3755
+					   array(
3756
+						   EEM_Base::default_where_conditions_minimum_others,
3757
+						   EEM_Base::default_where_conditions_minimum_all,
3758
+					   ),
3759
+					   true
3760
+				   )
3761
+			   );
3762
+	}
3763
+
3764
+
3765
+	/**
3766
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3767
+	 * then we also add a special where condition which allows for that model's primary key
3768
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3769
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3770
+	 *
3771
+	 * @param array    $default_where_conditions
3772
+	 * @param array    $provided_where_conditions
3773
+	 * @param EEM_Base $model
3774
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3775
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3776
+	 * @throws EE_Error
3777
+	 */
3778
+	private function _override_defaults_or_make_null_friendly(
3779
+		$default_where_conditions,
3780
+		$provided_where_conditions,
3781
+		$model,
3782
+		$model_relation_path
3783
+	) {
3784
+		$null_friendly_where_conditions = array();
3785
+		$none_overridden = true;
3786
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3787
+		foreach ($default_where_conditions as $key => $val) {
3788
+			if (isset($provided_where_conditions[ $key ])) {
3789
+				$none_overridden = false;
3790
+			} else {
3791
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3792
+			}
3793
+		}
3794
+		if ($none_overridden && $default_where_conditions) {
3795
+			if ($model->has_primary_key_field()) {
3796
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3797
+																				. "."
3798
+																				. $model->primary_key_name() ] = array('IS NULL');
3799
+			}/*else{
3800 3800
                 //@todo NO PK, use other defaults
3801 3801
             }*/
3802
-        }
3803
-        return $null_friendly_where_conditions;
3804
-    }
3805
-
3806
-
3807
-
3808
-    /**
3809
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3810
-     * default where conditions on all get_all, update, and delete queries done by this model.
3811
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3812
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3813
-     *
3814
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3815
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3816
-     */
3817
-    private function _get_default_where_conditions($model_relation_path = null)
3818
-    {
3819
-        if ($this->_ignore_where_strategy) {
3820
-            return array();
3821
-        }
3822
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3823
-    }
3824
-
3825
-
3826
-
3827
-    /**
3828
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3829
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3830
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3831
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3832
-     * Similar to _get_default_where_conditions
3833
-     *
3834
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3835
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3836
-     */
3837
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3838
-    {
3839
-        if ($this->_ignore_where_strategy) {
3840
-            return array();
3841
-        }
3842
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3843
-    }
3844
-
3845
-
3846
-
3847
-    /**
3848
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3849
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3850
-     *
3851
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3852
-     * @return string
3853
-     * @throws EE_Error
3854
-     */
3855
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3856
-    {
3857
-        $selects = $this->_get_columns_to_select_for_this_model();
3858
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3859
-            $name_of_other_model_included) {
3860
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3861
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3862
-            foreach ($other_model_selects as $key => $value) {
3863
-                $selects[] = $value;
3864
-            }
3865
-        }
3866
-        return implode(", ", $selects);
3867
-    }
3868
-
3869
-
3870
-
3871
-    /**
3872
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3873
-     * So that's going to be the columns for all the fields on the model
3874
-     *
3875
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3876
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3877
-     */
3878
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3879
-    {
3880
-        $fields = $this->field_settings();
3881
-        $selects = array();
3882
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3883
-            $model_relation_chain,
3884
-            $this->get_this_model_name()
3885
-        );
3886
-        foreach ($fields as $field_obj) {
3887
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3888
-                         . $field_obj->get_table_alias()
3889
-                         . "."
3890
-                         . $field_obj->get_table_column()
3891
-                         . " AS '"
3892
-                         . $table_alias_with_model_relation_chain_prefix
3893
-                         . $field_obj->get_table_alias()
3894
-                         . "."
3895
-                         . $field_obj->get_table_column()
3896
-                         . "'";
3897
-        }
3898
-        // make sure we are also getting the PKs of each table
3899
-        $tables = $this->get_tables();
3900
-        if (count($tables) > 1) {
3901
-            foreach ($tables as $table_obj) {
3902
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3903
-                                       . $table_obj->get_fully_qualified_pk_column();
3904
-                if (! in_array($qualified_pk_column, $selects)) {
3905
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3906
-                }
3907
-            }
3908
-        }
3909
-        return $selects;
3910
-    }
3911
-
3912
-
3913
-
3914
-    /**
3915
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3916
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3917
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3918
-     * SQL for joining, and the data types
3919
-     *
3920
-     * @param null|string                 $original_query_param
3921
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3922
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3923
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3924
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3925
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3926
-     *                                                          or 'Registration's
3927
-     * @param string                      $original_query_param what it originally was (eg
3928
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3929
-     *                                                          matches $query_param
3930
-     * @throws EE_Error
3931
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3932
-     */
3933
-    private function _extract_related_model_info_from_query_param(
3934
-        $query_param,
3935
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3936
-        $query_param_type,
3937
-        $original_query_param = null
3938
-    ) {
3939
-        if ($original_query_param === null) {
3940
-            $original_query_param = $query_param;
3941
-        }
3942
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3943
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3944
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3945
-        $allow_fields = in_array(
3946
-            $query_param_type,
3947
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3948
-            true
3949
-        );
3950
-        // check to see if we have a field on this model
3951
-        $this_model_fields = $this->field_settings(true);
3952
-        if (array_key_exists($query_param, $this_model_fields)) {
3953
-            if ($allow_fields) {
3954
-                return;
3955
-            }
3956
-            throw new EE_Error(
3957
-                sprintf(
3958
-                    __(
3959
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3960
-                        "event_espresso"
3961
-                    ),
3962
-                    $query_param,
3963
-                    get_class($this),
3964
-                    $query_param_type,
3965
-                    $original_query_param
3966
-                )
3967
-            );
3968
-        }
3969
-        // check if this is a special logic query param
3970
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3971
-            if ($allow_logic_query_params) {
3972
-                return;
3973
-            }
3974
-            throw new EE_Error(
3975
-                sprintf(
3976
-                    __(
3977
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3978
-                        'event_espresso'
3979
-                    ),
3980
-                    implode('", "', $this->_logic_query_param_keys),
3981
-                    $query_param,
3982
-                    get_class($this),
3983
-                    '<br />',
3984
-                    "\t"
3985
-                    . ' $passed_in_query_info = <pre>'
3986
-                    . print_r($passed_in_query_info, true)
3987
-                    . '</pre>'
3988
-                    . "\n\t"
3989
-                    . ' $query_param_type = '
3990
-                    . $query_param_type
3991
-                    . "\n\t"
3992
-                    . ' $original_query_param = '
3993
-                    . $original_query_param
3994
-                )
3995
-            );
3996
-        }
3997
-        // check if it's a custom selection
3998
-        if ($this->_custom_selections instanceof CustomSelects
3999
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4000
-        ) {
4001
-            return;
4002
-        }
4003
-        // check if has a model name at the beginning
4004
-        // and
4005
-        // check if it's a field on a related model
4006
-        if ($this->extractJoinModelFromQueryParams(
4007
-            $passed_in_query_info,
4008
-            $query_param,
4009
-            $original_query_param,
4010
-            $query_param_type
4011
-        )) {
4012
-            return;
4013
-        }
4014
-
4015
-        // ok so $query_param didn't start with a model name
4016
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4017
-        // it's wack, that's what it is
4018
-        throw new EE_Error(
4019
-            sprintf(
4020
-                esc_html__(
4021
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4022
-                    "event_espresso"
4023
-                ),
4024
-                $query_param,
4025
-                get_class($this),
4026
-                $query_param_type,
4027
-                $original_query_param
4028
-            )
4029
-        );
4030
-    }
4031
-
4032
-
4033
-    /**
4034
-     * Extracts any possible join model information from the provided possible_join_string.
4035
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4036
-     * parts that should be added to the query.
4037
-     *
4038
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4039
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4040
-     * @param null|string                 $original_query_param
4041
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4042
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4043
-     * @return bool  returns true if a join was added and false if not.
4044
-     * @throws EE_Error
4045
-     */
4046
-    private function extractJoinModelFromQueryParams(
4047
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4048
-        $possible_join_string,
4049
-        $original_query_param,
4050
-        $query_parameter_type
4051
-    ) {
4052
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4053
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4054
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4055
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4056
-                if ($possible_join_string === '') {
4057
-                    // nothing left to $query_param
4058
-                    // we should actually end in a field name, not a model like this!
4059
-                    throw new EE_Error(
4060
-                        sprintf(
4061
-                            esc_html__(
4062
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4063
-                                "event_espresso"
4064
-                            ),
4065
-                            $possible_join_string,
4066
-                            $query_parameter_type,
4067
-                            get_class($this),
4068
-                            $valid_related_model_name
4069
-                        )
4070
-                    );
4071
-                }
4072
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4073
-                $related_model_obj->_extract_related_model_info_from_query_param(
4074
-                    $possible_join_string,
4075
-                    $query_info_carrier,
4076
-                    $query_parameter_type,
4077
-                    $original_query_param
4078
-                );
4079
-                return true;
4080
-            }
4081
-            if ($possible_join_string === $valid_related_model_name) {
4082
-                $this->_add_join_to_model(
4083
-                    $valid_related_model_name,
4084
-                    $query_info_carrier,
4085
-                    $original_query_param
4086
-                );
4087
-                return true;
4088
-            }
4089
-        }
4090
-        return false;
4091
-    }
4092
-
4093
-
4094
-    /**
4095
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4096
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4097
-     * @throws EE_Error
4098
-     */
4099
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4100
-    {
4101
-        if ($this->_custom_selections instanceof CustomSelects
4102
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4103
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4104
-            )
4105
-        ) {
4106
-            $original_selects = $this->_custom_selections->originalSelects();
4107
-            foreach ($original_selects as $alias => $select_configuration) {
4108
-                $this->extractJoinModelFromQueryParams(
4109
-                    $query_info_carrier,
4110
-                    $select_configuration[0],
4111
-                    $select_configuration[0],
4112
-                    'custom_selects'
4113
-                );
4114
-            }
4115
-        }
4116
-    }
4117
-
4118
-
4119
-
4120
-    /**
4121
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4122
-     * and store it on $passed_in_query_info
4123
-     *
4124
-     * @param string                      $model_name
4125
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4126
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4127
-     *                                                          model and $model_name. Eg, if we are querying Event,
4128
-     *                                                          and are adding a join to 'Payment' with the original
4129
-     *                                                          query param key
4130
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4131
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4132
-     *                                                          Payment wants to add default query params so that it
4133
-     *                                                          will know what models to prepend onto its default query
4134
-     *                                                          params or in case it wants to rename tables (in case
4135
-     *                                                          there are multiple joins to the same table)
4136
-     * @return void
4137
-     * @throws EE_Error
4138
-     */
4139
-    private function _add_join_to_model(
4140
-        $model_name,
4141
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4142
-        $original_query_param
4143
-    ) {
4144
-        $relation_obj = $this->related_settings_for($model_name);
4145
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4146
-        // check if the relation is HABTM, because then we're essentially doing two joins
4147
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4148
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4149
-            $join_model_obj = $relation_obj->get_join_model();
4150
-            // replace the model specified with the join model for this relation chain, whi
4151
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4152
-                $model_name,
4153
-                $join_model_obj->get_this_model_name(),
4154
-                $model_relation_chain
4155
-            );
4156
-            $passed_in_query_info->merge(
4157
-                new EE_Model_Query_Info_Carrier(
4158
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4159
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4160
-                )
4161
-            );
4162
-        }
4163
-        // now just join to the other table pointed to by the relation object, and add its data types
4164
-        $passed_in_query_info->merge(
4165
-            new EE_Model_Query_Info_Carrier(
4166
-                array($model_relation_chain => $model_name),
4167
-                $relation_obj->get_join_statement($model_relation_chain)
4168
-            )
4169
-        );
4170
-    }
4171
-
4172
-
4173
-
4174
-    /**
4175
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4176
-     *
4177
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4178
-     * @return string of SQL
4179
-     * @throws EE_Error
4180
-     */
4181
-    private function _construct_where_clause($where_params)
4182
-    {
4183
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4184
-        if ($SQL) {
4185
-            return " WHERE " . $SQL;
4186
-        }
4187
-        return '';
4188
-    }
4189
-
4190
-
4191
-
4192
-    /**
4193
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4194
-     * and should be passed HAVING parameters, not WHERE parameters
4195
-     *
4196
-     * @param array $having_params
4197
-     * @return string
4198
-     * @throws EE_Error
4199
-     */
4200
-    private function _construct_having_clause($having_params)
4201
-    {
4202
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4203
-        if ($SQL) {
4204
-            return " HAVING " . $SQL;
4205
-        }
4206
-        return '';
4207
-    }
4208
-
4209
-
4210
-    /**
4211
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4212
-     * Event_Meta.meta_value = 'foo'))"
4213
-     *
4214
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4215
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4216
-     * @throws EE_Error
4217
-     * @return string of SQL
4218
-     */
4219
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4220
-    {
4221
-        $where_clauses = array();
4222
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4223
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4224
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4225
-                switch ($query_param) {
4226
-                    case 'not':
4227
-                    case 'NOT':
4228
-                        $where_clauses[] = "! ("
4229
-                                           . $this->_construct_condition_clause_recursive(
4230
-                                               $op_and_value_or_sub_condition,
4231
-                                               $glue
4232
-                                           )
4233
-                                           . ")";
4234
-                        break;
4235
-                    case 'and':
4236
-                    case 'AND':
4237
-                        $where_clauses[] = " ("
4238
-                                           . $this->_construct_condition_clause_recursive(
4239
-                                               $op_and_value_or_sub_condition,
4240
-                                               ' AND '
4241
-                                           )
4242
-                                           . ")";
4243
-                        break;
4244
-                    case 'or':
4245
-                    case 'OR':
4246
-                        $where_clauses[] = " ("
4247
-                                           . $this->_construct_condition_clause_recursive(
4248
-                                               $op_and_value_or_sub_condition,
4249
-                                               ' OR '
4250
-                                           )
4251
-                                           . ")";
4252
-                        break;
4253
-                }
4254
-            } else {
4255
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4256
-                // if it's not a normal field, maybe it's a custom selection?
4257
-                if (! $field_obj) {
4258
-                    if ($this->_custom_selections instanceof CustomSelects) {
4259
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4260
-                    } else {
4261
-                        throw new EE_Error(sprintf(__(
4262
-                            "%s is neither a valid model field name, nor a custom selection",
4263
-                            "event_espresso"
4264
-                        ), $query_param));
4265
-                    }
4266
-                }
4267
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4268
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4269
-            }
4270
-        }
4271
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4272
-    }
4273
-
4274
-
4275
-
4276
-    /**
4277
-     * Takes the input parameter and extract the table name (alias) and column name
4278
-     *
4279
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4280
-     * @throws EE_Error
4281
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4282
-     */
4283
-    private function _deduce_column_name_from_query_param($query_param)
4284
-    {
4285
-        $field = $this->_deduce_field_from_query_param($query_param);
4286
-        if ($field) {
4287
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4288
-                $field->get_model_name(),
4289
-                $query_param
4290
-            );
4291
-            return $table_alias_prefix . $field->get_qualified_column();
4292
-        }
4293
-        if ($this->_custom_selections instanceof CustomSelects
4294
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4295
-        ) {
4296
-            // maybe it's custom selection item?
4297
-            // if so, just use it as the "column name"
4298
-            return $query_param;
4299
-        }
4300
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4301
-            ? implode(',', $this->_custom_selections->columnAliases())
4302
-            : '';
4303
-        throw new EE_Error(
4304
-            sprintf(
4305
-                __(
4306
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4307
-                    "event_espresso"
4308
-                ),
4309
-                $query_param,
4310
-                $custom_select_aliases
4311
-            )
4312
-        );
4313
-    }
4314
-
4315
-
4316
-
4317
-    /**
4318
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4319
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4320
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4321
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4322
-     *
4323
-     * @param string $condition_query_param_key
4324
-     * @return string
4325
-     */
4326
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4327
-    {
4328
-        $pos_of_star = strpos($condition_query_param_key, '*');
4329
-        if ($pos_of_star === false) {
4330
-            return $condition_query_param_key;
4331
-        }
4332
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4333
-        return $condition_query_param_sans_star;
4334
-    }
4335
-
4336
-
4337
-
4338
-    /**
4339
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4340
-     *
4341
-     * @param                            mixed      array | string    $op_and_value
4342
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4343
-     * @throws EE_Error
4344
-     * @return string
4345
-     */
4346
-    private function _construct_op_and_value($op_and_value, $field_obj)
4347
-    {
4348
-        if (is_array($op_and_value)) {
4349
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4350
-            if (! $operator) {
4351
-                $php_array_like_string = array();
4352
-                foreach ($op_and_value as $key => $value) {
4353
-                    $php_array_like_string[] = "$key=>$value";
4354
-                }
4355
-                throw new EE_Error(
4356
-                    sprintf(
4357
-                        __(
4358
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4359
-                            "event_espresso"
4360
-                        ),
4361
-                        implode(",", $php_array_like_string)
4362
-                    )
4363
-                );
4364
-            }
4365
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4366
-        } else {
4367
-            $operator = '=';
4368
-            $value = $op_and_value;
4369
-        }
4370
-        // check to see if the value is actually another field
4371
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4372
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4373
-        }
4374
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4375
-            // in this case, the value should be an array, or at least a comma-separated list
4376
-            // it will need to handle a little differently
4377
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4378
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4379
-            return $operator . SP . $cleaned_value;
4380
-        }
4381
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4382
-            // the value should be an array with count of two.
4383
-            if (count($value) !== 2) {
4384
-                throw new EE_Error(
4385
-                    sprintf(
4386
-                        __(
4387
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4388
-                            'event_espresso'
4389
-                        ),
4390
-                        "BETWEEN"
4391
-                    )
4392
-                );
4393
-            }
4394
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4395
-            return $operator . SP . $cleaned_value;
4396
-        }
4397
-        if (in_array($operator, $this->valid_null_style_operators())) {
4398
-            if ($value !== null) {
4399
-                throw new EE_Error(
4400
-                    sprintf(
4401
-                        __(
4402
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4403
-                            "event_espresso"
4404
-                        ),
4405
-                        $value,
4406
-                        $operator
4407
-                    )
4408
-                );
4409
-            }
4410
-            return $operator;
4411
-        }
4412
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4413
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4414
-            // remove other junk. So just treat it as a string.
4415
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4416
-        }
4417
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4418
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4419
-        }
4420
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4421
-            throw new EE_Error(
4422
-                sprintf(
4423
-                    __(
4424
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4425
-                        'event_espresso'
4426
-                    ),
4427
-                    $operator,
4428
-                    $operator
4429
-                )
4430
-            );
4431
-        }
4432
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4433
-            throw new EE_Error(
4434
-                sprintf(
4435
-                    __(
4436
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4437
-                        'event_espresso'
4438
-                    ),
4439
-                    $operator,
4440
-                    $operator
4441
-                )
4442
-            );
4443
-        }
4444
-        throw new EE_Error(
4445
-            sprintf(
4446
-                __(
4447
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4448
-                    "event_espresso"
4449
-                ),
4450
-                http_build_query($op_and_value)
4451
-            )
4452
-        );
4453
-    }
4454
-
4455
-
4456
-
4457
-    /**
4458
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4459
-     *
4460
-     * @param array                      $values
4461
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4462
-     *                                              '%s'
4463
-     * @return string
4464
-     * @throws EE_Error
4465
-     */
4466
-    public function _construct_between_value($values, $field_obj)
4467
-    {
4468
-        $cleaned_values = array();
4469
-        foreach ($values as $value) {
4470
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4471
-        }
4472
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4473
-    }
4474
-
4475
-
4476
-    /**
4477
-     * Takes an array or a comma-separated list of $values and cleans them
4478
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4479
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4480
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4481
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4482
-     *
4483
-     * @param mixed                      $values    array or comma-separated string
4484
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4485
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4486
-     * @throws EE_Error
4487
-     */
4488
-    public function _construct_in_value($values, $field_obj)
4489
-    {
4490
-        $prepped = [];
4491
-        // check if the value is a CSV list
4492
-        if (is_string($values)) {
4493
-            // in which case, turn it into an array
4494
-            $values = explode(',', $values);
4495
-        }
4496
-        // make sure we only have one of each value in the list
4497
-        $values = array_unique($values);
4498
-        foreach ($values as $value) {
4499
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4500
-        }
4501
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4502
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4503
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4504
-        if (empty($prepped)) {
4505
-            $all_fields = $this->field_settings();
4506
-            $first_field    = reset($all_fields);
4507
-            $main_table = $this->_get_main_table();
4508
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4509
-        }
4510
-        return '(' . implode(',', $prepped) . ')';
4511
-    }
4512
-
4513
-
4514
-
4515
-    /**
4516
-     * @param mixed                      $value
4517
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4518
-     * @throws EE_Error
4519
-     * @return false|null|string
4520
-     */
4521
-    private function _wpdb_prepare_using_field($value, $field_obj)
4522
-    {
4523
-        /** @type WPDB $wpdb */
4524
-        global $wpdb;
4525
-        if ($field_obj instanceof EE_Model_Field_Base) {
4526
-            return $wpdb->prepare(
4527
-                $field_obj->get_wpdb_data_type(),
4528
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4529
-            );
4530
-        } //$field_obj should really just be a data type
4531
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4532
-            throw new EE_Error(
4533
-                sprintf(
4534
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4535
-                    $field_obj,
4536
-                    implode(",", $this->_valid_wpdb_data_types)
4537
-                )
4538
-            );
4539
-        }
4540
-        return $wpdb->prepare($field_obj, $value);
4541
-    }
4542
-
4543
-
4544
-
4545
-    /**
4546
-     * Takes the input parameter and finds the model field that it indicates.
4547
-     *
4548
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4549
-     * @throws EE_Error
4550
-     * @return EE_Model_Field_Base
4551
-     */
4552
-    protected function _deduce_field_from_query_param($query_param_name)
4553
-    {
4554
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4555
-        // which will help us find the database table and column
4556
-        $query_param_parts = explode(".", $query_param_name);
4557
-        if (empty($query_param_parts)) {
4558
-            throw new EE_Error(sprintf(__(
4559
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4560
-                'event_espresso'
4561
-            ), $query_param_name));
4562
-        }
4563
-        $number_of_parts = count($query_param_parts);
4564
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4565
-        if ($number_of_parts === 1) {
4566
-            $field_name = $last_query_param_part;
4567
-            $model_obj = $this;
4568
-        } else {// $number_of_parts >= 2
4569
-            // the last part is the column name, and there are only 2parts. therefore...
4570
-            $field_name = $last_query_param_part;
4571
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4572
-        }
4573
-        try {
4574
-            return $model_obj->field_settings_for($field_name);
4575
-        } catch (EE_Error $e) {
4576
-            return null;
4577
-        }
4578
-    }
4579
-
4580
-
4581
-
4582
-    /**
4583
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4584
-     * alias and column which corresponds to it
4585
-     *
4586
-     * @param string $field_name
4587
-     * @throws EE_Error
4588
-     * @return string
4589
-     */
4590
-    public function _get_qualified_column_for_field($field_name)
4591
-    {
4592
-        $all_fields = $this->field_settings();
4593
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4594
-        if ($field) {
4595
-            return $field->get_qualified_column();
4596
-        }
4597
-        throw new EE_Error(
4598
-            sprintf(
4599
-                __(
4600
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4601
-                    'event_espresso'
4602
-                ),
4603
-                $field_name,
4604
-                get_class($this)
4605
-            )
4606
-        );
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4613
-     * Example usage:
4614
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4615
-     *      array(),
4616
-     *      ARRAY_A,
4617
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4618
-     *  );
4619
-     * is equivalent to
4620
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4621
-     * and
4622
-     *  EEM_Event::instance()->get_all_wpdb_results(
4623
-     *      array(
4624
-     *          array(
4625
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4626
-     *          ),
4627
-     *          ARRAY_A,
4628
-     *          implode(
4629
-     *              ', ',
4630
-     *              array_merge(
4631
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4632
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4633
-     *              )
4634
-     *          )
4635
-     *      )
4636
-     *  );
4637
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4638
-     *
4639
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4640
-     *                                            and the one whose fields you are selecting for example: when querying
4641
-     *                                            tickets model and selecting fields from the tickets model you would
4642
-     *                                            leave this parameter empty, because no models are needed to join
4643
-     *                                            between the queried model and the selected one. Likewise when
4644
-     *                                            querying the datetime model and selecting fields from the tickets
4645
-     *                                            model, it would also be left empty, because there is a direct
4646
-     *                                            relation from datetimes to tickets, so no model is needed to join
4647
-     *                                            them together. However, when querying from the event model and
4648
-     *                                            selecting fields from the ticket model, you should provide the string
4649
-     *                                            'Datetime', indicating that the event model must first join to the
4650
-     *                                            datetime model in order to find its relation to ticket model.
4651
-     *                                            Also, when querying from the venue model and selecting fields from
4652
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4653
-     *                                            indicating you need to join the venue model to the event model,
4654
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4655
-     *                                            This string is used to deduce the prefix that gets added onto the
4656
-     *                                            models' tables qualified columns
4657
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4658
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4659
-     *                                            qualified column names
4660
-     * @return array|string
4661
-     */
4662
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4663
-    {
4664
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4665
-        $qualified_columns = array();
4666
-        foreach ($this->field_settings() as $field_name => $field) {
4667
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4668
-        }
4669
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4670
-    }
4671
-
4672
-
4673
-
4674
-    /**
4675
-     * constructs the select use on special limit joins
4676
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4677
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4678
-     * (as that is typically where the limits would be set).
4679
-     *
4680
-     * @param  string       $table_alias The table the select is being built for
4681
-     * @param  mixed|string $limit       The limit for this select
4682
-     * @return string                The final select join element for the query.
4683
-     */
4684
-    public function _construct_limit_join_select($table_alias, $limit)
4685
-    {
4686
-        $SQL = '';
4687
-        foreach ($this->_tables as $table_obj) {
4688
-            if ($table_obj instanceof EE_Primary_Table) {
4689
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4690
-                    ? $table_obj->get_select_join_limit($limit)
4691
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4692
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4693
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4694
-                    ? $table_obj->get_select_join_limit_join($limit)
4695
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4696
-            }
4697
-        }
4698
-        return $SQL;
4699
-    }
4700
-
4701
-
4702
-
4703
-    /**
4704
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4705
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4706
-     *
4707
-     * @return string SQL
4708
-     * @throws EE_Error
4709
-     */
4710
-    public function _construct_internal_join()
4711
-    {
4712
-        $SQL = $this->_get_main_table()->get_table_sql();
4713
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4714
-        return $SQL;
4715
-    }
4716
-
4717
-
4718
-
4719
-    /**
4720
-     * Constructs the SQL for joining all the tables on this model.
4721
-     * Normally $alias should be the primary table's alias, but in cases where
4722
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4723
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4724
-     * alias, this will construct SQL like:
4725
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4726
-     * With $alias being a secondary table's alias, this will construct SQL like:
4727
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4728
-     *
4729
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4730
-     * @return string
4731
-     */
4732
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4733
-    {
4734
-        $SQL = '';
4735
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4736
-        foreach ($this->_tables as $table_obj) {
4737
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4738
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4739
-                    // so we're joining to this table, meaning the table is already in
4740
-                    // the FROM statement, BUT the primary table isn't. So we want
4741
-                    // to add the inverse join sql
4742
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4743
-                } else {
4744
-                    // just add a regular JOIN to this table from the primary table
4745
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4746
-                }
4747
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4748
-        }
4749
-        return $SQL;
4750
-    }
4751
-
4752
-
4753
-
4754
-    /**
4755
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4756
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4757
-     * their data type (eg, '%s', '%d', etc)
4758
-     *
4759
-     * @return array
4760
-     */
4761
-    public function _get_data_types()
4762
-    {
4763
-        $data_types = array();
4764
-        foreach ($this->field_settings() as $field_obj) {
4765
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4766
-            /** @var $field_obj EE_Model_Field_Base */
4767
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4768
-        }
4769
-        return $data_types;
4770
-    }
4771
-
4772
-
4773
-
4774
-    /**
4775
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4776
-     *
4777
-     * @param string $model_name
4778
-     * @throws EE_Error
4779
-     * @return EEM_Base
4780
-     */
4781
-    public function get_related_model_obj($model_name)
4782
-    {
4783
-        $model_classname = "EEM_" . $model_name;
4784
-        if (! class_exists($model_classname)) {
4785
-            throw new EE_Error(sprintf(__(
4786
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4787
-                'event_espresso'
4788
-            ), $model_name, $model_classname));
4789
-        }
4790
-        return call_user_func($model_classname . "::instance");
4791
-    }
4792
-
4793
-
4794
-
4795
-    /**
4796
-     * Returns the array of EE_ModelRelations for this model.
4797
-     *
4798
-     * @return EE_Model_Relation_Base[]
4799
-     */
4800
-    public function relation_settings()
4801
-    {
4802
-        return $this->_model_relations;
4803
-    }
4804
-
4805
-
4806
-
4807
-    /**
4808
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4809
-     * because without THOSE models, this model probably doesn't have much purpose.
4810
-     * (Eg, without an event, datetimes have little purpose.)
4811
-     *
4812
-     * @return EE_Belongs_To_Relation[]
4813
-     */
4814
-    public function belongs_to_relations()
4815
-    {
4816
-        $belongs_to_relations = array();
4817
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4818
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4819
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4820
-            }
4821
-        }
4822
-        return $belongs_to_relations;
4823
-    }
4824
-
4825
-
4826
-
4827
-    /**
4828
-     * Returns the specified EE_Model_Relation, or throws an exception
4829
-     *
4830
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4831
-     * @throws EE_Error
4832
-     * @return EE_Model_Relation_Base
4833
-     */
4834
-    public function related_settings_for($relation_name)
4835
-    {
4836
-        $relatedModels = $this->relation_settings();
4837
-        if (! array_key_exists($relation_name, $relatedModels)) {
4838
-            throw new EE_Error(
4839
-                sprintf(
4840
-                    __(
4841
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4842
-                        'event_espresso'
4843
-                    ),
4844
-                    $relation_name,
4845
-                    $this->_get_class_name(),
4846
-                    implode(', ', array_keys($relatedModels))
4847
-                )
4848
-            );
4849
-        }
4850
-        return $relatedModels[ $relation_name ];
4851
-    }
4852
-
4853
-
4854
-
4855
-    /**
4856
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4857
-     * fields
4858
-     *
4859
-     * @param string $fieldName
4860
-     * @param boolean $include_db_only_fields
4861
-     * @throws EE_Error
4862
-     * @return EE_Model_Field_Base
4863
-     */
4864
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4865
-    {
4866
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4867
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4868
-            throw new EE_Error(sprintf(
4869
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4870
-                $fieldName,
4871
-                get_class($this)
4872
-            ));
4873
-        }
4874
-        return $fieldSettings[ $fieldName ];
4875
-    }
4876
-
4877
-
4878
-
4879
-    /**
4880
-     * Checks if this field exists on this model
4881
-     *
4882
-     * @param string $fieldName a key in the model's _field_settings array
4883
-     * @return boolean
4884
-     */
4885
-    public function has_field($fieldName)
4886
-    {
4887
-        $fieldSettings = $this->field_settings(true);
4888
-        if (isset($fieldSettings[ $fieldName ])) {
4889
-            return true;
4890
-        }
4891
-        return false;
4892
-    }
4893
-
4894
-
4895
-
4896
-    /**
4897
-     * Returns whether or not this model has a relation to the specified model
4898
-     *
4899
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4900
-     * @return boolean
4901
-     */
4902
-    public function has_relation($relation_name)
4903
-    {
4904
-        $relations = $this->relation_settings();
4905
-        if (isset($relations[ $relation_name ])) {
4906
-            return true;
4907
-        }
4908
-        return false;
4909
-    }
4910
-
4911
-
4912
-
4913
-    /**
4914
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4915
-     * Eg, on EE_Answer that would be ANS_ID field object
4916
-     *
4917
-     * @param $field_obj
4918
-     * @return boolean
4919
-     */
4920
-    public function is_primary_key_field($field_obj)
4921
-    {
4922
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4923
-    }
4924
-
4925
-
4926
-
4927
-    /**
4928
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4929
-     * Eg, on EE_Answer that would be ANS_ID field object
4930
-     *
4931
-     * @return EE_Model_Field_Base
4932
-     * @throws EE_Error
4933
-     */
4934
-    public function get_primary_key_field()
4935
-    {
4936
-        if ($this->_primary_key_field === null) {
4937
-            foreach ($this->field_settings(true) as $field_obj) {
4938
-                if ($this->is_primary_key_field($field_obj)) {
4939
-                    $this->_primary_key_field = $field_obj;
4940
-                    break;
4941
-                }
4942
-            }
4943
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4944
-                throw new EE_Error(sprintf(
4945
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4946
-                    get_class($this)
4947
-                ));
4948
-            }
4949
-        }
4950
-        return $this->_primary_key_field;
4951
-    }
4952
-
4953
-
4954
-
4955
-    /**
4956
-     * Returns whether or not not there is a primary key on this model.
4957
-     * Internally does some caching.
4958
-     *
4959
-     * @return boolean
4960
-     */
4961
-    public function has_primary_key_field()
4962
-    {
4963
-        if ($this->_has_primary_key_field === null) {
4964
-            try {
4965
-                $this->get_primary_key_field();
4966
-                $this->_has_primary_key_field = true;
4967
-            } catch (EE_Error $e) {
4968
-                $this->_has_primary_key_field = false;
4969
-            }
4970
-        }
4971
-        return $this->_has_primary_key_field;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * Finds the first field of type $field_class_name.
4978
-     *
4979
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4980
-     *                                 EE_Foreign_Key_Field, etc
4981
-     * @return EE_Model_Field_Base or null if none is found
4982
-     */
4983
-    public function get_a_field_of_type($field_class_name)
4984
-    {
4985
-        foreach ($this->field_settings() as $field) {
4986
-            if ($field instanceof $field_class_name) {
4987
-                return $field;
4988
-            }
4989
-        }
4990
-        return null;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * Gets a foreign key field pointing to model.
4997
-     *
4998
-     * @param string $model_name eg Event, Registration, not EEM_Event
4999
-     * @return EE_Foreign_Key_Field_Base
5000
-     * @throws EE_Error
5001
-     */
5002
-    public function get_foreign_key_to($model_name)
5003
-    {
5004
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5005
-            foreach ($this->field_settings() as $field) {
5006
-                if ($field instanceof EE_Foreign_Key_Field_Base
5007
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5008
-                ) {
5009
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5010
-                    break;
5011
-                }
5012
-            }
5013
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5014
-                throw new EE_Error(sprintf(__(
5015
-                    "There is no foreign key field pointing to model %s on model %s",
5016
-                    'event_espresso'
5017
-                ), $model_name, get_class($this)));
5018
-            }
5019
-        }
5020
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5021
-    }
5022
-
5023
-
5024
-
5025
-    /**
5026
-     * Gets the table name (including $wpdb->prefix) for the table alias
5027
-     *
5028
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5029
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5030
-     *                            Either one works
5031
-     * @return string
5032
-     */
5033
-    public function get_table_for_alias($table_alias)
5034
-    {
5035
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5036
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5037
-    }
5038
-
5039
-
5040
-
5041
-    /**
5042
-     * Returns a flat array of all field son this model, instead of organizing them
5043
-     * by table_alias as they are in the constructor.
5044
-     *
5045
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5046
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5047
-     */
5048
-    public function field_settings($include_db_only_fields = false)
5049
-    {
5050
-        if ($include_db_only_fields) {
5051
-            if ($this->_cached_fields === null) {
5052
-                $this->_cached_fields = array();
5053
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5054
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5055
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5056
-                    }
5057
-                }
5058
-            }
5059
-            return $this->_cached_fields;
5060
-        }
5061
-        if ($this->_cached_fields_non_db_only === null) {
5062
-            $this->_cached_fields_non_db_only = array();
5063
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5064
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5065
-                    /** @var $field_obj EE_Model_Field_Base */
5066
-                    if (! $field_obj->is_db_only_field()) {
5067
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5068
-                    }
5069
-                }
5070
-            }
5071
-        }
5072
-        return $this->_cached_fields_non_db_only;
5073
-    }
5074
-
5075
-
5076
-
5077
-    /**
5078
-     *        cycle though array of attendees and create objects out of each item
5079
-     *
5080
-     * @access        private
5081
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5082
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5083
-     *                           numerically indexed)
5084
-     * @throws EE_Error
5085
-     */
5086
-    protected function _create_objects($rows = array())
5087
-    {
5088
-        $array_of_objects = array();
5089
-        if (empty($rows)) {
5090
-            return array();
5091
-        }
5092
-        $count_if_model_has_no_primary_key = 0;
5093
-        $has_primary_key = $this->has_primary_key_field();
5094
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5095
-        foreach ((array) $rows as $row) {
5096
-            if (empty($row)) {
5097
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5098
-                return array();
5099
-            }
5100
-            // check if we've already set this object in the results array,
5101
-            // in which case there's no need to process it further (again)
5102
-            if ($has_primary_key) {
5103
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5104
-                    $row,
5105
-                    $primary_key_field->get_qualified_column(),
5106
-                    $primary_key_field->get_table_column()
5107
-                );
5108
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5109
-                    continue;
5110
-                }
5111
-            }
5112
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5113
-            if (! $classInstance) {
5114
-                throw new EE_Error(
5115
-                    sprintf(
5116
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5117
-                        $this->get_this_model_name(),
5118
-                        http_build_query($row)
5119
-                    )
5120
-                );
5121
-            }
5122
-            // set the timezone on the instantiated objects
5123
-            $classInstance->set_timezone($this->_timezone);
5124
-            // make sure if there is any timezone setting present that we set the timezone for the object
5125
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5126
-            $array_of_objects[ $key ] = $classInstance;
5127
-            // also, for all the relations of type BelongsTo, see if we can cache
5128
-            // those related models
5129
-            // (we could do this for other relations too, but if there are conditions
5130
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5131
-            // so it requires a little more thought than just caching them immediately...)
5132
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5133
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5134
-                    // check if this model's INFO is present. If so, cache it on the model
5135
-                    $other_model = $relation_obj->get_other_model();
5136
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5137
-                    // if we managed to make a model object from the results, cache it on the main model object
5138
-                    if ($other_model_obj_maybe) {
5139
-                        // set timezone on these other model objects if they are present
5140
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5141
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5142
-                    }
5143
-                }
5144
-            }
5145
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5146
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5147
-            // the field in the CustomSelects object
5148
-            if ($this->_custom_selections instanceof CustomSelects) {
5149
-                $classInstance->setCustomSelectsValues(
5150
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5151
-                );
5152
-            }
5153
-        }
5154
-        return $array_of_objects;
5155
-    }
5156
-
5157
-
5158
-    /**
5159
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5160
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5161
-     *
5162
-     * @param array $db_results_row
5163
-     * @return array
5164
-     */
5165
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5166
-    {
5167
-        $results = array();
5168
-        if ($this->_custom_selections instanceof CustomSelects) {
5169
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5170
-                if (isset($db_results_row[ $alias ])) {
5171
-                    $results[ $alias ] = $this->convertValueToDataType(
5172
-                        $db_results_row[ $alias ],
5173
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5174
-                    );
5175
-                }
5176
-            }
5177
-        }
5178
-        return $results;
5179
-    }
5180
-
5181
-
5182
-    /**
5183
-     * This will set the value for the given alias
5184
-     * @param string $value
5185
-     * @param string $datatype (one of %d, %s, %f)
5186
-     * @return int|string|float (int for %d, string for %s, float for %f)
5187
-     */
5188
-    protected function convertValueToDataType($value, $datatype)
5189
-    {
5190
-        switch ($datatype) {
5191
-            case '%f':
5192
-                return (float) $value;
5193
-            case '%d':
5194
-                return (int) $value;
5195
-            default:
5196
-                return (string) $value;
5197
-        }
5198
-    }
5199
-
5200
-
5201
-    /**
5202
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5203
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5204
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5205
-     * object (as set in the model_field!).
5206
-     *
5207
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5208
-     */
5209
-    public function create_default_object()
5210
-    {
5211
-        $this_model_fields_and_values = array();
5212
-        // setup the row using default values;
5213
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5214
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5215
-        }
5216
-        $className = $this->_get_class_name();
5217
-        $classInstance = EE_Registry::instance()
5218
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5219
-        return $classInstance;
5220
-    }
5221
-
5222
-
5223
-
5224
-    /**
5225
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5226
-     *                             or an stdClass where each property is the name of a column,
5227
-     * @return EE_Base_Class
5228
-     * @throws EE_Error
5229
-     */
5230
-    public function instantiate_class_from_array_or_object($cols_n_values)
5231
-    {
5232
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5233
-            $cols_n_values = get_object_vars($cols_n_values);
5234
-        }
5235
-        $primary_key = null;
5236
-        // make sure the array only has keys that are fields/columns on this model
5237
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5238
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5239
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5240
-        }
5241
-        $className = $this->_get_class_name();
5242
-        // check we actually found results that we can use to build our model object
5243
-        // if not, return null
5244
-        if ($this->has_primary_key_field()) {
5245
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5246
-                return null;
5247
-            }
5248
-        } elseif ($this->unique_indexes()) {
5249
-            $first_column = reset($this_model_fields_n_values);
5250
-            if (empty($first_column)) {
5251
-                return null;
5252
-            }
5253
-        }
5254
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5255
-        if ($primary_key) {
5256
-            $classInstance = $this->get_from_entity_map($primary_key);
5257
-            if (! $classInstance) {
5258
-                $classInstance = EE_Registry::instance()
5259
-                                            ->load_class(
5260
-                                                $className,
5261
-                                                array($this_model_fields_n_values, $this->_timezone),
5262
-                                                true,
5263
-                                                false
5264
-                                            );
5265
-                // add this new object to the entity map
5266
-                $classInstance = $this->add_to_entity_map($classInstance);
5267
-            }
5268
-        } else {
5269
-            $classInstance = EE_Registry::instance()
5270
-                                        ->load_class(
5271
-                                            $className,
5272
-                                            array($this_model_fields_n_values, $this->_timezone),
5273
-                                            true,
5274
-                                            false
5275
-                                        );
5276
-        }
5277
-        return $classInstance;
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Gets the model object from the  entity map if it exists
5284
-     *
5285
-     * @param int|string $id the ID of the model object
5286
-     * @return EE_Base_Class
5287
-     */
5288
-    public function get_from_entity_map($id)
5289
-    {
5290
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5291
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5292
-    }
5293
-
5294
-
5295
-
5296
-    /**
5297
-     * add_to_entity_map
5298
-     * Adds the object to the model's entity mappings
5299
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5300
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5301
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5302
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5303
-     *        then this method should be called immediately after the update query
5304
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5305
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5306
-     *
5307
-     * @param    EE_Base_Class $object
5308
-     * @throws EE_Error
5309
-     * @return \EE_Base_Class
5310
-     */
5311
-    public function add_to_entity_map(EE_Base_Class $object)
5312
-    {
5313
-        $className = $this->_get_class_name();
5314
-        if (! $object instanceof $className) {
5315
-            throw new EE_Error(sprintf(
5316
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5317
-                is_object($object) ? get_class($object) : $object,
5318
-                $className
5319
-            ));
5320
-        }
5321
-        /** @var $object EE_Base_Class */
5322
-        if (! $object->ID()) {
5323
-            throw new EE_Error(sprintf(__(
5324
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5325
-                "event_espresso"
5326
-            ), get_class($this)));
5327
-        }
5328
-        // double check it's not already there
5329
-        $classInstance = $this->get_from_entity_map($object->ID());
5330
-        if ($classInstance) {
5331
-            return $classInstance;
5332
-        }
5333
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5334
-        return $object;
5335
-    }
5336
-
5337
-
5338
-
5339
-    /**
5340
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5341
-     * if no identifier is provided, then the entire entity map is emptied
5342
-     *
5343
-     * @param int|string $id the ID of the model object
5344
-     * @return boolean
5345
-     */
5346
-    public function clear_entity_map($id = null)
5347
-    {
5348
-        if (empty($id)) {
5349
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5350
-            return true;
5351
-        }
5352
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5353
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5354
-            return true;
5355
-        }
5356
-        return false;
5357
-    }
5358
-
5359
-
5360
-
5361
-    /**
5362
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5363
-     * Given an array where keys are column (or column alias) names and values,
5364
-     * returns an array of their corresponding field names and database values
5365
-     *
5366
-     * @param array $cols_n_values
5367
-     * @return array
5368
-     */
5369
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5370
-    {
5371
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5372
-    }
5373
-
5374
-
5375
-
5376
-    /**
5377
-     * _deduce_fields_n_values_from_cols_n_values
5378
-     * Given an array where keys are column (or column alias) names and values,
5379
-     * returns an array of their corresponding field names and database values
5380
-     *
5381
-     * @param string $cols_n_values
5382
-     * @return array
5383
-     */
5384
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5385
-    {
5386
-        $this_model_fields_n_values = array();
5387
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5388
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5389
-                $cols_n_values,
5390
-                $table_obj->get_fully_qualified_pk_column(),
5391
-                $table_obj->get_pk_column()
5392
-            );
5393
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5394
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5395
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5396
-                    if (! $field_obj->is_db_only_field()) {
5397
-                        // prepare field as if its coming from db
5398
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5399
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5400
-                    }
5401
-                }
5402
-            } else {
5403
-                // the table's rows existed. Use their values
5404
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5405
-                    if (! $field_obj->is_db_only_field()) {
5406
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5407
-                            $cols_n_values,
5408
-                            $field_obj->get_qualified_column(),
5409
-                            $field_obj->get_table_column()
5410
-                        );
5411
-                    }
5412
-                }
5413
-            }
5414
-        }
5415
-        return $this_model_fields_n_values;
5416
-    }
5417
-
5418
-
5419
-    /**
5420
-     * @param $cols_n_values
5421
-     * @param $qualified_column
5422
-     * @param $regular_column
5423
-     * @return null
5424
-     * @throws EE_Error
5425
-     * @throws ReflectionException
5426
-     */
5427
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5428
-    {
5429
-        $value = null;
5430
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5431
-        // does the field on the model relate to this column retrieved from the db?
5432
-        // or is it a db-only field? (not relating to the model)
5433
-        if (isset($cols_n_values[ $qualified_column ])) {
5434
-            $value = $cols_n_values[ $qualified_column ];
5435
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5436
-            $value = $cols_n_values[ $regular_column ];
5437
-        } elseif (! empty($this->foreign_key_aliases)) {
5438
-            // no PK?  ok check if there is a foreign key alias set for this table
5439
-            // then check if that alias exists in the incoming data
5440
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5441
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5442
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5443
-                    $value = $cols_n_values[ $FK_alias ];
5444
-                    list($pk_class) = explode('.', $PK_column);
5445
-                    $pk_model_name = "EEM_{$pk_class}";
5446
-                    /** @var EEM_Base $pk_model */
5447
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5448
-                    if ($pk_model instanceof EEM_Base) {
5449
-                        // make sure object is pulled from db and added to entity map
5450
-                        $pk_model->get_one_by_ID($value);
5451
-                    }
5452
-                    break;
5453
-                }
5454
-            }
5455
-        }
5456
-        return $value;
5457
-    }
5458
-
5459
-
5460
-
5461
-    /**
5462
-     * refresh_entity_map_from_db
5463
-     * Makes sure the model object in the entity map at $id assumes the values
5464
-     * of the database (opposite of EE_base_Class::save())
5465
-     *
5466
-     * @param int|string $id
5467
-     * @return EE_Base_Class
5468
-     * @throws EE_Error
5469
-     */
5470
-    public function refresh_entity_map_from_db($id)
5471
-    {
5472
-        $obj_in_map = $this->get_from_entity_map($id);
5473
-        if ($obj_in_map) {
5474
-            $wpdb_results = $this->_get_all_wpdb_results(
5475
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5476
-            );
5477
-            if ($wpdb_results && is_array($wpdb_results)) {
5478
-                $one_row = reset($wpdb_results);
5479
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5480
-                    $obj_in_map->set_from_db($field_name, $db_value);
5481
-                }
5482
-                // clear the cache of related model objects
5483
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5484
-                    $obj_in_map->clear_cache($relation_name, null, true);
5485
-                }
5486
-            }
5487
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5488
-            return $obj_in_map;
5489
-        }
5490
-        return $this->get_one_by_ID($id);
5491
-    }
5492
-
5493
-
5494
-
5495
-    /**
5496
-     * refresh_entity_map_with
5497
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5498
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5499
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5500
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5501
-     *
5502
-     * @param int|string    $id
5503
-     * @param EE_Base_Class $replacing_model_obj
5504
-     * @return \EE_Base_Class
5505
-     * @throws EE_Error
5506
-     */
5507
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5508
-    {
5509
-        $obj_in_map = $this->get_from_entity_map($id);
5510
-        if ($obj_in_map) {
5511
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5512
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5513
-                    $obj_in_map->set($field_name, $value);
5514
-                }
5515
-                // make the model object in the entity map's cache match the $replacing_model_obj
5516
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5517
-                    $obj_in_map->clear_cache($relation_name, null, true);
5518
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5519
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5520
-                    }
5521
-                }
5522
-            }
5523
-            return $obj_in_map;
5524
-        }
5525
-        $this->add_to_entity_map($replacing_model_obj);
5526
-        return $replacing_model_obj;
5527
-    }
5528
-
5529
-
5530
-
5531
-    /**
5532
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5533
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5534
-     * require_once($this->_getClassName().".class.php");
5535
-     *
5536
-     * @return string
5537
-     */
5538
-    private function _get_class_name()
5539
-    {
5540
-        return "EE_" . $this->get_this_model_name();
5541
-    }
5542
-
5543
-
5544
-
5545
-    /**
5546
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5547
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5548
-     * it would be 'Events'.
5549
-     *
5550
-     * @param int $quantity
5551
-     * @return string
5552
-     */
5553
-    public function item_name($quantity = 1)
5554
-    {
5555
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5556
-    }
5557
-
5558
-
5559
-
5560
-    /**
5561
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5562
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5563
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5564
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5565
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5566
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5567
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5568
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5569
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5570
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5571
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5572
-     *        return $previousReturnValue.$returnString;
5573
-     * }
5574
-     * require('EEM_Answer.model.php');
5575
-     * $answer=EEM_Answer::instance();
5576
-     * echo $answer->my_callback('monkeys',100);
5577
-     * //will output "you called my_callback! and passed args:monkeys,100"
5578
-     *
5579
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5580
-     * @param array  $args       array of original arguments passed to the function
5581
-     * @throws EE_Error
5582
-     * @return mixed whatever the plugin which calls add_filter decides
5583
-     */
5584
-    public function __call($methodName, $args)
5585
-    {
5586
-        $className = get_class($this);
5587
-        $tagName = "FHEE__{$className}__{$methodName}";
5588
-        if (! has_filter($tagName)) {
5589
-            throw new EE_Error(
5590
-                sprintf(
5591
-                    __(
5592
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5593
-                        'event_espresso'
5594
-                    ),
5595
-                    $methodName,
5596
-                    $className,
5597
-                    $tagName,
5598
-                    '<br />'
5599
-                )
5600
-            );
5601
-        }
5602
-        return apply_filters($tagName, null, $this, $args);
5603
-    }
5604
-
5605
-
5606
-
5607
-    /**
5608
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5609
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5610
-     *
5611
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5612
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5613
-     *                                                       the object's class name
5614
-     *                                                       or object's ID
5615
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5616
-     *                                                       exists in the database. If it does not, we add it
5617
-     * @throws EE_Error
5618
-     * @return EE_Base_Class
5619
-     */
5620
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5621
-    {
5622
-        $className = $this->_get_class_name();
5623
-        if ($base_class_obj_or_id instanceof $className) {
5624
-            $model_object = $base_class_obj_or_id;
5625
-        } else {
5626
-            $primary_key_field = $this->get_primary_key_field();
5627
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5628
-                && (
5629
-                    is_int($base_class_obj_or_id)
5630
-                    || is_string($base_class_obj_or_id)
5631
-                )
5632
-            ) {
5633
-                // assume it's an ID.
5634
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5635
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5636
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5637
-                && is_string($base_class_obj_or_id)
5638
-            ) {
5639
-                // assume its a string representation of the object
5640
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
-            } else {
5642
-                throw new EE_Error(
5643
-                    sprintf(
5644
-                        __(
5645
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5646
-                            'event_espresso'
5647
-                        ),
5648
-                        $base_class_obj_or_id,
5649
-                        $this->_get_class_name(),
5650
-                        print_r($base_class_obj_or_id, true)
5651
-                    )
5652
-                );
5653
-            }
5654
-        }
5655
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5656
-            $model_object->save();
5657
-        }
5658
-        return $model_object;
5659
-    }
5660
-
5661
-
5662
-
5663
-    /**
5664
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5665
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5666
-     * returns it ID.
5667
-     *
5668
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5669
-     * @return int|string depending on the type of this model object's ID
5670
-     * @throws EE_Error
5671
-     */
5672
-    public function ensure_is_ID($base_class_obj_or_id)
5673
-    {
5674
-        $className = $this->_get_class_name();
5675
-        if ($base_class_obj_or_id instanceof $className) {
5676
-            /** @var $base_class_obj_or_id EE_Base_Class */
5677
-            $id = $base_class_obj_or_id->ID();
5678
-        } elseif (is_int($base_class_obj_or_id)) {
5679
-            // assume it's an ID
5680
-            $id = $base_class_obj_or_id;
5681
-        } elseif (is_string($base_class_obj_or_id)) {
5682
-            // assume its a string representation of the object
5683
-            $id = $base_class_obj_or_id;
5684
-        } else {
5685
-            throw new EE_Error(sprintf(
5686
-                __(
5687
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5688
-                    'event_espresso'
5689
-                ),
5690
-                $base_class_obj_or_id,
5691
-                $this->_get_class_name(),
5692
-                print_r($base_class_obj_or_id, true)
5693
-            ));
5694
-        }
5695
-        return $id;
5696
-    }
5697
-
5698
-
5699
-
5700
-    /**
5701
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5702
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5703
-     * been sanitized and converted into the appropriate domain.
5704
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5705
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5706
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5707
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5708
-     * $EVT = EEM_Event::instance(); $old_setting =
5709
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5710
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5711
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5712
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5713
-     *
5714
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5715
-     * @return void
5716
-     */
5717
-    public function assume_values_already_prepared_by_model_object(
5718
-        $values_already_prepared = self::not_prepared_by_model_object
5719
-    ) {
5720
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5721
-    }
5722
-
5723
-
5724
-
5725
-    /**
5726
-     * Read comments for assume_values_already_prepared_by_model_object()
5727
-     *
5728
-     * @return int
5729
-     */
5730
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5731
-    {
5732
-        return $this->_values_already_prepared_by_model_object;
5733
-    }
5734
-
5735
-
5736
-
5737
-    /**
5738
-     * Gets all the indexes on this model
5739
-     *
5740
-     * @return EE_Index[]
5741
-     */
5742
-    public function indexes()
5743
-    {
5744
-        return $this->_indexes;
5745
-    }
5746
-
5747
-
5748
-
5749
-    /**
5750
-     * Gets all the Unique Indexes on this model
5751
-     *
5752
-     * @return EE_Unique_Index[]
5753
-     */
5754
-    public function unique_indexes()
5755
-    {
5756
-        $unique_indexes = array();
5757
-        foreach ($this->_indexes as $name => $index) {
5758
-            if ($index instanceof EE_Unique_Index) {
5759
-                $unique_indexes [ $name ] = $index;
5760
-            }
5761
-        }
5762
-        return $unique_indexes;
5763
-    }
5764
-
5765
-
5766
-
5767
-    /**
5768
-     * Gets all the fields which, when combined, make the primary key.
5769
-     * This is usually just an array with 1 element (the primary key), but in cases
5770
-     * where there is no primary key, it's a combination of fields as defined
5771
-     * on a primary index
5772
-     *
5773
-     * @return EE_Model_Field_Base[] indexed by the field's name
5774
-     * @throws EE_Error
5775
-     */
5776
-    public function get_combined_primary_key_fields()
5777
-    {
5778
-        foreach ($this->indexes() as $index) {
5779
-            if ($index instanceof EE_Primary_Key_Index) {
5780
-                return $index->fields();
5781
-            }
5782
-        }
5783
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5784
-    }
5785
-
5786
-
5787
-
5788
-    /**
5789
-     * Used to build a primary key string (when the model has no primary key),
5790
-     * which can be used a unique string to identify this model object.
5791
-     *
5792
-     * @param array $fields_n_values keys are field names, values are their values.
5793
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5794
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5795
-     *                               before passing it to this function (that will convert it from columns-n-values
5796
-     *                               to field-names-n-values).
5797
-     * @return string
5798
-     * @throws EE_Error
5799
-     */
5800
-    public function get_index_primary_key_string($fields_n_values)
5801
-    {
5802
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5803
-            $fields_n_values,
5804
-            $this->get_combined_primary_key_fields()
5805
-        );
5806
-        return http_build_query($cols_n_values_for_primary_key_index);
5807
-    }
5808
-
5809
-
5810
-
5811
-    /**
5812
-     * Gets the field values from the primary key string
5813
-     *
5814
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5815
-     * @param string $index_primary_key_string
5816
-     * @return null|array
5817
-     * @throws EE_Error
5818
-     */
5819
-    public function parse_index_primary_key_string($index_primary_key_string)
5820
-    {
5821
-        $key_fields = $this->get_combined_primary_key_fields();
5822
-        // check all of them are in the $id
5823
-        $key_vals_in_combined_pk = array();
5824
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5825
-        foreach ($key_fields as $key_field_name => $field_obj) {
5826
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5827
-                return null;
5828
-            }
5829
-        }
5830
-        return $key_vals_in_combined_pk;
5831
-    }
5832
-
5833
-
5834
-
5835
-    /**
5836
-     * verifies that an array of key-value pairs for model fields has a key
5837
-     * for each field comprising the primary key index
5838
-     *
5839
-     * @param array $key_vals
5840
-     * @return boolean
5841
-     * @throws EE_Error
5842
-     */
5843
-    public function has_all_combined_primary_key_fields($key_vals)
5844
-    {
5845
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5846
-        foreach ($keys_it_should_have as $key) {
5847
-            if (! isset($key_vals[ $key ])) {
5848
-                return false;
5849
-            }
5850
-        }
5851
-        return true;
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5858
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5859
-     *
5860
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5861
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5862
-     * @throws EE_Error
5863
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5864
-     *                                                              indexed)
5865
-     */
5866
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5867
-    {
5868
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5869
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5870
-        } elseif (is_array($model_object_or_attributes_array)) {
5871
-            $attributes_array = $model_object_or_attributes_array;
5872
-        } else {
5873
-            throw new EE_Error(sprintf(__(
5874
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5875
-                "event_espresso"
5876
-            ), $model_object_or_attributes_array));
5877
-        }
5878
-        // even copies obviously won't have the same ID, so remove the primary key
5879
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5880
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5881
-            unset($attributes_array[ $this->primary_key_name() ]);
5882
-        }
5883
-        if (isset($query_params[0])) {
5884
-            $query_params[0] = array_merge($attributes_array, $query_params);
5885
-        } else {
5886
-            $query_params[0] = $attributes_array;
5887
-        }
5888
-        return $this->get_all($query_params);
5889
-    }
5890
-
5891
-
5892
-
5893
-    /**
5894
-     * Gets the first copy we find. See get_all_copies for more details
5895
-     *
5896
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5897
-     * @param array $query_params
5898
-     * @return EE_Base_Class
5899
-     * @throws EE_Error
5900
-     */
5901
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5902
-    {
5903
-        if (! is_array($query_params)) {
5904
-            EE_Error::doing_it_wrong(
5905
-                'EEM_Base::get_one_copy',
5906
-                sprintf(
5907
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5908
-                    gettype($query_params)
5909
-                ),
5910
-                '4.6.0'
5911
-            );
5912
-            $query_params = array();
5913
-        }
5914
-        $query_params['limit'] = 1;
5915
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5916
-        if (is_array($copies)) {
5917
-            return array_shift($copies);
5918
-        }
5919
-        return null;
5920
-    }
5921
-
5922
-
5923
-
5924
-    /**
5925
-     * Updates the item with the specified id. Ignores default query parameters because
5926
-     * we have specified the ID, and its assumed we KNOW what we're doing
5927
-     *
5928
-     * @param array      $fields_n_values keys are field names, values are their new values
5929
-     * @param int|string $id              the value of the primary key to update
5930
-     * @return int number of rows updated
5931
-     * @throws EE_Error
5932
-     */
5933
-    public function update_by_ID($fields_n_values, $id)
5934
-    {
5935
-        $query_params = array(
5936
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5937
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5938
-        );
5939
-        return $this->update($fields_n_values, $query_params);
5940
-    }
5941
-
5942
-
5943
-
5944
-    /**
5945
-     * Changes an operator which was supplied to the models into one usable in SQL
5946
-     *
5947
-     * @param string $operator_supplied
5948
-     * @return string an operator which can be used in SQL
5949
-     * @throws EE_Error
5950
-     */
5951
-    private function _prepare_operator_for_sql($operator_supplied)
5952
-    {
5953
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5954
-            : null;
5955
-        if ($sql_operator) {
5956
-            return $sql_operator;
5957
-        }
5958
-        throw new EE_Error(
5959
-            sprintf(
5960
-                __(
5961
-                    "The operator '%s' is not in the list of valid operators: %s",
5962
-                    "event_espresso"
5963
-                ),
5964
-                $operator_supplied,
5965
-                implode(",", array_keys($this->_valid_operators))
5966
-            )
5967
-        );
5968
-    }
5969
-
5970
-
5971
-
5972
-    /**
5973
-     * Gets the valid operators
5974
-     * @return array keys are accepted strings, values are the SQL they are converted to
5975
-     */
5976
-    public function valid_operators()
5977
-    {
5978
-        return $this->_valid_operators;
5979
-    }
5980
-
5981
-
5982
-
5983
-    /**
5984
-     * Gets the between-style operators (take 2 arguments).
5985
-     * @return array keys are accepted strings, values are the SQL they are converted to
5986
-     */
5987
-    public function valid_between_style_operators()
5988
-    {
5989
-        return array_intersect(
5990
-            $this->valid_operators(),
5991
-            $this->_between_style_operators
5992
-        );
5993
-    }
5994
-
5995
-    /**
5996
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5997
-     * @return array keys are accepted strings, values are the SQL they are converted to
5998
-     */
5999
-    public function valid_like_style_operators()
6000
-    {
6001
-        return array_intersect(
6002
-            $this->valid_operators(),
6003
-            $this->_like_style_operators
6004
-        );
6005
-    }
6006
-
6007
-    /**
6008
-     * Gets the "in"-style operators
6009
-     * @return array keys are accepted strings, values are the SQL they are converted to
6010
-     */
6011
-    public function valid_in_style_operators()
6012
-    {
6013
-        return array_intersect(
6014
-            $this->valid_operators(),
6015
-            $this->_in_style_operators
6016
-        );
6017
-    }
6018
-
6019
-    /**
6020
-     * Gets the "null"-style operators (accept no arguments)
6021
-     * @return array keys are accepted strings, values are the SQL they are converted to
6022
-     */
6023
-    public function valid_null_style_operators()
6024
-    {
6025
-        return array_intersect(
6026
-            $this->valid_operators(),
6027
-            $this->_null_style_operators
6028
-        );
6029
-    }
6030
-
6031
-    /**
6032
-     * Gets an array where keys are the primary keys and values are their 'names'
6033
-     * (as determined by the model object's name() function, which is often overridden)
6034
-     *
6035
-     * @param array $query_params like get_all's
6036
-     * @return string[]
6037
-     * @throws EE_Error
6038
-     */
6039
-    public function get_all_names($query_params = array())
6040
-    {
6041
-        $objs = $this->get_all($query_params);
6042
-        $names = array();
6043
-        foreach ($objs as $obj) {
6044
-            $names[ $obj->ID() ] = $obj->name();
6045
-        }
6046
-        return $names;
6047
-    }
6048
-
6049
-
6050
-
6051
-    /**
6052
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6053
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6054
-     * this is duplicated effort and reduces efficiency) you would be better to use
6055
-     * array_keys() on $model_objects.
6056
-     *
6057
-     * @param \EE_Base_Class[] $model_objects
6058
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6059
-     *                                               in the returned array
6060
-     * @return array
6061
-     * @throws EE_Error
6062
-     */
6063
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6064
-    {
6065
-        if (! $this->has_primary_key_field()) {
6066
-            if (WP_DEBUG) {
6067
-                EE_Error::add_error(
6068
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6069
-                    __FILE__,
6070
-                    __FUNCTION__,
6071
-                    __LINE__
6072
-                );
6073
-            }
6074
-        }
6075
-        $IDs = array();
6076
-        foreach ($model_objects as $model_object) {
6077
-            $id = $model_object->ID();
6078
-            if (! $id) {
6079
-                if ($filter_out_empty_ids) {
6080
-                    continue;
6081
-                }
6082
-                if (WP_DEBUG) {
6083
-                    EE_Error::add_error(
6084
-                        __(
6085
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6086
-                            'event_espresso'
6087
-                        ),
6088
-                        __FILE__,
6089
-                        __FUNCTION__,
6090
-                        __LINE__
6091
-                    );
6092
-                }
6093
-            }
6094
-            $IDs[] = $id;
6095
-        }
6096
-        return $IDs;
6097
-    }
6098
-
6099
-
6100
-
6101
-    /**
6102
-     * Returns the string used in capabilities relating to this model. If there
6103
-     * are no capabilities that relate to this model returns false
6104
-     *
6105
-     * @return string|false
6106
-     */
6107
-    public function cap_slug()
6108
-    {
6109
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6110
-    }
6111
-
6112
-
6113
-
6114
-    /**
6115
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6116
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6117
-     * only returns the cap restrictions array in that context (ie, the array
6118
-     * at that key)
6119
-     *
6120
-     * @param string $context
6121
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6122
-     * @throws EE_Error
6123
-     */
6124
-    public function cap_restrictions($context = EEM_Base::caps_read)
6125
-    {
6126
-        EEM_Base::verify_is_valid_cap_context($context);
6127
-        // check if we ought to run the restriction generator first
6128
-        if (isset($this->_cap_restriction_generators[ $context ])
6129
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6130
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6131
-        ) {
6132
-            $this->_cap_restrictions[ $context ] = array_merge(
6133
-                $this->_cap_restrictions[ $context ],
6134
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6135
-            );
6136
-        }
6137
-        // and make sure we've finalized the construction of each restriction
6138
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6139
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6140
-                $where_conditions_obj->_finalize_construct($this);
6141
-            }
6142
-        }
6143
-        return $this->_cap_restrictions[ $context ];
6144
-    }
6145
-
6146
-
6147
-
6148
-    /**
6149
-     * Indicating whether or not this model thinks its a wp core model
6150
-     *
6151
-     * @return boolean
6152
-     */
6153
-    public function is_wp_core_model()
6154
-    {
6155
-        return $this->_wp_core_model;
6156
-    }
6157
-
6158
-
6159
-
6160
-    /**
6161
-     * Gets all the caps that are missing which impose a restriction on
6162
-     * queries made in this context
6163
-     *
6164
-     * @param string $context one of EEM_Base::caps_ constants
6165
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6166
-     * @throws EE_Error
6167
-     */
6168
-    public function caps_missing($context = EEM_Base::caps_read)
6169
-    {
6170
-        $missing_caps = array();
6171
-        $cap_restrictions = $this->cap_restrictions($context);
6172
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6173
-            if (! EE_Capabilities::instance()
6174
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6175
-            ) {
6176
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6177
-            }
6178
-        }
6179
-        return $missing_caps;
6180
-    }
6181
-
6182
-
6183
-
6184
-    /**
6185
-     * Gets the mapping from capability contexts to action strings used in capability names
6186
-     *
6187
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6188
-     * one of 'read', 'edit', or 'delete'
6189
-     */
6190
-    public function cap_contexts_to_cap_action_map()
6191
-    {
6192
-        return apply_filters(
6193
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6194
-            $this->_cap_contexts_to_cap_action_map,
6195
-            $this
6196
-        );
6197
-    }
6198
-
6199
-
6200
-
6201
-    /**
6202
-     * Gets the action string for the specified capability context
6203
-     *
6204
-     * @param string $context
6205
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6206
-     * @throws EE_Error
6207
-     */
6208
-    public function cap_action_for_context($context)
6209
-    {
6210
-        $mapping = $this->cap_contexts_to_cap_action_map();
6211
-        if (isset($mapping[ $context ])) {
6212
-            return $mapping[ $context ];
6213
-        }
6214
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6215
-            return $action;
6216
-        }
6217
-        throw new EE_Error(
6218
-            sprintf(
6219
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6220
-                $context,
6221
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6222
-            )
6223
-        );
6224
-    }
6225
-
6226
-
6227
-
6228
-    /**
6229
-     * Returns all the capability contexts which are valid when querying models
6230
-     *
6231
-     * @return array
6232
-     */
6233
-    public static function valid_cap_contexts()
6234
-    {
6235
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6236
-            self::caps_read,
6237
-            self::caps_read_admin,
6238
-            self::caps_edit,
6239
-            self::caps_delete,
6240
-        ));
6241
-    }
6242
-
6243
-
6244
-
6245
-    /**
6246
-     * Returns all valid options for 'default_where_conditions'
6247
-     *
6248
-     * @return array
6249
-     */
6250
-    public static function valid_default_where_conditions()
6251
-    {
6252
-        return array(
6253
-            EEM_Base::default_where_conditions_all,
6254
-            EEM_Base::default_where_conditions_this_only,
6255
-            EEM_Base::default_where_conditions_others_only,
6256
-            EEM_Base::default_where_conditions_minimum_all,
6257
-            EEM_Base::default_where_conditions_minimum_others,
6258
-            EEM_Base::default_where_conditions_none
6259
-        );
6260
-    }
6261
-
6262
-    // public static function default_where_conditions_full
6263
-    /**
6264
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6265
-     *
6266
-     * @param string $context
6267
-     * @return bool
6268
-     * @throws EE_Error
6269
-     */
6270
-    public static function verify_is_valid_cap_context($context)
6271
-    {
6272
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6273
-        if (in_array($context, $valid_cap_contexts)) {
6274
-            return true;
6275
-        }
6276
-        throw new EE_Error(
6277
-            sprintf(
6278
-                __(
6279
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6280
-                    'event_espresso'
6281
-                ),
6282
-                $context,
6283
-                'EEM_Base',
6284
-                implode(',', $valid_cap_contexts)
6285
-            )
6286
-        );
6287
-    }
6288
-
6289
-
6290
-
6291
-    /**
6292
-     * Clears all the models field caches. This is only useful when a sub-class
6293
-     * might have added a field or something and these caches might be invalidated
6294
-     */
6295
-    protected function _invalidate_field_caches()
6296
-    {
6297
-        $this->_cache_foreign_key_to_fields = array();
6298
-        $this->_cached_fields = null;
6299
-        $this->_cached_fields_non_db_only = null;
6300
-    }
6301
-
6302
-
6303
-
6304
-    /**
6305
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6306
-     * (eg "and", "or", "not").
6307
-     *
6308
-     * @return array
6309
-     */
6310
-    public function logic_query_param_keys()
6311
-    {
6312
-        return $this->_logic_query_param_keys;
6313
-    }
6314
-
6315
-
6316
-
6317
-    /**
6318
-     * Determines whether or not the where query param array key is for a logic query param.
6319
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6320
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6321
-     *
6322
-     * @param $query_param_key
6323
-     * @return bool
6324
-     */
6325
-    public function is_logic_query_param_key($query_param_key)
6326
-    {
6327
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6328
-            if ($query_param_key === $logic_query_param_key
6329
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6330
-            ) {
6331
-                return true;
6332
-            }
6333
-        }
6334
-        return false;
6335
-    }
6336
-
6337
-    /**
6338
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6339
-     * @since 4.9.74.p
6340
-     * @return boolean
6341
-     */
6342
-    public function hasPassword()
6343
-    {
6344
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6345
-        if ($this->has_password_field === null) {
6346
-            $password_field = $this->getPasswordField();
6347
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6348
-        }
6349
-        return $this->has_password_field;
6350
-    }
6351
-
6352
-    /**
6353
-     * Returns the password field on this model, if there is one
6354
-     * @since 4.9.74.p
6355
-     * @return EE_Password_Field|null
6356
-     */
6357
-    public function getPasswordField()
6358
-    {
6359
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6360
-        // there's no need to search for it. If we don't know yet, then find out
6361
-        if ($this->has_password_field === null && $this->password_field === null) {
6362
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6363
-        }
6364
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6365
-        return $this->password_field;
6366
-    }
6367
-
6368
-
6369
-    /**
6370
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6371
-     * @since 4.9.74.p
6372
-     * @return EE_Model_Field_Base[]
6373
-     * @throws EE_Error
6374
-     */
6375
-    public function getPasswordProtectedFields()
6376
-    {
6377
-        $password_field = $this->getPasswordField();
6378
-        $fields = array();
6379
-        if ($password_field instanceof EE_Password_Field) {
6380
-            $field_names = $password_field->protectedFields();
6381
-            foreach ($field_names as $field_name) {
6382
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6383
-            }
6384
-        }
6385
-        return $fields;
6386
-    }
6387
-
6388
-
6389
-    /**
6390
-     * Checks if the current user can perform the requested action on this model
6391
-     * @since 4.9.74.p
6392
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6393
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6394
-     * @return bool
6395
-     * @throws EE_Error
6396
-     * @throws InvalidArgumentException
6397
-     * @throws InvalidDataTypeException
6398
-     * @throws InvalidInterfaceException
6399
-     * @throws ReflectionException
6400
-     * @throws UnexpectedEntityException
6401
-     */
6402
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6403
-    {
6404
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6405
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6406
-        }
6407
-        if (!is_array($model_obj_or_fields_n_values)) {
6408
-            throw new UnexpectedEntityException(
6409
-                $model_obj_or_fields_n_values,
6410
-                'EE_Base_Class',
6411
-                sprintf(
6412
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6413
-                    __FUNCTION__
6414
-                )
6415
-            );
6416
-        }
6417
-        return $this->exists(
6418
-            $this->alter_query_params_to_restrict_by_ID(
6419
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6420
-                array(
6421
-                    'default_where_conditions' => 'none',
6422
-                    'caps'                     => $cap_to_check,
6423
-                )
6424
-            )
6425
-        );
6426
-    }
6427
-
6428
-    /**
6429
-     * Returns the query param where conditions key to the password affecting this model.
6430
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6431
-     * @since 4.9.74.p
6432
-     * @return null|string
6433
-     * @throws EE_Error
6434
-     * @throws InvalidArgumentException
6435
-     * @throws InvalidDataTypeException
6436
-     * @throws InvalidInterfaceException
6437
-     * @throws ModelConfigurationException
6438
-     * @throws ReflectionException
6439
-     */
6440
-    public function modelChainAndPassword()
6441
-    {
6442
-        if ($this->model_chain_to_password === null) {
6443
-            throw new ModelConfigurationException(
6444
-                $this,
6445
-                esc_html_x(
6446
-                // @codingStandardsIgnoreStart
6447
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6448
-                    // @codingStandardsIgnoreEnd
6449
-                    '1: model name',
6450
-                    'event_espresso'
6451
-                )
6452
-            );
6453
-        }
6454
-        if ($this->model_chain_to_password === '') {
6455
-            $model_with_password = $this;
6456
-        } else {
6457
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6458
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6459
-            } else {
6460
-                $last_model_in_chain = $this->model_chain_to_password;
6461
-            }
6462
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6463
-        }
6464
-
6465
-        $password_field = $model_with_password->getPasswordField();
6466
-        if ($password_field instanceof EE_Password_Field) {
6467
-            $password_field_name = $password_field->get_name();
6468
-        } else {
6469
-            throw new ModelConfigurationException(
6470
-                $this,
6471
-                sprintf(
6472
-                    esc_html_x(
6473
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6474
-                        '1: model name, 2: special string',
6475
-                        'event_espresso'
6476
-                    ),
6477
-                    $model_with_password->get_this_model_name(),
6478
-                    $this->model_chain_to_password
6479
-                )
6480
-            );
6481
-        }
6482
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6483
-    }
6484
-
6485
-    /**
6486
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6487
-     * or if this model itself has a password affecting access to some of its other fields.
6488
-     * @since 4.9.74.p
6489
-     * @return boolean
6490
-     */
6491
-    public function restrictedByRelatedModelPassword()
6492
-    {
6493
-        return $this->model_chain_to_password !== null;
6494
-    }
3802
+		}
3803
+		return $null_friendly_where_conditions;
3804
+	}
3805
+
3806
+
3807
+
3808
+	/**
3809
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3810
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3811
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3812
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3813
+	 *
3814
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3815
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3816
+	 */
3817
+	private function _get_default_where_conditions($model_relation_path = null)
3818
+	{
3819
+		if ($this->_ignore_where_strategy) {
3820
+			return array();
3821
+		}
3822
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3823
+	}
3824
+
3825
+
3826
+
3827
+	/**
3828
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3829
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3830
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3831
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3832
+	 * Similar to _get_default_where_conditions
3833
+	 *
3834
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3835
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3836
+	 */
3837
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3838
+	{
3839
+		if ($this->_ignore_where_strategy) {
3840
+			return array();
3841
+		}
3842
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3843
+	}
3844
+
3845
+
3846
+
3847
+	/**
3848
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3849
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3850
+	 *
3851
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3852
+	 * @return string
3853
+	 * @throws EE_Error
3854
+	 */
3855
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3856
+	{
3857
+		$selects = $this->_get_columns_to_select_for_this_model();
3858
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3859
+			$name_of_other_model_included) {
3860
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3861
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3862
+			foreach ($other_model_selects as $key => $value) {
3863
+				$selects[] = $value;
3864
+			}
3865
+		}
3866
+		return implode(", ", $selects);
3867
+	}
3868
+
3869
+
3870
+
3871
+	/**
3872
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3873
+	 * So that's going to be the columns for all the fields on the model
3874
+	 *
3875
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3876
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3877
+	 */
3878
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3879
+	{
3880
+		$fields = $this->field_settings();
3881
+		$selects = array();
3882
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3883
+			$model_relation_chain,
3884
+			$this->get_this_model_name()
3885
+		);
3886
+		foreach ($fields as $field_obj) {
3887
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3888
+						 . $field_obj->get_table_alias()
3889
+						 . "."
3890
+						 . $field_obj->get_table_column()
3891
+						 . " AS '"
3892
+						 . $table_alias_with_model_relation_chain_prefix
3893
+						 . $field_obj->get_table_alias()
3894
+						 . "."
3895
+						 . $field_obj->get_table_column()
3896
+						 . "'";
3897
+		}
3898
+		// make sure we are also getting the PKs of each table
3899
+		$tables = $this->get_tables();
3900
+		if (count($tables) > 1) {
3901
+			foreach ($tables as $table_obj) {
3902
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3903
+									   . $table_obj->get_fully_qualified_pk_column();
3904
+				if (! in_array($qualified_pk_column, $selects)) {
3905
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3906
+				}
3907
+			}
3908
+		}
3909
+		return $selects;
3910
+	}
3911
+
3912
+
3913
+
3914
+	/**
3915
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3916
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3917
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3918
+	 * SQL for joining, and the data types
3919
+	 *
3920
+	 * @param null|string                 $original_query_param
3921
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3922
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3923
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3924
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3925
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3926
+	 *                                                          or 'Registration's
3927
+	 * @param string                      $original_query_param what it originally was (eg
3928
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3929
+	 *                                                          matches $query_param
3930
+	 * @throws EE_Error
3931
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3932
+	 */
3933
+	private function _extract_related_model_info_from_query_param(
3934
+		$query_param,
3935
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3936
+		$query_param_type,
3937
+		$original_query_param = null
3938
+	) {
3939
+		if ($original_query_param === null) {
3940
+			$original_query_param = $query_param;
3941
+		}
3942
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3943
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3944
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3945
+		$allow_fields = in_array(
3946
+			$query_param_type,
3947
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3948
+			true
3949
+		);
3950
+		// check to see if we have a field on this model
3951
+		$this_model_fields = $this->field_settings(true);
3952
+		if (array_key_exists($query_param, $this_model_fields)) {
3953
+			if ($allow_fields) {
3954
+				return;
3955
+			}
3956
+			throw new EE_Error(
3957
+				sprintf(
3958
+					__(
3959
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3960
+						"event_espresso"
3961
+					),
3962
+					$query_param,
3963
+					get_class($this),
3964
+					$query_param_type,
3965
+					$original_query_param
3966
+				)
3967
+			);
3968
+		}
3969
+		// check if this is a special logic query param
3970
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3971
+			if ($allow_logic_query_params) {
3972
+				return;
3973
+			}
3974
+			throw new EE_Error(
3975
+				sprintf(
3976
+					__(
3977
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3978
+						'event_espresso'
3979
+					),
3980
+					implode('", "', $this->_logic_query_param_keys),
3981
+					$query_param,
3982
+					get_class($this),
3983
+					'<br />',
3984
+					"\t"
3985
+					. ' $passed_in_query_info = <pre>'
3986
+					. print_r($passed_in_query_info, true)
3987
+					. '</pre>'
3988
+					. "\n\t"
3989
+					. ' $query_param_type = '
3990
+					. $query_param_type
3991
+					. "\n\t"
3992
+					. ' $original_query_param = '
3993
+					. $original_query_param
3994
+				)
3995
+			);
3996
+		}
3997
+		// check if it's a custom selection
3998
+		if ($this->_custom_selections instanceof CustomSelects
3999
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4000
+		) {
4001
+			return;
4002
+		}
4003
+		// check if has a model name at the beginning
4004
+		// and
4005
+		// check if it's a field on a related model
4006
+		if ($this->extractJoinModelFromQueryParams(
4007
+			$passed_in_query_info,
4008
+			$query_param,
4009
+			$original_query_param,
4010
+			$query_param_type
4011
+		)) {
4012
+			return;
4013
+		}
4014
+
4015
+		// ok so $query_param didn't start with a model name
4016
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4017
+		// it's wack, that's what it is
4018
+		throw new EE_Error(
4019
+			sprintf(
4020
+				esc_html__(
4021
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4022
+					"event_espresso"
4023
+				),
4024
+				$query_param,
4025
+				get_class($this),
4026
+				$query_param_type,
4027
+				$original_query_param
4028
+			)
4029
+		);
4030
+	}
4031
+
4032
+
4033
+	/**
4034
+	 * Extracts any possible join model information from the provided possible_join_string.
4035
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4036
+	 * parts that should be added to the query.
4037
+	 *
4038
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4039
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4040
+	 * @param null|string                 $original_query_param
4041
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4042
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4043
+	 * @return bool  returns true if a join was added and false if not.
4044
+	 * @throws EE_Error
4045
+	 */
4046
+	private function extractJoinModelFromQueryParams(
4047
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4048
+		$possible_join_string,
4049
+		$original_query_param,
4050
+		$query_parameter_type
4051
+	) {
4052
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4053
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4054
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4055
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4056
+				if ($possible_join_string === '') {
4057
+					// nothing left to $query_param
4058
+					// we should actually end in a field name, not a model like this!
4059
+					throw new EE_Error(
4060
+						sprintf(
4061
+							esc_html__(
4062
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4063
+								"event_espresso"
4064
+							),
4065
+							$possible_join_string,
4066
+							$query_parameter_type,
4067
+							get_class($this),
4068
+							$valid_related_model_name
4069
+						)
4070
+					);
4071
+				}
4072
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4073
+				$related_model_obj->_extract_related_model_info_from_query_param(
4074
+					$possible_join_string,
4075
+					$query_info_carrier,
4076
+					$query_parameter_type,
4077
+					$original_query_param
4078
+				);
4079
+				return true;
4080
+			}
4081
+			if ($possible_join_string === $valid_related_model_name) {
4082
+				$this->_add_join_to_model(
4083
+					$valid_related_model_name,
4084
+					$query_info_carrier,
4085
+					$original_query_param
4086
+				);
4087
+				return true;
4088
+			}
4089
+		}
4090
+		return false;
4091
+	}
4092
+
4093
+
4094
+	/**
4095
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4096
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4097
+	 * @throws EE_Error
4098
+	 */
4099
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4100
+	{
4101
+		if ($this->_custom_selections instanceof CustomSelects
4102
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4103
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4104
+			)
4105
+		) {
4106
+			$original_selects = $this->_custom_selections->originalSelects();
4107
+			foreach ($original_selects as $alias => $select_configuration) {
4108
+				$this->extractJoinModelFromQueryParams(
4109
+					$query_info_carrier,
4110
+					$select_configuration[0],
4111
+					$select_configuration[0],
4112
+					'custom_selects'
4113
+				);
4114
+			}
4115
+		}
4116
+	}
4117
+
4118
+
4119
+
4120
+	/**
4121
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4122
+	 * and store it on $passed_in_query_info
4123
+	 *
4124
+	 * @param string                      $model_name
4125
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4126
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4127
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4128
+	 *                                                          and are adding a join to 'Payment' with the original
4129
+	 *                                                          query param key
4130
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4131
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4132
+	 *                                                          Payment wants to add default query params so that it
4133
+	 *                                                          will know what models to prepend onto its default query
4134
+	 *                                                          params or in case it wants to rename tables (in case
4135
+	 *                                                          there are multiple joins to the same table)
4136
+	 * @return void
4137
+	 * @throws EE_Error
4138
+	 */
4139
+	private function _add_join_to_model(
4140
+		$model_name,
4141
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4142
+		$original_query_param
4143
+	) {
4144
+		$relation_obj = $this->related_settings_for($model_name);
4145
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4146
+		// check if the relation is HABTM, because then we're essentially doing two joins
4147
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4148
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4149
+			$join_model_obj = $relation_obj->get_join_model();
4150
+			// replace the model specified with the join model for this relation chain, whi
4151
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4152
+				$model_name,
4153
+				$join_model_obj->get_this_model_name(),
4154
+				$model_relation_chain
4155
+			);
4156
+			$passed_in_query_info->merge(
4157
+				new EE_Model_Query_Info_Carrier(
4158
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4159
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4160
+				)
4161
+			);
4162
+		}
4163
+		// now just join to the other table pointed to by the relation object, and add its data types
4164
+		$passed_in_query_info->merge(
4165
+			new EE_Model_Query_Info_Carrier(
4166
+				array($model_relation_chain => $model_name),
4167
+				$relation_obj->get_join_statement($model_relation_chain)
4168
+			)
4169
+		);
4170
+	}
4171
+
4172
+
4173
+
4174
+	/**
4175
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4176
+	 *
4177
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4178
+	 * @return string of SQL
4179
+	 * @throws EE_Error
4180
+	 */
4181
+	private function _construct_where_clause($where_params)
4182
+	{
4183
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4184
+		if ($SQL) {
4185
+			return " WHERE " . $SQL;
4186
+		}
4187
+		return '';
4188
+	}
4189
+
4190
+
4191
+
4192
+	/**
4193
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4194
+	 * and should be passed HAVING parameters, not WHERE parameters
4195
+	 *
4196
+	 * @param array $having_params
4197
+	 * @return string
4198
+	 * @throws EE_Error
4199
+	 */
4200
+	private function _construct_having_clause($having_params)
4201
+	{
4202
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4203
+		if ($SQL) {
4204
+			return " HAVING " . $SQL;
4205
+		}
4206
+		return '';
4207
+	}
4208
+
4209
+
4210
+	/**
4211
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4212
+	 * Event_Meta.meta_value = 'foo'))"
4213
+	 *
4214
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4215
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4216
+	 * @throws EE_Error
4217
+	 * @return string of SQL
4218
+	 */
4219
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4220
+	{
4221
+		$where_clauses = array();
4222
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4223
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4224
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4225
+				switch ($query_param) {
4226
+					case 'not':
4227
+					case 'NOT':
4228
+						$where_clauses[] = "! ("
4229
+										   . $this->_construct_condition_clause_recursive(
4230
+											   $op_and_value_or_sub_condition,
4231
+											   $glue
4232
+										   )
4233
+										   . ")";
4234
+						break;
4235
+					case 'and':
4236
+					case 'AND':
4237
+						$where_clauses[] = " ("
4238
+										   . $this->_construct_condition_clause_recursive(
4239
+											   $op_and_value_or_sub_condition,
4240
+											   ' AND '
4241
+										   )
4242
+										   . ")";
4243
+						break;
4244
+					case 'or':
4245
+					case 'OR':
4246
+						$where_clauses[] = " ("
4247
+										   . $this->_construct_condition_clause_recursive(
4248
+											   $op_and_value_or_sub_condition,
4249
+											   ' OR '
4250
+										   )
4251
+										   . ")";
4252
+						break;
4253
+				}
4254
+			} else {
4255
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4256
+				// if it's not a normal field, maybe it's a custom selection?
4257
+				if (! $field_obj) {
4258
+					if ($this->_custom_selections instanceof CustomSelects) {
4259
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4260
+					} else {
4261
+						throw new EE_Error(sprintf(__(
4262
+							"%s is neither a valid model field name, nor a custom selection",
4263
+							"event_espresso"
4264
+						), $query_param));
4265
+					}
4266
+				}
4267
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4268
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4269
+			}
4270
+		}
4271
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4272
+	}
4273
+
4274
+
4275
+
4276
+	/**
4277
+	 * Takes the input parameter and extract the table name (alias) and column name
4278
+	 *
4279
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4280
+	 * @throws EE_Error
4281
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4282
+	 */
4283
+	private function _deduce_column_name_from_query_param($query_param)
4284
+	{
4285
+		$field = $this->_deduce_field_from_query_param($query_param);
4286
+		if ($field) {
4287
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4288
+				$field->get_model_name(),
4289
+				$query_param
4290
+			);
4291
+			return $table_alias_prefix . $field->get_qualified_column();
4292
+		}
4293
+		if ($this->_custom_selections instanceof CustomSelects
4294
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4295
+		) {
4296
+			// maybe it's custom selection item?
4297
+			// if so, just use it as the "column name"
4298
+			return $query_param;
4299
+		}
4300
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4301
+			? implode(',', $this->_custom_selections->columnAliases())
4302
+			: '';
4303
+		throw new EE_Error(
4304
+			sprintf(
4305
+				__(
4306
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4307
+					"event_espresso"
4308
+				),
4309
+				$query_param,
4310
+				$custom_select_aliases
4311
+			)
4312
+		);
4313
+	}
4314
+
4315
+
4316
+
4317
+	/**
4318
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4319
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4320
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4321
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4322
+	 *
4323
+	 * @param string $condition_query_param_key
4324
+	 * @return string
4325
+	 */
4326
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4327
+	{
4328
+		$pos_of_star = strpos($condition_query_param_key, '*');
4329
+		if ($pos_of_star === false) {
4330
+			return $condition_query_param_key;
4331
+		}
4332
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4333
+		return $condition_query_param_sans_star;
4334
+	}
4335
+
4336
+
4337
+
4338
+	/**
4339
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4340
+	 *
4341
+	 * @param                            mixed      array | string    $op_and_value
4342
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4343
+	 * @throws EE_Error
4344
+	 * @return string
4345
+	 */
4346
+	private function _construct_op_and_value($op_and_value, $field_obj)
4347
+	{
4348
+		if (is_array($op_and_value)) {
4349
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4350
+			if (! $operator) {
4351
+				$php_array_like_string = array();
4352
+				foreach ($op_and_value as $key => $value) {
4353
+					$php_array_like_string[] = "$key=>$value";
4354
+				}
4355
+				throw new EE_Error(
4356
+					sprintf(
4357
+						__(
4358
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4359
+							"event_espresso"
4360
+						),
4361
+						implode(",", $php_array_like_string)
4362
+					)
4363
+				);
4364
+			}
4365
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4366
+		} else {
4367
+			$operator = '=';
4368
+			$value = $op_and_value;
4369
+		}
4370
+		// check to see if the value is actually another field
4371
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4372
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4373
+		}
4374
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4375
+			// in this case, the value should be an array, or at least a comma-separated list
4376
+			// it will need to handle a little differently
4377
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4378
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4379
+			return $operator . SP . $cleaned_value;
4380
+		}
4381
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4382
+			// the value should be an array with count of two.
4383
+			if (count($value) !== 2) {
4384
+				throw new EE_Error(
4385
+					sprintf(
4386
+						__(
4387
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4388
+							'event_espresso'
4389
+						),
4390
+						"BETWEEN"
4391
+					)
4392
+				);
4393
+			}
4394
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4395
+			return $operator . SP . $cleaned_value;
4396
+		}
4397
+		if (in_array($operator, $this->valid_null_style_operators())) {
4398
+			if ($value !== null) {
4399
+				throw new EE_Error(
4400
+					sprintf(
4401
+						__(
4402
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4403
+							"event_espresso"
4404
+						),
4405
+						$value,
4406
+						$operator
4407
+					)
4408
+				);
4409
+			}
4410
+			return $operator;
4411
+		}
4412
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4413
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4414
+			// remove other junk. So just treat it as a string.
4415
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4416
+		}
4417
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4418
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4419
+		}
4420
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4421
+			throw new EE_Error(
4422
+				sprintf(
4423
+					__(
4424
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4425
+						'event_espresso'
4426
+					),
4427
+					$operator,
4428
+					$operator
4429
+				)
4430
+			);
4431
+		}
4432
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4433
+			throw new EE_Error(
4434
+				sprintf(
4435
+					__(
4436
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4437
+						'event_espresso'
4438
+					),
4439
+					$operator,
4440
+					$operator
4441
+				)
4442
+			);
4443
+		}
4444
+		throw new EE_Error(
4445
+			sprintf(
4446
+				__(
4447
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4448
+					"event_espresso"
4449
+				),
4450
+				http_build_query($op_and_value)
4451
+			)
4452
+		);
4453
+	}
4454
+
4455
+
4456
+
4457
+	/**
4458
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4459
+	 *
4460
+	 * @param array                      $values
4461
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4462
+	 *                                              '%s'
4463
+	 * @return string
4464
+	 * @throws EE_Error
4465
+	 */
4466
+	public function _construct_between_value($values, $field_obj)
4467
+	{
4468
+		$cleaned_values = array();
4469
+		foreach ($values as $value) {
4470
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4471
+		}
4472
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4473
+	}
4474
+
4475
+
4476
+	/**
4477
+	 * Takes an array or a comma-separated list of $values and cleans them
4478
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4479
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4480
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4481
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4482
+	 *
4483
+	 * @param mixed                      $values    array or comma-separated string
4484
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4485
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4486
+	 * @throws EE_Error
4487
+	 */
4488
+	public function _construct_in_value($values, $field_obj)
4489
+	{
4490
+		$prepped = [];
4491
+		// check if the value is a CSV list
4492
+		if (is_string($values)) {
4493
+			// in which case, turn it into an array
4494
+			$values = explode(',', $values);
4495
+		}
4496
+		// make sure we only have one of each value in the list
4497
+		$values = array_unique($values);
4498
+		foreach ($values as $value) {
4499
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4500
+		}
4501
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4502
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4503
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4504
+		if (empty($prepped)) {
4505
+			$all_fields = $this->field_settings();
4506
+			$first_field    = reset($all_fields);
4507
+			$main_table = $this->_get_main_table();
4508
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4509
+		}
4510
+		return '(' . implode(',', $prepped) . ')';
4511
+	}
4512
+
4513
+
4514
+
4515
+	/**
4516
+	 * @param mixed                      $value
4517
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4518
+	 * @throws EE_Error
4519
+	 * @return false|null|string
4520
+	 */
4521
+	private function _wpdb_prepare_using_field($value, $field_obj)
4522
+	{
4523
+		/** @type WPDB $wpdb */
4524
+		global $wpdb;
4525
+		if ($field_obj instanceof EE_Model_Field_Base) {
4526
+			return $wpdb->prepare(
4527
+				$field_obj->get_wpdb_data_type(),
4528
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4529
+			);
4530
+		} //$field_obj should really just be a data type
4531
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4532
+			throw new EE_Error(
4533
+				sprintf(
4534
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4535
+					$field_obj,
4536
+					implode(",", $this->_valid_wpdb_data_types)
4537
+				)
4538
+			);
4539
+		}
4540
+		return $wpdb->prepare($field_obj, $value);
4541
+	}
4542
+
4543
+
4544
+
4545
+	/**
4546
+	 * Takes the input parameter and finds the model field that it indicates.
4547
+	 *
4548
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4549
+	 * @throws EE_Error
4550
+	 * @return EE_Model_Field_Base
4551
+	 */
4552
+	protected function _deduce_field_from_query_param($query_param_name)
4553
+	{
4554
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4555
+		// which will help us find the database table and column
4556
+		$query_param_parts = explode(".", $query_param_name);
4557
+		if (empty($query_param_parts)) {
4558
+			throw new EE_Error(sprintf(__(
4559
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4560
+				'event_espresso'
4561
+			), $query_param_name));
4562
+		}
4563
+		$number_of_parts = count($query_param_parts);
4564
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4565
+		if ($number_of_parts === 1) {
4566
+			$field_name = $last_query_param_part;
4567
+			$model_obj = $this;
4568
+		} else {// $number_of_parts >= 2
4569
+			// the last part is the column name, and there are only 2parts. therefore...
4570
+			$field_name = $last_query_param_part;
4571
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4572
+		}
4573
+		try {
4574
+			return $model_obj->field_settings_for($field_name);
4575
+		} catch (EE_Error $e) {
4576
+			return null;
4577
+		}
4578
+	}
4579
+
4580
+
4581
+
4582
+	/**
4583
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4584
+	 * alias and column which corresponds to it
4585
+	 *
4586
+	 * @param string $field_name
4587
+	 * @throws EE_Error
4588
+	 * @return string
4589
+	 */
4590
+	public function _get_qualified_column_for_field($field_name)
4591
+	{
4592
+		$all_fields = $this->field_settings();
4593
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4594
+		if ($field) {
4595
+			return $field->get_qualified_column();
4596
+		}
4597
+		throw new EE_Error(
4598
+			sprintf(
4599
+				__(
4600
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4601
+					'event_espresso'
4602
+				),
4603
+				$field_name,
4604
+				get_class($this)
4605
+			)
4606
+		);
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4613
+	 * Example usage:
4614
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4615
+	 *      array(),
4616
+	 *      ARRAY_A,
4617
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4618
+	 *  );
4619
+	 * is equivalent to
4620
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4621
+	 * and
4622
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4623
+	 *      array(
4624
+	 *          array(
4625
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4626
+	 *          ),
4627
+	 *          ARRAY_A,
4628
+	 *          implode(
4629
+	 *              ', ',
4630
+	 *              array_merge(
4631
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4632
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4633
+	 *              )
4634
+	 *          )
4635
+	 *      )
4636
+	 *  );
4637
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4638
+	 *
4639
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4640
+	 *                                            and the one whose fields you are selecting for example: when querying
4641
+	 *                                            tickets model and selecting fields from the tickets model you would
4642
+	 *                                            leave this parameter empty, because no models are needed to join
4643
+	 *                                            between the queried model and the selected one. Likewise when
4644
+	 *                                            querying the datetime model and selecting fields from the tickets
4645
+	 *                                            model, it would also be left empty, because there is a direct
4646
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4647
+	 *                                            them together. However, when querying from the event model and
4648
+	 *                                            selecting fields from the ticket model, you should provide the string
4649
+	 *                                            'Datetime', indicating that the event model must first join to the
4650
+	 *                                            datetime model in order to find its relation to ticket model.
4651
+	 *                                            Also, when querying from the venue model and selecting fields from
4652
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4653
+	 *                                            indicating you need to join the venue model to the event model,
4654
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4655
+	 *                                            This string is used to deduce the prefix that gets added onto the
4656
+	 *                                            models' tables qualified columns
4657
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4658
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4659
+	 *                                            qualified column names
4660
+	 * @return array|string
4661
+	 */
4662
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4663
+	{
4664
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4665
+		$qualified_columns = array();
4666
+		foreach ($this->field_settings() as $field_name => $field) {
4667
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4668
+		}
4669
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4670
+	}
4671
+
4672
+
4673
+
4674
+	/**
4675
+	 * constructs the select use on special limit joins
4676
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4677
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4678
+	 * (as that is typically where the limits would be set).
4679
+	 *
4680
+	 * @param  string       $table_alias The table the select is being built for
4681
+	 * @param  mixed|string $limit       The limit for this select
4682
+	 * @return string                The final select join element for the query.
4683
+	 */
4684
+	public function _construct_limit_join_select($table_alias, $limit)
4685
+	{
4686
+		$SQL = '';
4687
+		foreach ($this->_tables as $table_obj) {
4688
+			if ($table_obj instanceof EE_Primary_Table) {
4689
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4690
+					? $table_obj->get_select_join_limit($limit)
4691
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4692
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4693
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4694
+					? $table_obj->get_select_join_limit_join($limit)
4695
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4696
+			}
4697
+		}
4698
+		return $SQL;
4699
+	}
4700
+
4701
+
4702
+
4703
+	/**
4704
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4705
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4706
+	 *
4707
+	 * @return string SQL
4708
+	 * @throws EE_Error
4709
+	 */
4710
+	public function _construct_internal_join()
4711
+	{
4712
+		$SQL = $this->_get_main_table()->get_table_sql();
4713
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4714
+		return $SQL;
4715
+	}
4716
+
4717
+
4718
+
4719
+	/**
4720
+	 * Constructs the SQL for joining all the tables on this model.
4721
+	 * Normally $alias should be the primary table's alias, but in cases where
4722
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4723
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4724
+	 * alias, this will construct SQL like:
4725
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4726
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4727
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4728
+	 *
4729
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4730
+	 * @return string
4731
+	 */
4732
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4733
+	{
4734
+		$SQL = '';
4735
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4736
+		foreach ($this->_tables as $table_obj) {
4737
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4738
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4739
+					// so we're joining to this table, meaning the table is already in
4740
+					// the FROM statement, BUT the primary table isn't. So we want
4741
+					// to add the inverse join sql
4742
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4743
+				} else {
4744
+					// just add a regular JOIN to this table from the primary table
4745
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4746
+				}
4747
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4748
+		}
4749
+		return $SQL;
4750
+	}
4751
+
4752
+
4753
+
4754
+	/**
4755
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4756
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4757
+	 * their data type (eg, '%s', '%d', etc)
4758
+	 *
4759
+	 * @return array
4760
+	 */
4761
+	public function _get_data_types()
4762
+	{
4763
+		$data_types = array();
4764
+		foreach ($this->field_settings() as $field_obj) {
4765
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4766
+			/** @var $field_obj EE_Model_Field_Base */
4767
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4768
+		}
4769
+		return $data_types;
4770
+	}
4771
+
4772
+
4773
+
4774
+	/**
4775
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4776
+	 *
4777
+	 * @param string $model_name
4778
+	 * @throws EE_Error
4779
+	 * @return EEM_Base
4780
+	 */
4781
+	public function get_related_model_obj($model_name)
4782
+	{
4783
+		$model_classname = "EEM_" . $model_name;
4784
+		if (! class_exists($model_classname)) {
4785
+			throw new EE_Error(sprintf(__(
4786
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4787
+				'event_espresso'
4788
+			), $model_name, $model_classname));
4789
+		}
4790
+		return call_user_func($model_classname . "::instance");
4791
+	}
4792
+
4793
+
4794
+
4795
+	/**
4796
+	 * Returns the array of EE_ModelRelations for this model.
4797
+	 *
4798
+	 * @return EE_Model_Relation_Base[]
4799
+	 */
4800
+	public function relation_settings()
4801
+	{
4802
+		return $this->_model_relations;
4803
+	}
4804
+
4805
+
4806
+
4807
+	/**
4808
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4809
+	 * because without THOSE models, this model probably doesn't have much purpose.
4810
+	 * (Eg, without an event, datetimes have little purpose.)
4811
+	 *
4812
+	 * @return EE_Belongs_To_Relation[]
4813
+	 */
4814
+	public function belongs_to_relations()
4815
+	{
4816
+		$belongs_to_relations = array();
4817
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4818
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4819
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4820
+			}
4821
+		}
4822
+		return $belongs_to_relations;
4823
+	}
4824
+
4825
+
4826
+
4827
+	/**
4828
+	 * Returns the specified EE_Model_Relation, or throws an exception
4829
+	 *
4830
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4831
+	 * @throws EE_Error
4832
+	 * @return EE_Model_Relation_Base
4833
+	 */
4834
+	public function related_settings_for($relation_name)
4835
+	{
4836
+		$relatedModels = $this->relation_settings();
4837
+		if (! array_key_exists($relation_name, $relatedModels)) {
4838
+			throw new EE_Error(
4839
+				sprintf(
4840
+					__(
4841
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4842
+						'event_espresso'
4843
+					),
4844
+					$relation_name,
4845
+					$this->_get_class_name(),
4846
+					implode(', ', array_keys($relatedModels))
4847
+				)
4848
+			);
4849
+		}
4850
+		return $relatedModels[ $relation_name ];
4851
+	}
4852
+
4853
+
4854
+
4855
+	/**
4856
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4857
+	 * fields
4858
+	 *
4859
+	 * @param string $fieldName
4860
+	 * @param boolean $include_db_only_fields
4861
+	 * @throws EE_Error
4862
+	 * @return EE_Model_Field_Base
4863
+	 */
4864
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4865
+	{
4866
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4867
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4868
+			throw new EE_Error(sprintf(
4869
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4870
+				$fieldName,
4871
+				get_class($this)
4872
+			));
4873
+		}
4874
+		return $fieldSettings[ $fieldName ];
4875
+	}
4876
+
4877
+
4878
+
4879
+	/**
4880
+	 * Checks if this field exists on this model
4881
+	 *
4882
+	 * @param string $fieldName a key in the model's _field_settings array
4883
+	 * @return boolean
4884
+	 */
4885
+	public function has_field($fieldName)
4886
+	{
4887
+		$fieldSettings = $this->field_settings(true);
4888
+		if (isset($fieldSettings[ $fieldName ])) {
4889
+			return true;
4890
+		}
4891
+		return false;
4892
+	}
4893
+
4894
+
4895
+
4896
+	/**
4897
+	 * Returns whether or not this model has a relation to the specified model
4898
+	 *
4899
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4900
+	 * @return boolean
4901
+	 */
4902
+	public function has_relation($relation_name)
4903
+	{
4904
+		$relations = $this->relation_settings();
4905
+		if (isset($relations[ $relation_name ])) {
4906
+			return true;
4907
+		}
4908
+		return false;
4909
+	}
4910
+
4911
+
4912
+
4913
+	/**
4914
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4915
+	 * Eg, on EE_Answer that would be ANS_ID field object
4916
+	 *
4917
+	 * @param $field_obj
4918
+	 * @return boolean
4919
+	 */
4920
+	public function is_primary_key_field($field_obj)
4921
+	{
4922
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4923
+	}
4924
+
4925
+
4926
+
4927
+	/**
4928
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4929
+	 * Eg, on EE_Answer that would be ANS_ID field object
4930
+	 *
4931
+	 * @return EE_Model_Field_Base
4932
+	 * @throws EE_Error
4933
+	 */
4934
+	public function get_primary_key_field()
4935
+	{
4936
+		if ($this->_primary_key_field === null) {
4937
+			foreach ($this->field_settings(true) as $field_obj) {
4938
+				if ($this->is_primary_key_field($field_obj)) {
4939
+					$this->_primary_key_field = $field_obj;
4940
+					break;
4941
+				}
4942
+			}
4943
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4944
+				throw new EE_Error(sprintf(
4945
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4946
+					get_class($this)
4947
+				));
4948
+			}
4949
+		}
4950
+		return $this->_primary_key_field;
4951
+	}
4952
+
4953
+
4954
+
4955
+	/**
4956
+	 * Returns whether or not not there is a primary key on this model.
4957
+	 * Internally does some caching.
4958
+	 *
4959
+	 * @return boolean
4960
+	 */
4961
+	public function has_primary_key_field()
4962
+	{
4963
+		if ($this->_has_primary_key_field === null) {
4964
+			try {
4965
+				$this->get_primary_key_field();
4966
+				$this->_has_primary_key_field = true;
4967
+			} catch (EE_Error $e) {
4968
+				$this->_has_primary_key_field = false;
4969
+			}
4970
+		}
4971
+		return $this->_has_primary_key_field;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * Finds the first field of type $field_class_name.
4978
+	 *
4979
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4980
+	 *                                 EE_Foreign_Key_Field, etc
4981
+	 * @return EE_Model_Field_Base or null if none is found
4982
+	 */
4983
+	public function get_a_field_of_type($field_class_name)
4984
+	{
4985
+		foreach ($this->field_settings() as $field) {
4986
+			if ($field instanceof $field_class_name) {
4987
+				return $field;
4988
+			}
4989
+		}
4990
+		return null;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * Gets a foreign key field pointing to model.
4997
+	 *
4998
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4999
+	 * @return EE_Foreign_Key_Field_Base
5000
+	 * @throws EE_Error
5001
+	 */
5002
+	public function get_foreign_key_to($model_name)
5003
+	{
5004
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5005
+			foreach ($this->field_settings() as $field) {
5006
+				if ($field instanceof EE_Foreign_Key_Field_Base
5007
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5008
+				) {
5009
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5010
+					break;
5011
+				}
5012
+			}
5013
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5014
+				throw new EE_Error(sprintf(__(
5015
+					"There is no foreign key field pointing to model %s on model %s",
5016
+					'event_espresso'
5017
+				), $model_name, get_class($this)));
5018
+			}
5019
+		}
5020
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5021
+	}
5022
+
5023
+
5024
+
5025
+	/**
5026
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5027
+	 *
5028
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5029
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5030
+	 *                            Either one works
5031
+	 * @return string
5032
+	 */
5033
+	public function get_table_for_alias($table_alias)
5034
+	{
5035
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5036
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5037
+	}
5038
+
5039
+
5040
+
5041
+	/**
5042
+	 * Returns a flat array of all field son this model, instead of organizing them
5043
+	 * by table_alias as they are in the constructor.
5044
+	 *
5045
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5046
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5047
+	 */
5048
+	public function field_settings($include_db_only_fields = false)
5049
+	{
5050
+		if ($include_db_only_fields) {
5051
+			if ($this->_cached_fields === null) {
5052
+				$this->_cached_fields = array();
5053
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5054
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5055
+						$this->_cached_fields[ $field_name ] = $field_obj;
5056
+					}
5057
+				}
5058
+			}
5059
+			return $this->_cached_fields;
5060
+		}
5061
+		if ($this->_cached_fields_non_db_only === null) {
5062
+			$this->_cached_fields_non_db_only = array();
5063
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5064
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5065
+					/** @var $field_obj EE_Model_Field_Base */
5066
+					if (! $field_obj->is_db_only_field()) {
5067
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5068
+					}
5069
+				}
5070
+			}
5071
+		}
5072
+		return $this->_cached_fields_non_db_only;
5073
+	}
5074
+
5075
+
5076
+
5077
+	/**
5078
+	 *        cycle though array of attendees and create objects out of each item
5079
+	 *
5080
+	 * @access        private
5081
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5082
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5083
+	 *                           numerically indexed)
5084
+	 * @throws EE_Error
5085
+	 */
5086
+	protected function _create_objects($rows = array())
5087
+	{
5088
+		$array_of_objects = array();
5089
+		if (empty($rows)) {
5090
+			return array();
5091
+		}
5092
+		$count_if_model_has_no_primary_key = 0;
5093
+		$has_primary_key = $this->has_primary_key_field();
5094
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5095
+		foreach ((array) $rows as $row) {
5096
+			if (empty($row)) {
5097
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5098
+				return array();
5099
+			}
5100
+			// check if we've already set this object in the results array,
5101
+			// in which case there's no need to process it further (again)
5102
+			if ($has_primary_key) {
5103
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5104
+					$row,
5105
+					$primary_key_field->get_qualified_column(),
5106
+					$primary_key_field->get_table_column()
5107
+				);
5108
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5109
+					continue;
5110
+				}
5111
+			}
5112
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5113
+			if (! $classInstance) {
5114
+				throw new EE_Error(
5115
+					sprintf(
5116
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5117
+						$this->get_this_model_name(),
5118
+						http_build_query($row)
5119
+					)
5120
+				);
5121
+			}
5122
+			// set the timezone on the instantiated objects
5123
+			$classInstance->set_timezone($this->_timezone);
5124
+			// make sure if there is any timezone setting present that we set the timezone for the object
5125
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5126
+			$array_of_objects[ $key ] = $classInstance;
5127
+			// also, for all the relations of type BelongsTo, see if we can cache
5128
+			// those related models
5129
+			// (we could do this for other relations too, but if there are conditions
5130
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5131
+			// so it requires a little more thought than just caching them immediately...)
5132
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5133
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5134
+					// check if this model's INFO is present. If so, cache it on the model
5135
+					$other_model = $relation_obj->get_other_model();
5136
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5137
+					// if we managed to make a model object from the results, cache it on the main model object
5138
+					if ($other_model_obj_maybe) {
5139
+						// set timezone on these other model objects if they are present
5140
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5141
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5142
+					}
5143
+				}
5144
+			}
5145
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5146
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5147
+			// the field in the CustomSelects object
5148
+			if ($this->_custom_selections instanceof CustomSelects) {
5149
+				$classInstance->setCustomSelectsValues(
5150
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5151
+				);
5152
+			}
5153
+		}
5154
+		return $array_of_objects;
5155
+	}
5156
+
5157
+
5158
+	/**
5159
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5160
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5161
+	 *
5162
+	 * @param array $db_results_row
5163
+	 * @return array
5164
+	 */
5165
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5166
+	{
5167
+		$results = array();
5168
+		if ($this->_custom_selections instanceof CustomSelects) {
5169
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5170
+				if (isset($db_results_row[ $alias ])) {
5171
+					$results[ $alias ] = $this->convertValueToDataType(
5172
+						$db_results_row[ $alias ],
5173
+						$this->_custom_selections->getDataTypeForAlias($alias)
5174
+					);
5175
+				}
5176
+			}
5177
+		}
5178
+		return $results;
5179
+	}
5180
+
5181
+
5182
+	/**
5183
+	 * This will set the value for the given alias
5184
+	 * @param string $value
5185
+	 * @param string $datatype (one of %d, %s, %f)
5186
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5187
+	 */
5188
+	protected function convertValueToDataType($value, $datatype)
5189
+	{
5190
+		switch ($datatype) {
5191
+			case '%f':
5192
+				return (float) $value;
5193
+			case '%d':
5194
+				return (int) $value;
5195
+			default:
5196
+				return (string) $value;
5197
+		}
5198
+	}
5199
+
5200
+
5201
+	/**
5202
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5203
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5204
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5205
+	 * object (as set in the model_field!).
5206
+	 *
5207
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5208
+	 */
5209
+	public function create_default_object()
5210
+	{
5211
+		$this_model_fields_and_values = array();
5212
+		// setup the row using default values;
5213
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5214
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5215
+		}
5216
+		$className = $this->_get_class_name();
5217
+		$classInstance = EE_Registry::instance()
5218
+									->load_class($className, array($this_model_fields_and_values), false, false);
5219
+		return $classInstance;
5220
+	}
5221
+
5222
+
5223
+
5224
+	/**
5225
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5226
+	 *                             or an stdClass where each property is the name of a column,
5227
+	 * @return EE_Base_Class
5228
+	 * @throws EE_Error
5229
+	 */
5230
+	public function instantiate_class_from_array_or_object($cols_n_values)
5231
+	{
5232
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5233
+			$cols_n_values = get_object_vars($cols_n_values);
5234
+		}
5235
+		$primary_key = null;
5236
+		// make sure the array only has keys that are fields/columns on this model
5237
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5238
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5239
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5240
+		}
5241
+		$className = $this->_get_class_name();
5242
+		// check we actually found results that we can use to build our model object
5243
+		// if not, return null
5244
+		if ($this->has_primary_key_field()) {
5245
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5246
+				return null;
5247
+			}
5248
+		} elseif ($this->unique_indexes()) {
5249
+			$first_column = reset($this_model_fields_n_values);
5250
+			if (empty($first_column)) {
5251
+				return null;
5252
+			}
5253
+		}
5254
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5255
+		if ($primary_key) {
5256
+			$classInstance = $this->get_from_entity_map($primary_key);
5257
+			if (! $classInstance) {
5258
+				$classInstance = EE_Registry::instance()
5259
+											->load_class(
5260
+												$className,
5261
+												array($this_model_fields_n_values, $this->_timezone),
5262
+												true,
5263
+												false
5264
+											);
5265
+				// add this new object to the entity map
5266
+				$classInstance = $this->add_to_entity_map($classInstance);
5267
+			}
5268
+		} else {
5269
+			$classInstance = EE_Registry::instance()
5270
+										->load_class(
5271
+											$className,
5272
+											array($this_model_fields_n_values, $this->_timezone),
5273
+											true,
5274
+											false
5275
+										);
5276
+		}
5277
+		return $classInstance;
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Gets the model object from the  entity map if it exists
5284
+	 *
5285
+	 * @param int|string $id the ID of the model object
5286
+	 * @return EE_Base_Class
5287
+	 */
5288
+	public function get_from_entity_map($id)
5289
+	{
5290
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5291
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5292
+	}
5293
+
5294
+
5295
+
5296
+	/**
5297
+	 * add_to_entity_map
5298
+	 * Adds the object to the model's entity mappings
5299
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5300
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5301
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5302
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5303
+	 *        then this method should be called immediately after the update query
5304
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5305
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5306
+	 *
5307
+	 * @param    EE_Base_Class $object
5308
+	 * @throws EE_Error
5309
+	 * @return \EE_Base_Class
5310
+	 */
5311
+	public function add_to_entity_map(EE_Base_Class $object)
5312
+	{
5313
+		$className = $this->_get_class_name();
5314
+		if (! $object instanceof $className) {
5315
+			throw new EE_Error(sprintf(
5316
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5317
+				is_object($object) ? get_class($object) : $object,
5318
+				$className
5319
+			));
5320
+		}
5321
+		/** @var $object EE_Base_Class */
5322
+		if (! $object->ID()) {
5323
+			throw new EE_Error(sprintf(__(
5324
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5325
+				"event_espresso"
5326
+			), get_class($this)));
5327
+		}
5328
+		// double check it's not already there
5329
+		$classInstance = $this->get_from_entity_map($object->ID());
5330
+		if ($classInstance) {
5331
+			return $classInstance;
5332
+		}
5333
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5334
+		return $object;
5335
+	}
5336
+
5337
+
5338
+
5339
+	/**
5340
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5341
+	 * if no identifier is provided, then the entire entity map is emptied
5342
+	 *
5343
+	 * @param int|string $id the ID of the model object
5344
+	 * @return boolean
5345
+	 */
5346
+	public function clear_entity_map($id = null)
5347
+	{
5348
+		if (empty($id)) {
5349
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5350
+			return true;
5351
+		}
5352
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5353
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5354
+			return true;
5355
+		}
5356
+		return false;
5357
+	}
5358
+
5359
+
5360
+
5361
+	/**
5362
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5363
+	 * Given an array where keys are column (or column alias) names and values,
5364
+	 * returns an array of their corresponding field names and database values
5365
+	 *
5366
+	 * @param array $cols_n_values
5367
+	 * @return array
5368
+	 */
5369
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5370
+	{
5371
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5372
+	}
5373
+
5374
+
5375
+
5376
+	/**
5377
+	 * _deduce_fields_n_values_from_cols_n_values
5378
+	 * Given an array where keys are column (or column alias) names and values,
5379
+	 * returns an array of their corresponding field names and database values
5380
+	 *
5381
+	 * @param string $cols_n_values
5382
+	 * @return array
5383
+	 */
5384
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5385
+	{
5386
+		$this_model_fields_n_values = array();
5387
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5388
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5389
+				$cols_n_values,
5390
+				$table_obj->get_fully_qualified_pk_column(),
5391
+				$table_obj->get_pk_column()
5392
+			);
5393
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5394
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5395
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5396
+					if (! $field_obj->is_db_only_field()) {
5397
+						// prepare field as if its coming from db
5398
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5399
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5400
+					}
5401
+				}
5402
+			} else {
5403
+				// the table's rows existed. Use their values
5404
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5405
+					if (! $field_obj->is_db_only_field()) {
5406
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5407
+							$cols_n_values,
5408
+							$field_obj->get_qualified_column(),
5409
+							$field_obj->get_table_column()
5410
+						);
5411
+					}
5412
+				}
5413
+			}
5414
+		}
5415
+		return $this_model_fields_n_values;
5416
+	}
5417
+
5418
+
5419
+	/**
5420
+	 * @param $cols_n_values
5421
+	 * @param $qualified_column
5422
+	 * @param $regular_column
5423
+	 * @return null
5424
+	 * @throws EE_Error
5425
+	 * @throws ReflectionException
5426
+	 */
5427
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5428
+	{
5429
+		$value = null;
5430
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5431
+		// does the field on the model relate to this column retrieved from the db?
5432
+		// or is it a db-only field? (not relating to the model)
5433
+		if (isset($cols_n_values[ $qualified_column ])) {
5434
+			$value = $cols_n_values[ $qualified_column ];
5435
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5436
+			$value = $cols_n_values[ $regular_column ];
5437
+		} elseif (! empty($this->foreign_key_aliases)) {
5438
+			// no PK?  ok check if there is a foreign key alias set for this table
5439
+			// then check if that alias exists in the incoming data
5440
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5441
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5442
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5443
+					$value = $cols_n_values[ $FK_alias ];
5444
+					list($pk_class) = explode('.', $PK_column);
5445
+					$pk_model_name = "EEM_{$pk_class}";
5446
+					/** @var EEM_Base $pk_model */
5447
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5448
+					if ($pk_model instanceof EEM_Base) {
5449
+						// make sure object is pulled from db and added to entity map
5450
+						$pk_model->get_one_by_ID($value);
5451
+					}
5452
+					break;
5453
+				}
5454
+			}
5455
+		}
5456
+		return $value;
5457
+	}
5458
+
5459
+
5460
+
5461
+	/**
5462
+	 * refresh_entity_map_from_db
5463
+	 * Makes sure the model object in the entity map at $id assumes the values
5464
+	 * of the database (opposite of EE_base_Class::save())
5465
+	 *
5466
+	 * @param int|string $id
5467
+	 * @return EE_Base_Class
5468
+	 * @throws EE_Error
5469
+	 */
5470
+	public function refresh_entity_map_from_db($id)
5471
+	{
5472
+		$obj_in_map = $this->get_from_entity_map($id);
5473
+		if ($obj_in_map) {
5474
+			$wpdb_results = $this->_get_all_wpdb_results(
5475
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5476
+			);
5477
+			if ($wpdb_results && is_array($wpdb_results)) {
5478
+				$one_row = reset($wpdb_results);
5479
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5480
+					$obj_in_map->set_from_db($field_name, $db_value);
5481
+				}
5482
+				// clear the cache of related model objects
5483
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5484
+					$obj_in_map->clear_cache($relation_name, null, true);
5485
+				}
5486
+			}
5487
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5488
+			return $obj_in_map;
5489
+		}
5490
+		return $this->get_one_by_ID($id);
5491
+	}
5492
+
5493
+
5494
+
5495
+	/**
5496
+	 * refresh_entity_map_with
5497
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5498
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5499
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5500
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5501
+	 *
5502
+	 * @param int|string    $id
5503
+	 * @param EE_Base_Class $replacing_model_obj
5504
+	 * @return \EE_Base_Class
5505
+	 * @throws EE_Error
5506
+	 */
5507
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5508
+	{
5509
+		$obj_in_map = $this->get_from_entity_map($id);
5510
+		if ($obj_in_map) {
5511
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5512
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5513
+					$obj_in_map->set($field_name, $value);
5514
+				}
5515
+				// make the model object in the entity map's cache match the $replacing_model_obj
5516
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5517
+					$obj_in_map->clear_cache($relation_name, null, true);
5518
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5519
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5520
+					}
5521
+				}
5522
+			}
5523
+			return $obj_in_map;
5524
+		}
5525
+		$this->add_to_entity_map($replacing_model_obj);
5526
+		return $replacing_model_obj;
5527
+	}
5528
+
5529
+
5530
+
5531
+	/**
5532
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5533
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5534
+	 * require_once($this->_getClassName().".class.php");
5535
+	 *
5536
+	 * @return string
5537
+	 */
5538
+	private function _get_class_name()
5539
+	{
5540
+		return "EE_" . $this->get_this_model_name();
5541
+	}
5542
+
5543
+
5544
+
5545
+	/**
5546
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5547
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5548
+	 * it would be 'Events'.
5549
+	 *
5550
+	 * @param int $quantity
5551
+	 * @return string
5552
+	 */
5553
+	public function item_name($quantity = 1)
5554
+	{
5555
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5556
+	}
5557
+
5558
+
5559
+
5560
+	/**
5561
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5562
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5563
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5564
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5565
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5566
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5567
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5568
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5569
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5570
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5571
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5572
+	 *        return $previousReturnValue.$returnString;
5573
+	 * }
5574
+	 * require('EEM_Answer.model.php');
5575
+	 * $answer=EEM_Answer::instance();
5576
+	 * echo $answer->my_callback('monkeys',100);
5577
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5578
+	 *
5579
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5580
+	 * @param array  $args       array of original arguments passed to the function
5581
+	 * @throws EE_Error
5582
+	 * @return mixed whatever the plugin which calls add_filter decides
5583
+	 */
5584
+	public function __call($methodName, $args)
5585
+	{
5586
+		$className = get_class($this);
5587
+		$tagName = "FHEE__{$className}__{$methodName}";
5588
+		if (! has_filter($tagName)) {
5589
+			throw new EE_Error(
5590
+				sprintf(
5591
+					__(
5592
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5593
+						'event_espresso'
5594
+					),
5595
+					$methodName,
5596
+					$className,
5597
+					$tagName,
5598
+					'<br />'
5599
+				)
5600
+			);
5601
+		}
5602
+		return apply_filters($tagName, null, $this, $args);
5603
+	}
5604
+
5605
+
5606
+
5607
+	/**
5608
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5609
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5610
+	 *
5611
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5612
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5613
+	 *                                                       the object's class name
5614
+	 *                                                       or object's ID
5615
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5616
+	 *                                                       exists in the database. If it does not, we add it
5617
+	 * @throws EE_Error
5618
+	 * @return EE_Base_Class
5619
+	 */
5620
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5621
+	{
5622
+		$className = $this->_get_class_name();
5623
+		if ($base_class_obj_or_id instanceof $className) {
5624
+			$model_object = $base_class_obj_or_id;
5625
+		} else {
5626
+			$primary_key_field = $this->get_primary_key_field();
5627
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5628
+				&& (
5629
+					is_int($base_class_obj_or_id)
5630
+					|| is_string($base_class_obj_or_id)
5631
+				)
5632
+			) {
5633
+				// assume it's an ID.
5634
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5635
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5636
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5637
+				&& is_string($base_class_obj_or_id)
5638
+			) {
5639
+				// assume its a string representation of the object
5640
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
+			} else {
5642
+				throw new EE_Error(
5643
+					sprintf(
5644
+						__(
5645
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5646
+							'event_espresso'
5647
+						),
5648
+						$base_class_obj_or_id,
5649
+						$this->_get_class_name(),
5650
+						print_r($base_class_obj_or_id, true)
5651
+					)
5652
+				);
5653
+			}
5654
+		}
5655
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5656
+			$model_object->save();
5657
+		}
5658
+		return $model_object;
5659
+	}
5660
+
5661
+
5662
+
5663
+	/**
5664
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5665
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5666
+	 * returns it ID.
5667
+	 *
5668
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5669
+	 * @return int|string depending on the type of this model object's ID
5670
+	 * @throws EE_Error
5671
+	 */
5672
+	public function ensure_is_ID($base_class_obj_or_id)
5673
+	{
5674
+		$className = $this->_get_class_name();
5675
+		if ($base_class_obj_or_id instanceof $className) {
5676
+			/** @var $base_class_obj_or_id EE_Base_Class */
5677
+			$id = $base_class_obj_or_id->ID();
5678
+		} elseif (is_int($base_class_obj_or_id)) {
5679
+			// assume it's an ID
5680
+			$id = $base_class_obj_or_id;
5681
+		} elseif (is_string($base_class_obj_or_id)) {
5682
+			// assume its a string representation of the object
5683
+			$id = $base_class_obj_or_id;
5684
+		} else {
5685
+			throw new EE_Error(sprintf(
5686
+				__(
5687
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5688
+					'event_espresso'
5689
+				),
5690
+				$base_class_obj_or_id,
5691
+				$this->_get_class_name(),
5692
+				print_r($base_class_obj_or_id, true)
5693
+			));
5694
+		}
5695
+		return $id;
5696
+	}
5697
+
5698
+
5699
+
5700
+	/**
5701
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5702
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5703
+	 * been sanitized and converted into the appropriate domain.
5704
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5705
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5706
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5707
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5708
+	 * $EVT = EEM_Event::instance(); $old_setting =
5709
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5710
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5711
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5712
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5713
+	 *
5714
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5715
+	 * @return void
5716
+	 */
5717
+	public function assume_values_already_prepared_by_model_object(
5718
+		$values_already_prepared = self::not_prepared_by_model_object
5719
+	) {
5720
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5721
+	}
5722
+
5723
+
5724
+
5725
+	/**
5726
+	 * Read comments for assume_values_already_prepared_by_model_object()
5727
+	 *
5728
+	 * @return int
5729
+	 */
5730
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5731
+	{
5732
+		return $this->_values_already_prepared_by_model_object;
5733
+	}
5734
+
5735
+
5736
+
5737
+	/**
5738
+	 * Gets all the indexes on this model
5739
+	 *
5740
+	 * @return EE_Index[]
5741
+	 */
5742
+	public function indexes()
5743
+	{
5744
+		return $this->_indexes;
5745
+	}
5746
+
5747
+
5748
+
5749
+	/**
5750
+	 * Gets all the Unique Indexes on this model
5751
+	 *
5752
+	 * @return EE_Unique_Index[]
5753
+	 */
5754
+	public function unique_indexes()
5755
+	{
5756
+		$unique_indexes = array();
5757
+		foreach ($this->_indexes as $name => $index) {
5758
+			if ($index instanceof EE_Unique_Index) {
5759
+				$unique_indexes [ $name ] = $index;
5760
+			}
5761
+		}
5762
+		return $unique_indexes;
5763
+	}
5764
+
5765
+
5766
+
5767
+	/**
5768
+	 * Gets all the fields which, when combined, make the primary key.
5769
+	 * This is usually just an array with 1 element (the primary key), but in cases
5770
+	 * where there is no primary key, it's a combination of fields as defined
5771
+	 * on a primary index
5772
+	 *
5773
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5774
+	 * @throws EE_Error
5775
+	 */
5776
+	public function get_combined_primary_key_fields()
5777
+	{
5778
+		foreach ($this->indexes() as $index) {
5779
+			if ($index instanceof EE_Primary_Key_Index) {
5780
+				return $index->fields();
5781
+			}
5782
+		}
5783
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5784
+	}
5785
+
5786
+
5787
+
5788
+	/**
5789
+	 * Used to build a primary key string (when the model has no primary key),
5790
+	 * which can be used a unique string to identify this model object.
5791
+	 *
5792
+	 * @param array $fields_n_values keys are field names, values are their values.
5793
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5794
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5795
+	 *                               before passing it to this function (that will convert it from columns-n-values
5796
+	 *                               to field-names-n-values).
5797
+	 * @return string
5798
+	 * @throws EE_Error
5799
+	 */
5800
+	public function get_index_primary_key_string($fields_n_values)
5801
+	{
5802
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5803
+			$fields_n_values,
5804
+			$this->get_combined_primary_key_fields()
5805
+		);
5806
+		return http_build_query($cols_n_values_for_primary_key_index);
5807
+	}
5808
+
5809
+
5810
+
5811
+	/**
5812
+	 * Gets the field values from the primary key string
5813
+	 *
5814
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5815
+	 * @param string $index_primary_key_string
5816
+	 * @return null|array
5817
+	 * @throws EE_Error
5818
+	 */
5819
+	public function parse_index_primary_key_string($index_primary_key_string)
5820
+	{
5821
+		$key_fields = $this->get_combined_primary_key_fields();
5822
+		// check all of them are in the $id
5823
+		$key_vals_in_combined_pk = array();
5824
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5825
+		foreach ($key_fields as $key_field_name => $field_obj) {
5826
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5827
+				return null;
5828
+			}
5829
+		}
5830
+		return $key_vals_in_combined_pk;
5831
+	}
5832
+
5833
+
5834
+
5835
+	/**
5836
+	 * verifies that an array of key-value pairs for model fields has a key
5837
+	 * for each field comprising the primary key index
5838
+	 *
5839
+	 * @param array $key_vals
5840
+	 * @return boolean
5841
+	 * @throws EE_Error
5842
+	 */
5843
+	public function has_all_combined_primary_key_fields($key_vals)
5844
+	{
5845
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5846
+		foreach ($keys_it_should_have as $key) {
5847
+			if (! isset($key_vals[ $key ])) {
5848
+				return false;
5849
+			}
5850
+		}
5851
+		return true;
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5858
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5859
+	 *
5860
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5861
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5862
+	 * @throws EE_Error
5863
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5864
+	 *                                                              indexed)
5865
+	 */
5866
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5867
+	{
5868
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5869
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5870
+		} elseif (is_array($model_object_or_attributes_array)) {
5871
+			$attributes_array = $model_object_or_attributes_array;
5872
+		} else {
5873
+			throw new EE_Error(sprintf(__(
5874
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5875
+				"event_espresso"
5876
+			), $model_object_or_attributes_array));
5877
+		}
5878
+		// even copies obviously won't have the same ID, so remove the primary key
5879
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5880
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5881
+			unset($attributes_array[ $this->primary_key_name() ]);
5882
+		}
5883
+		if (isset($query_params[0])) {
5884
+			$query_params[0] = array_merge($attributes_array, $query_params);
5885
+		} else {
5886
+			$query_params[0] = $attributes_array;
5887
+		}
5888
+		return $this->get_all($query_params);
5889
+	}
5890
+
5891
+
5892
+
5893
+	/**
5894
+	 * Gets the first copy we find. See get_all_copies for more details
5895
+	 *
5896
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5897
+	 * @param array $query_params
5898
+	 * @return EE_Base_Class
5899
+	 * @throws EE_Error
5900
+	 */
5901
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5902
+	{
5903
+		if (! is_array($query_params)) {
5904
+			EE_Error::doing_it_wrong(
5905
+				'EEM_Base::get_one_copy',
5906
+				sprintf(
5907
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5908
+					gettype($query_params)
5909
+				),
5910
+				'4.6.0'
5911
+			);
5912
+			$query_params = array();
5913
+		}
5914
+		$query_params['limit'] = 1;
5915
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5916
+		if (is_array($copies)) {
5917
+			return array_shift($copies);
5918
+		}
5919
+		return null;
5920
+	}
5921
+
5922
+
5923
+
5924
+	/**
5925
+	 * Updates the item with the specified id. Ignores default query parameters because
5926
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5927
+	 *
5928
+	 * @param array      $fields_n_values keys are field names, values are their new values
5929
+	 * @param int|string $id              the value of the primary key to update
5930
+	 * @return int number of rows updated
5931
+	 * @throws EE_Error
5932
+	 */
5933
+	public function update_by_ID($fields_n_values, $id)
5934
+	{
5935
+		$query_params = array(
5936
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5937
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5938
+		);
5939
+		return $this->update($fields_n_values, $query_params);
5940
+	}
5941
+
5942
+
5943
+
5944
+	/**
5945
+	 * Changes an operator which was supplied to the models into one usable in SQL
5946
+	 *
5947
+	 * @param string $operator_supplied
5948
+	 * @return string an operator which can be used in SQL
5949
+	 * @throws EE_Error
5950
+	 */
5951
+	private function _prepare_operator_for_sql($operator_supplied)
5952
+	{
5953
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5954
+			: null;
5955
+		if ($sql_operator) {
5956
+			return $sql_operator;
5957
+		}
5958
+		throw new EE_Error(
5959
+			sprintf(
5960
+				__(
5961
+					"The operator '%s' is not in the list of valid operators: %s",
5962
+					"event_espresso"
5963
+				),
5964
+				$operator_supplied,
5965
+				implode(",", array_keys($this->_valid_operators))
5966
+			)
5967
+		);
5968
+	}
5969
+
5970
+
5971
+
5972
+	/**
5973
+	 * Gets the valid operators
5974
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5975
+	 */
5976
+	public function valid_operators()
5977
+	{
5978
+		return $this->_valid_operators;
5979
+	}
5980
+
5981
+
5982
+
5983
+	/**
5984
+	 * Gets the between-style operators (take 2 arguments).
5985
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5986
+	 */
5987
+	public function valid_between_style_operators()
5988
+	{
5989
+		return array_intersect(
5990
+			$this->valid_operators(),
5991
+			$this->_between_style_operators
5992
+		);
5993
+	}
5994
+
5995
+	/**
5996
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5997
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5998
+	 */
5999
+	public function valid_like_style_operators()
6000
+	{
6001
+		return array_intersect(
6002
+			$this->valid_operators(),
6003
+			$this->_like_style_operators
6004
+		);
6005
+	}
6006
+
6007
+	/**
6008
+	 * Gets the "in"-style operators
6009
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6010
+	 */
6011
+	public function valid_in_style_operators()
6012
+	{
6013
+		return array_intersect(
6014
+			$this->valid_operators(),
6015
+			$this->_in_style_operators
6016
+		);
6017
+	}
6018
+
6019
+	/**
6020
+	 * Gets the "null"-style operators (accept no arguments)
6021
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6022
+	 */
6023
+	public function valid_null_style_operators()
6024
+	{
6025
+		return array_intersect(
6026
+			$this->valid_operators(),
6027
+			$this->_null_style_operators
6028
+		);
6029
+	}
6030
+
6031
+	/**
6032
+	 * Gets an array where keys are the primary keys and values are their 'names'
6033
+	 * (as determined by the model object's name() function, which is often overridden)
6034
+	 *
6035
+	 * @param array $query_params like get_all's
6036
+	 * @return string[]
6037
+	 * @throws EE_Error
6038
+	 */
6039
+	public function get_all_names($query_params = array())
6040
+	{
6041
+		$objs = $this->get_all($query_params);
6042
+		$names = array();
6043
+		foreach ($objs as $obj) {
6044
+			$names[ $obj->ID() ] = $obj->name();
6045
+		}
6046
+		return $names;
6047
+	}
6048
+
6049
+
6050
+
6051
+	/**
6052
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6053
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6054
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6055
+	 * array_keys() on $model_objects.
6056
+	 *
6057
+	 * @param \EE_Base_Class[] $model_objects
6058
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6059
+	 *                                               in the returned array
6060
+	 * @return array
6061
+	 * @throws EE_Error
6062
+	 */
6063
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6064
+	{
6065
+		if (! $this->has_primary_key_field()) {
6066
+			if (WP_DEBUG) {
6067
+				EE_Error::add_error(
6068
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6069
+					__FILE__,
6070
+					__FUNCTION__,
6071
+					__LINE__
6072
+				);
6073
+			}
6074
+		}
6075
+		$IDs = array();
6076
+		foreach ($model_objects as $model_object) {
6077
+			$id = $model_object->ID();
6078
+			if (! $id) {
6079
+				if ($filter_out_empty_ids) {
6080
+					continue;
6081
+				}
6082
+				if (WP_DEBUG) {
6083
+					EE_Error::add_error(
6084
+						__(
6085
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6086
+							'event_espresso'
6087
+						),
6088
+						__FILE__,
6089
+						__FUNCTION__,
6090
+						__LINE__
6091
+					);
6092
+				}
6093
+			}
6094
+			$IDs[] = $id;
6095
+		}
6096
+		return $IDs;
6097
+	}
6098
+
6099
+
6100
+
6101
+	/**
6102
+	 * Returns the string used in capabilities relating to this model. If there
6103
+	 * are no capabilities that relate to this model returns false
6104
+	 *
6105
+	 * @return string|false
6106
+	 */
6107
+	public function cap_slug()
6108
+	{
6109
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6110
+	}
6111
+
6112
+
6113
+
6114
+	/**
6115
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6116
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6117
+	 * only returns the cap restrictions array in that context (ie, the array
6118
+	 * at that key)
6119
+	 *
6120
+	 * @param string $context
6121
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6122
+	 * @throws EE_Error
6123
+	 */
6124
+	public function cap_restrictions($context = EEM_Base::caps_read)
6125
+	{
6126
+		EEM_Base::verify_is_valid_cap_context($context);
6127
+		// check if we ought to run the restriction generator first
6128
+		if (isset($this->_cap_restriction_generators[ $context ])
6129
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6130
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6131
+		) {
6132
+			$this->_cap_restrictions[ $context ] = array_merge(
6133
+				$this->_cap_restrictions[ $context ],
6134
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6135
+			);
6136
+		}
6137
+		// and make sure we've finalized the construction of each restriction
6138
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6139
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6140
+				$where_conditions_obj->_finalize_construct($this);
6141
+			}
6142
+		}
6143
+		return $this->_cap_restrictions[ $context ];
6144
+	}
6145
+
6146
+
6147
+
6148
+	/**
6149
+	 * Indicating whether or not this model thinks its a wp core model
6150
+	 *
6151
+	 * @return boolean
6152
+	 */
6153
+	public function is_wp_core_model()
6154
+	{
6155
+		return $this->_wp_core_model;
6156
+	}
6157
+
6158
+
6159
+
6160
+	/**
6161
+	 * Gets all the caps that are missing which impose a restriction on
6162
+	 * queries made in this context
6163
+	 *
6164
+	 * @param string $context one of EEM_Base::caps_ constants
6165
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6166
+	 * @throws EE_Error
6167
+	 */
6168
+	public function caps_missing($context = EEM_Base::caps_read)
6169
+	{
6170
+		$missing_caps = array();
6171
+		$cap_restrictions = $this->cap_restrictions($context);
6172
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6173
+			if (! EE_Capabilities::instance()
6174
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6175
+			) {
6176
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6177
+			}
6178
+		}
6179
+		return $missing_caps;
6180
+	}
6181
+
6182
+
6183
+
6184
+	/**
6185
+	 * Gets the mapping from capability contexts to action strings used in capability names
6186
+	 *
6187
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6188
+	 * one of 'read', 'edit', or 'delete'
6189
+	 */
6190
+	public function cap_contexts_to_cap_action_map()
6191
+	{
6192
+		return apply_filters(
6193
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6194
+			$this->_cap_contexts_to_cap_action_map,
6195
+			$this
6196
+		);
6197
+	}
6198
+
6199
+
6200
+
6201
+	/**
6202
+	 * Gets the action string for the specified capability context
6203
+	 *
6204
+	 * @param string $context
6205
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6206
+	 * @throws EE_Error
6207
+	 */
6208
+	public function cap_action_for_context($context)
6209
+	{
6210
+		$mapping = $this->cap_contexts_to_cap_action_map();
6211
+		if (isset($mapping[ $context ])) {
6212
+			return $mapping[ $context ];
6213
+		}
6214
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6215
+			return $action;
6216
+		}
6217
+		throw new EE_Error(
6218
+			sprintf(
6219
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6220
+				$context,
6221
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6222
+			)
6223
+		);
6224
+	}
6225
+
6226
+
6227
+
6228
+	/**
6229
+	 * Returns all the capability contexts which are valid when querying models
6230
+	 *
6231
+	 * @return array
6232
+	 */
6233
+	public static function valid_cap_contexts()
6234
+	{
6235
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6236
+			self::caps_read,
6237
+			self::caps_read_admin,
6238
+			self::caps_edit,
6239
+			self::caps_delete,
6240
+		));
6241
+	}
6242
+
6243
+
6244
+
6245
+	/**
6246
+	 * Returns all valid options for 'default_where_conditions'
6247
+	 *
6248
+	 * @return array
6249
+	 */
6250
+	public static function valid_default_where_conditions()
6251
+	{
6252
+		return array(
6253
+			EEM_Base::default_where_conditions_all,
6254
+			EEM_Base::default_where_conditions_this_only,
6255
+			EEM_Base::default_where_conditions_others_only,
6256
+			EEM_Base::default_where_conditions_minimum_all,
6257
+			EEM_Base::default_where_conditions_minimum_others,
6258
+			EEM_Base::default_where_conditions_none
6259
+		);
6260
+	}
6261
+
6262
+	// public static function default_where_conditions_full
6263
+	/**
6264
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6265
+	 *
6266
+	 * @param string $context
6267
+	 * @return bool
6268
+	 * @throws EE_Error
6269
+	 */
6270
+	public static function verify_is_valid_cap_context($context)
6271
+	{
6272
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6273
+		if (in_array($context, $valid_cap_contexts)) {
6274
+			return true;
6275
+		}
6276
+		throw new EE_Error(
6277
+			sprintf(
6278
+				__(
6279
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6280
+					'event_espresso'
6281
+				),
6282
+				$context,
6283
+				'EEM_Base',
6284
+				implode(',', $valid_cap_contexts)
6285
+			)
6286
+		);
6287
+	}
6288
+
6289
+
6290
+
6291
+	/**
6292
+	 * Clears all the models field caches. This is only useful when a sub-class
6293
+	 * might have added a field or something and these caches might be invalidated
6294
+	 */
6295
+	protected function _invalidate_field_caches()
6296
+	{
6297
+		$this->_cache_foreign_key_to_fields = array();
6298
+		$this->_cached_fields = null;
6299
+		$this->_cached_fields_non_db_only = null;
6300
+	}
6301
+
6302
+
6303
+
6304
+	/**
6305
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6306
+	 * (eg "and", "or", "not").
6307
+	 *
6308
+	 * @return array
6309
+	 */
6310
+	public function logic_query_param_keys()
6311
+	{
6312
+		return $this->_logic_query_param_keys;
6313
+	}
6314
+
6315
+
6316
+
6317
+	/**
6318
+	 * Determines whether or not the where query param array key is for a logic query param.
6319
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6320
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6321
+	 *
6322
+	 * @param $query_param_key
6323
+	 * @return bool
6324
+	 */
6325
+	public function is_logic_query_param_key($query_param_key)
6326
+	{
6327
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6328
+			if ($query_param_key === $logic_query_param_key
6329
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6330
+			) {
6331
+				return true;
6332
+			}
6333
+		}
6334
+		return false;
6335
+	}
6336
+
6337
+	/**
6338
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6339
+	 * @since 4.9.74.p
6340
+	 * @return boolean
6341
+	 */
6342
+	public function hasPassword()
6343
+	{
6344
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6345
+		if ($this->has_password_field === null) {
6346
+			$password_field = $this->getPasswordField();
6347
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6348
+		}
6349
+		return $this->has_password_field;
6350
+	}
6351
+
6352
+	/**
6353
+	 * Returns the password field on this model, if there is one
6354
+	 * @since 4.9.74.p
6355
+	 * @return EE_Password_Field|null
6356
+	 */
6357
+	public function getPasswordField()
6358
+	{
6359
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6360
+		// there's no need to search for it. If we don't know yet, then find out
6361
+		if ($this->has_password_field === null && $this->password_field === null) {
6362
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6363
+		}
6364
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6365
+		return $this->password_field;
6366
+	}
6367
+
6368
+
6369
+	/**
6370
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6371
+	 * @since 4.9.74.p
6372
+	 * @return EE_Model_Field_Base[]
6373
+	 * @throws EE_Error
6374
+	 */
6375
+	public function getPasswordProtectedFields()
6376
+	{
6377
+		$password_field = $this->getPasswordField();
6378
+		$fields = array();
6379
+		if ($password_field instanceof EE_Password_Field) {
6380
+			$field_names = $password_field->protectedFields();
6381
+			foreach ($field_names as $field_name) {
6382
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6383
+			}
6384
+		}
6385
+		return $fields;
6386
+	}
6387
+
6388
+
6389
+	/**
6390
+	 * Checks if the current user can perform the requested action on this model
6391
+	 * @since 4.9.74.p
6392
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6393
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6394
+	 * @return bool
6395
+	 * @throws EE_Error
6396
+	 * @throws InvalidArgumentException
6397
+	 * @throws InvalidDataTypeException
6398
+	 * @throws InvalidInterfaceException
6399
+	 * @throws ReflectionException
6400
+	 * @throws UnexpectedEntityException
6401
+	 */
6402
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6403
+	{
6404
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6405
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6406
+		}
6407
+		if (!is_array($model_obj_or_fields_n_values)) {
6408
+			throw new UnexpectedEntityException(
6409
+				$model_obj_or_fields_n_values,
6410
+				'EE_Base_Class',
6411
+				sprintf(
6412
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6413
+					__FUNCTION__
6414
+				)
6415
+			);
6416
+		}
6417
+		return $this->exists(
6418
+			$this->alter_query_params_to_restrict_by_ID(
6419
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6420
+				array(
6421
+					'default_where_conditions' => 'none',
6422
+					'caps'                     => $cap_to_check,
6423
+				)
6424
+			)
6425
+		);
6426
+	}
6427
+
6428
+	/**
6429
+	 * Returns the query param where conditions key to the password affecting this model.
6430
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6431
+	 * @since 4.9.74.p
6432
+	 * @return null|string
6433
+	 * @throws EE_Error
6434
+	 * @throws InvalidArgumentException
6435
+	 * @throws InvalidDataTypeException
6436
+	 * @throws InvalidInterfaceException
6437
+	 * @throws ModelConfigurationException
6438
+	 * @throws ReflectionException
6439
+	 */
6440
+	public function modelChainAndPassword()
6441
+	{
6442
+		if ($this->model_chain_to_password === null) {
6443
+			throw new ModelConfigurationException(
6444
+				$this,
6445
+				esc_html_x(
6446
+				// @codingStandardsIgnoreStart
6447
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6448
+					// @codingStandardsIgnoreEnd
6449
+					'1: model name',
6450
+					'event_espresso'
6451
+				)
6452
+			);
6453
+		}
6454
+		if ($this->model_chain_to_password === '') {
6455
+			$model_with_password = $this;
6456
+		} else {
6457
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6458
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6459
+			} else {
6460
+				$last_model_in_chain = $this->model_chain_to_password;
6461
+			}
6462
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6463
+		}
6464
+
6465
+		$password_field = $model_with_password->getPasswordField();
6466
+		if ($password_field instanceof EE_Password_Field) {
6467
+			$password_field_name = $password_field->get_name();
6468
+		} else {
6469
+			throw new ModelConfigurationException(
6470
+				$this,
6471
+				sprintf(
6472
+					esc_html_x(
6473
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6474
+						'1: model name, 2: special string',
6475
+						'event_espresso'
6476
+					),
6477
+					$model_with_password->get_this_model_name(),
6478
+					$this->model_chain_to_password
6479
+				)
6480
+			);
6481
+		}
6482
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6483
+	}
6484
+
6485
+	/**
6486
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6487
+	 * or if this model itself has a password affecting access to some of its other fields.
6488
+	 * @since 4.9.74.p
6489
+	 * @return boolean
6490
+	 */
6491
+	public function restrictedByRelatedModelPassword()
6492
+	{
6493
+		return $this->model_chain_to_password !== null;
6494
+	}
6495 6495
 }
Please login to merge, or discard this patch.
Spacing   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     __(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             __(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
     {
890 890
         $wp_user_field_name = $this->wp_user_field_name();
891 891
         if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
892
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
893 893
         }
894 894
         return $query_params;
895 895
     }
@@ -907,17 +907,17 @@  discard block
 block discarded – undo
907 907
     public function wp_user_field_name()
908 908
     {
909 909
         try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
910
+            if ( ! empty($this->_model_chain_to_wp_user)) {
911 911
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912 912
                 $last_model_name = end($models_to_follow_to_wp_users);
913 913
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
914
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
915 915
             } else {
916 916
                 $model_with_fk_to_wp_users = $this;
917 917
                 $model_chain_to_wp_user = '';
918 918
             }
919 919
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
920
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
921 921
         } catch (EE_Error $e) {
922 922
             return false;
923 923
         }
@@ -994,11 +994,11 @@  discard block
 block discarded – undo
994 994
         if ($this->_custom_selections instanceof CustomSelects) {
995 995
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996 996
             $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
997
+                ? ', '.$custom_expressions
998 998
                 : $custom_expressions;
999 999
         }
1000 1000
 
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1001
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1002 1002
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003 1003
     }
1004 1004
 
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
      */
1016 1016
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017 1017
     {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1018
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019 1019
             return null;
1020 1020
         }
1021 1021
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
         if (is_array($columns_to_select)) {
1065 1065
             $select_sql_array = array();
1066 1066
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1067
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068 1068
                     throw new EE_Error(
1069 1069
                         sprintf(
1070 1070
                             __(
@@ -1076,7 +1076,7 @@  discard block
 block discarded – undo
1076 1076
                         )
1077 1077
                     );
1078 1078
                 }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1079
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080 1080
                     throw new EE_Error(
1081 1081
                         sprintf(
1082 1082
                             esc_html__(
@@ -1155,12 +1155,12 @@  discard block
 block discarded – undo
1155 1155
      */
1156 1156
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157 1157
     {
1158
-        if (! isset($query_params[0])) {
1158
+        if ( ! isset($query_params[0])) {
1159 1159
             $query_params[0] = array();
1160 1160
         }
1161 1161
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1162 1162
         if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1163
+            $query_params[0][$this->primary_key_name()] = $id;
1164 1164
         } else {
1165 1165
             // no primary key, so the $id must be from the get_index_primary_key_string()
1166 1166
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
      */
1181 1181
     public function get_one($query_params = array())
1182 1182
     {
1183
-        if (! is_array($query_params)) {
1183
+        if ( ! is_array($query_params)) {
1184 1184
             EE_Error::doing_it_wrong(
1185 1185
                 'EEM_Base::get_one',
1186 1186
                 sprintf(
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
                 return array();
1379 1379
             }
1380 1380
         }
1381
-        if (! is_array($query_params)) {
1381
+        if ( ! is_array($query_params)) {
1382 1382
             EE_Error::doing_it_wrong(
1383 1383
                 'EEM_Base::_get_consecutive',
1384 1384
                 sprintf(
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
             $query_params = array();
1391 1391
         }
1392 1392
         // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1393
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1394 1394
         $query_params['limit'] = $limit;
1395 1395
         // set direction
1396 1396
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
     {
1472 1472
         $field_settings = $this->field_settings_for($field_name);
1473 1473
         // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1474
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1475 1475
             throw new EE_Error(sprintf(__(
1476 1476
                 'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1477 1477
                 'event_espresso'
@@ -1620,7 +1620,7 @@  discard block
 block discarded – undo
1620 1620
      */
1621 1621
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622 1622
     {
1623
-        if (! is_array($query_params)) {
1623
+        if ( ! is_array($query_params)) {
1624 1624
             EE_Error::doing_it_wrong(
1625 1625
                 'EEM_Base::update',
1626 1626
                 sprintf(
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
             $wpdb_result = (array) $wpdb_result;
1669 1669
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670 1670
             if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1671
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1672 1672
             } else {
1673 1673
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1674 1674
                 $main_table_pk_value = null;
@@ -1682,8 +1682,8 @@  discard block
 block discarded – undo
1682 1682
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683 1683
                     // if there is no private key for this table on the results, it means there's no entry
1684 1684
                     // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1685
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+                           && $wpdb_result[$this_table_pk_column])
1687 1687
                     ) {
1688 1688
                         $success = $this->_insert_into_specific_table(
1689 1689
                             $table_obj,
@@ -1691,7 +1691,7 @@  discard block
 block discarded – undo
1691 1691
                             $main_table_pk_value
1692 1692
                         );
1693 1693
                         // if we died here, report the error
1694
-                        if (! $success) {
1694
+                        if ( ! $success) {
1695 1695
                             return false;
1696 1696
                         }
1697 1697
                     }
@@ -1719,10 +1719,10 @@  discard block
 block discarded – undo
1719 1719
                 $model_objs_affected_ids = array();
1720 1720
                 foreach ($models_affected_key_columns as $row) {
1721 1721
                     $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1722
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1723 1723
                 }
1724 1724
             }
1725
-            if (! $model_objs_affected_ids) {
1725
+            if ( ! $model_objs_affected_ids) {
1726 1726
                 // wait wait wait- if nothing was affected let's stop here
1727 1727
                 return 0;
1728 1728
             }
@@ -1749,7 +1749,7 @@  discard block
 block discarded – undo
1749 1749
                . $model_query_info->get_full_join_sql()
1750 1750
                . " SET "
1751 1751
                . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1752
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753 1753
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754 1754
         /**
1755 1755
          * Action called after a model update call has been made.
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
          * @param int      $rows_affected
1761 1761
          */
1762 1762
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1763
+        return $rows_affected; // how many supposedly got updated
1764 1764
     }
1765 1765
 
1766 1766
 
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
         }
1789 1789
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790 1790
         $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1791
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1792 1792
         return $this->_do_wpdb_query('get_col', array($SQL));
1793 1793
     }
1794 1794
 
@@ -1806,7 +1806,7 @@  discard block
 block discarded – undo
1806 1806
     {
1807 1807
         $query_params['limit'] = 1;
1808 1808
         $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1809
+        if ( ! empty($col)) {
1810 1810
             return reset($col);
1811 1811
         }
1812 1812
         return null;
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838 1838
             $value_sql = $prepared_value === null ? 'NULL'
1839 1839
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1840
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1841 1841
         }
1842 1842
         return implode(",", $cols_n_values);
1843 1843
     }
@@ -1980,12 +1980,12 @@  discard block
 block discarded – undo
1980 1980
         // there was no error with the delete query.
1981 1981
         if ($this->has_primary_key_field()
1982 1982
             && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1983
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1984 1984
         ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1985
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1986 1986
             foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1987
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1988
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1989 1989
                 }
1990 1990
             }
1991 1991
 
@@ -2020,7 +2020,7 @@  discard block
 block discarded – undo
2020 2020
          * @param int      $rows_deleted
2021 2021
          */
2022 2022
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2023
+        return $rows_deleted; // how many supposedly got deleted
2024 2024
     }
2025 2025
 
2026 2026
 
@@ -2113,15 +2113,15 @@  discard block
 block discarded – undo
2113 2113
                 // make sure there's no related entities blocking its deletion (if we're checking)
2114 2114
                 if ($allow_blocking
2115 2115
                     && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2116
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2117 2117
                     )
2118 2118
                 ) {
2119 2119
                     continue;
2120 2120
                 }
2121 2121
                 // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2122
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2123
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2124
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2125 2125
                 }
2126 2126
             }
2127 2127
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2130,8 +2130,8 @@  discard block
 block discarded – undo
2130 2130
                 $ids_to_delete_indexed_by_column_for_row = array();
2131 2131
                 foreach ($fields as $cpk_field) {
2132 2132
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2133
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2134
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2135 2135
                     }
2136 2136
                 }
2137 2137
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2169,7 +2169,7 @@  discard block
 block discarded – undo
2169 2169
         } elseif ($this->has_primary_key_field()) {
2170 2170
             $query = array();
2171 2171
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2172
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2173 2173
             }
2174 2174
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2175 2175
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2177,7 +2177,7 @@  discard block
 block discarded – undo
2177 2177
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2178 2178
                 $values_for_each_combined_primary_key_for_a_row = array();
2179 2179
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2180
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2180
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2181 2181
                 }
2182 2182
                 $ways_to_identify_a_row[] = '('
2183 2183
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2249,8 +2249,8 @@  discard block
 block discarded – undo
2249 2249
                 $column_to_count = '*';
2250 2250
             }
2251 2251
         }
2252
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2253
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2252
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2253
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2254 2254
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2255 2255
     }
2256 2256
 
@@ -2273,7 +2273,7 @@  discard block
 block discarded – undo
2273 2273
             $field_obj = $this->get_primary_key_field();
2274 2274
         }
2275 2275
         $column_to_count = $field_obj->get_qualified_column();
2276
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2276
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2277 2277
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2278 2278
         $data_type = $field_obj->get_wpdb_data_type();
2279 2279
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2300,7 +2300,7 @@  discard block
 block discarded – undo
2300 2300
         // if we're in maintenance mode level 2, DON'T run any queries
2301 2301
         // because level 2 indicates the database needs updating and
2302 2302
         // is probably out of sync with the code
2303
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2303
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2304 2304
             throw new EE_Error(sprintf(__(
2305 2305
                 "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2306 2306
                 "event_espresso"
@@ -2308,7 +2308,7 @@  discard block
 block discarded – undo
2308 2308
         }
2309 2309
         /** @type WPDB $wpdb */
2310 2310
         global $wpdb;
2311
-        if (! method_exists($wpdb, $wpdb_method)) {
2311
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2312 2312
             throw new EE_Error(sprintf(__(
2313 2313
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2314 2314
                 'event_espresso'
@@ -2322,7 +2322,7 @@  discard block
 block discarded – undo
2322 2322
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2323 2323
         if (WP_DEBUG) {
2324 2324
             $wpdb->show_errors($old_show_errors_value);
2325
-            if (! empty($wpdb->last_error)) {
2325
+            if ( ! empty($wpdb->last_error)) {
2326 2326
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2327 2327
             }
2328 2328
             if ($result === false) {
@@ -2387,7 +2387,7 @@  discard block
 block discarded – undo
2387 2387
                     return $result;
2388 2388
                     break;
2389 2389
             }
2390
-            if (! empty($error_message)) {
2390
+            if ( ! empty($error_message)) {
2391 2391
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2392 2392
                 trigger_error($error_message);
2393 2393
             }
@@ -2467,11 +2467,11 @@  discard block
 block discarded – undo
2467 2467
      */
2468 2468
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2469 2469
     {
2470
-        return " FROM " . $model_query_info->get_full_join_sql() .
2471
-               $model_query_info->get_where_sql() .
2472
-               $model_query_info->get_group_by_sql() .
2473
-               $model_query_info->get_having_sql() .
2474
-               $model_query_info->get_order_by_sql() .
2470
+        return " FROM ".$model_query_info->get_full_join_sql().
2471
+               $model_query_info->get_where_sql().
2472
+               $model_query_info->get_group_by_sql().
2473
+               $model_query_info->get_having_sql().
2474
+               $model_query_info->get_order_by_sql().
2475 2475
                $model_query_info->get_limit_sql();
2476 2476
     }
2477 2477
 
@@ -2667,12 +2667,12 @@  discard block
 block discarded – undo
2667 2667
         $related_model = $this->get_related_model_obj($model_name);
2668 2668
         // we're just going to use the query params on the related model's normal get_all query,
2669 2669
         // except add a condition to say to match the current mod
2670
-        if (! isset($query_params['default_where_conditions'])) {
2670
+        if ( ! isset($query_params['default_where_conditions'])) {
2671 2671
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2672 2672
         }
2673 2673
         $this_model_name = $this->get_this_model_name();
2674 2674
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2675
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2675
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2676 2676
         return $related_model->count($query_params, $field_to_count, $distinct);
2677 2677
     }
2678 2678
 
@@ -2692,7 +2692,7 @@  discard block
 block discarded – undo
2692 2692
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2693 2693
     {
2694 2694
         $related_model = $this->get_related_model_obj($model_name);
2695
-        if (! is_array($query_params)) {
2695
+        if ( ! is_array($query_params)) {
2696 2696
             EE_Error::doing_it_wrong(
2697 2697
                 'EEM_Base::sum_related',
2698 2698
                 sprintf(
@@ -2705,12 +2705,12 @@  discard block
 block discarded – undo
2705 2705
         }
2706 2706
         // we're just going to use the query params on the related model's normal get_all query,
2707 2707
         // except add a condition to say to match the current mod
2708
-        if (! isset($query_params['default_where_conditions'])) {
2708
+        if ( ! isset($query_params['default_where_conditions'])) {
2709 2709
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2710 2710
         }
2711 2711
         $this_model_name = $this->get_this_model_name();
2712 2712
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2713
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2713
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2714 2714
         return $related_model->sum($query_params, $field_to_sum);
2715 2715
     }
2716 2716
 
@@ -2763,7 +2763,7 @@  discard block
 block discarded – undo
2763 2763
                 $field_with_model_name = $field;
2764 2764
             }
2765 2765
         }
2766
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2766
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2767 2767
             throw new EE_Error(sprintf(
2768 2768
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2769 2769
                 $this->get_this_model_name()
@@ -2899,13 +2899,13 @@  discard block
 block discarded – undo
2899 2899
                 || $this->get_primary_key_field()
2900 2900
                    instanceof
2901 2901
                    EE_Primary_Key_String_Field)
2902
-            && isset($fields_n_values[ $this->primary_key_name() ])
2902
+            && isset($fields_n_values[$this->primary_key_name()])
2903 2903
         ) {
2904
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2904
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2905 2905
         }
2906 2906
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907 2907
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2908
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2909 2909
         }
2910 2910
         // if there is nothing to base this search on, then we shouldn't find anything
2911 2911
         if (empty($query_params)) {
@@ -2983,15 +2983,15 @@  discard block
 block discarded – undo
2983 2983
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984 2984
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2985 2985
             if ($prepared_value !== null) {
2986
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2986
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2987 2987
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988 2988
             }
2989 2989
         }
2990 2990
         if ($table instanceof EE_Secondary_Table && $new_id) {
2991 2991
             // its not the main table, so we should have already saved the main table's PK which we just inserted
2992 2992
             // so add the fk to the main table as a column
2993
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2994
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2993
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2994
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
2995 2995
         }
2996 2996
         // insert the new entry
2997 2997
         $result = $this->_do_wpdb_query(
@@ -3008,7 +3008,7 @@  discard block
 block discarded – undo
3008 3008
             }
3009 3009
             // it's not an auto-increment primary key, so
3010 3010
             // it must have been supplied
3011
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3011
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3012 3012
         }
3013 3013
         // we can't return a  primary key because there is none. instead return
3014 3014
         // a unique string indicating this model
@@ -3030,16 +3030,16 @@  discard block
 block discarded – undo
3030 3030
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3031 3031
     {
3032 3032
         // if this field doesn't allow nullable, don't allow it
3033
-        if (! $field_obj->is_nullable()
3033
+        if ( ! $field_obj->is_nullable()
3034 3034
             && (
3035
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3036
-                || $fields_n_values[ $field_obj->get_name() ] === null
3035
+                ! isset($fields_n_values[$field_obj->get_name()])
3036
+                || $fields_n_values[$field_obj->get_name()] === null
3037 3037
             )
3038 3038
         ) {
3039
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3039
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3040 3040
         }
3041
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3042
-            ? $fields_n_values[ $field_obj->get_name() ]
3041
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3042
+            ? $fields_n_values[$field_obj->get_name()]
3043 3043
             : null;
3044 3044
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3045 3045
     }
@@ -3140,7 +3140,7 @@  discard block
 block discarded – undo
3140 3140
      */
3141 3141
     public function get_table_obj_by_alias($table_alias = '')
3142 3142
     {
3143
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3143
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3144 3144
     }
3145 3145
 
3146 3146
 
@@ -3155,7 +3155,7 @@  discard block
 block discarded – undo
3155 3155
         $other_tables = array();
3156 3156
         foreach ($this->_tables as $table_alias => $table) {
3157 3157
             if ($table instanceof EE_Secondary_Table) {
3158
-                $other_tables[ $table_alias ] = $table;
3158
+                $other_tables[$table_alias] = $table;
3159 3159
             }
3160 3160
         }
3161 3161
         return $other_tables;
@@ -3171,7 +3171,7 @@  discard block
 block discarded – undo
3171 3171
      */
3172 3172
     public function _get_fields_for_table($table_alias)
3173 3173
     {
3174
-        return $this->_fields[ $table_alias ];
3174
+        return $this->_fields[$table_alias];
3175 3175
     }
3176 3176
 
3177 3177
 
@@ -3200,7 +3200,7 @@  discard block
 block discarded – undo
3200 3200
                     $query_info_carrier,
3201 3201
                     'group_by'
3202 3202
                 );
3203
-            } elseif (! empty($query_params['group_by'])) {
3203
+            } elseif ( ! empty($query_params['group_by'])) {
3204 3204
                 $this->_extract_related_model_info_from_query_param(
3205 3205
                     $query_params['group_by'],
3206 3206
                     $query_info_carrier,
@@ -3222,7 +3222,7 @@  discard block
 block discarded – undo
3222 3222
                     $query_info_carrier,
3223 3223
                     'order_by'
3224 3224
                 );
3225
-            } elseif (! empty($query_params['order_by'])) {
3225
+            } elseif ( ! empty($query_params['order_by'])) {
3226 3226
                 $this->_extract_related_model_info_from_query_param(
3227 3227
                     $query_params['order_by'],
3228 3228
                     $query_info_carrier,
@@ -3257,7 +3257,7 @@  discard block
 block discarded – undo
3257 3257
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3258 3258
         $query_param_type
3259 3259
     ) {
3260
-        if (! empty($sub_query_params)) {
3260
+        if ( ! empty($sub_query_params)) {
3261 3261
             $sub_query_params = (array) $sub_query_params;
3262 3262
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3263 3263
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3272,7 +3272,7 @@  discard block
 block discarded – undo
3272 3272
                 // of array('Registration.TXN_ID'=>23)
3273 3273
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3274 3274
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3275
-                    if (! is_array($possibly_array_of_params)) {
3275
+                    if ( ! is_array($possibly_array_of_params)) {
3276 3276
                         throw new EE_Error(sprintf(
3277 3277
                             __(
3278 3278
                                 "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
@@ -3295,7 +3295,7 @@  discard block
 block discarded – undo
3295 3295
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3296 3296
                     // indicating that $possible_array_of_params[1] is actually a field name,
3297 3297
                     // from which we should extract query parameters!
3298
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3298
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3299 3299
                         throw new EE_Error(sprintf(__(
3300 3300
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3301 3301
                             "event_espresso"
@@ -3329,8 +3329,8 @@  discard block
 block discarded – undo
3329 3329
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330 3330
         $query_param_type
3331 3331
     ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3332
+        if ( ! empty($sub_query_params)) {
3333
+            if ( ! is_array($sub_query_params)) {
3334 3334
                 throw new EE_Error(sprintf(
3335 3335
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336 3336
                     $sub_query_params
@@ -3364,7 +3364,7 @@  discard block
 block discarded – undo
3364 3364
      */
3365 3365
     public function _create_model_query_info_carrier($query_params)
3366 3366
     {
3367
-        if (! is_array($query_params)) {
3367
+        if ( ! is_array($query_params)) {
3368 3368
             EE_Error::doing_it_wrong(
3369 3369
                 'EEM_Base::_create_model_query_info_carrier',
3370 3370
                 sprintf(
@@ -3397,7 +3397,7 @@  discard block
 block discarded – undo
3397 3397
             // only include if related to a cpt where no password has been set
3398 3398
             $query_params[0]['OR*nopassword'] = array(
3399 3399
                 $where_param_key_for_password => '',
3400
-                $where_param_key_for_password . '*' => array('IS_NULL')
3400
+                $where_param_key_for_password.'*' => array('IS_NULL')
3401 3401
             );
3402 3402
         }
3403 3403
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3450,7 +3450,7 @@  discard block
 block discarded – undo
3450 3450
         // set limit
3451 3451
         if (array_key_exists('limit', $query_params)) {
3452 3452
             if (is_array($query_params['limit'])) {
3453
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3453
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3454 3454
                     $e = sprintf(
3455 3455
                         __(
3456 3456
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3458,12 +3458,12 @@  discard block
 block discarded – undo
3458 3458
                         ),
3459 3459
                         http_build_query($query_params['limit'])
3460 3460
                     );
3461
-                    throw new EE_Error($e . "|" . $e);
3461
+                    throw new EE_Error($e."|".$e);
3462 3462
                 }
3463 3463
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3464
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3465
-            } elseif (! empty($query_params['limit'])) {
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3464
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3465
+            } elseif ( ! empty($query_params['limit'])) {
3466
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3467 3467
             }
3468 3468
         }
3469 3469
         // set order by
@@ -3495,10 +3495,10 @@  discard block
 block discarded – undo
3495 3495
                 $order_array = array();
3496 3496
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3497 3497
                     $order = $this->_extract_order($order);
3498
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3498
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3499 3499
                 }
3500
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3501
-            } elseif (! empty($query_params['order_by'])) {
3500
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3501
+            } elseif ( ! empty($query_params['order_by'])) {
3502 3502
                 $this->_extract_related_model_info_from_query_param(
3503 3503
                     $query_params['order_by'],
3504 3504
                     $query_object,
@@ -3509,18 +3509,18 @@  discard block
 block discarded – undo
3509 3509
                     ? $this->_extract_order($query_params['order'])
3510 3510
                     : 'DESC';
3511 3511
                 $query_object->set_order_by_sql(
3512
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3512
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3513 3513
                 );
3514 3514
             }
3515 3515
         }
3516 3516
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3517
-        if (! array_key_exists('order_by', $query_params)
3517
+        if ( ! array_key_exists('order_by', $query_params)
3518 3518
             && array_key_exists('order', $query_params)
3519 3519
             && ! empty($query_params['order'])
3520 3520
         ) {
3521 3521
             $pk_field = $this->get_primary_key_field();
3522 3522
             $order = $this->_extract_order($query_params['order']);
3523
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3523
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3524 3524
         }
3525 3525
         // set group by
3526 3526
         if (array_key_exists('group_by', $query_params)) {
@@ -3530,10 +3530,10 @@  discard block
 block discarded – undo
3530 3530
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3531 3531
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3532 3532
                 }
3533
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3534
-            } elseif (! empty($query_params['group_by'])) {
3533
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3534
+            } elseif ( ! empty($query_params['group_by'])) {
3535 3535
                 $query_object->set_group_by_sql(
3536
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3536
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3537 3537
                 );
3538 3538
             }
3539 3539
         }
@@ -3543,7 +3543,7 @@  discard block
 block discarded – undo
3543 3543
         }
3544 3544
         // now, just verify they didn't pass anything wack
3545 3545
         foreach ($query_params as $query_key => $query_value) {
3546
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3546
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3547 3547
                 throw new EE_Error(
3548 3548
                     sprintf(
3549 3549
                         __(
@@ -3651,7 +3651,7 @@  discard block
 block discarded – undo
3651 3651
         $where_query_params = array()
3652 3652
     ) {
3653 3653
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3654
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3654
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3655 3655
             throw new EE_Error(sprintf(
3656 3656
                 __(
3657 3657
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3783,19 +3783,19 @@  discard block
 block discarded – undo
3783 3783
     ) {
3784 3784
         $null_friendly_where_conditions = array();
3785 3785
         $none_overridden = true;
3786
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3786
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3787 3787
         foreach ($default_where_conditions as $key => $val) {
3788
-            if (isset($provided_where_conditions[ $key ])) {
3788
+            if (isset($provided_where_conditions[$key])) {
3789 3789
                 $none_overridden = false;
3790 3790
             } else {
3791
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3791
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3792 3792
             }
3793 3793
         }
3794 3794
         if ($none_overridden && $default_where_conditions) {
3795 3795
             if ($model->has_primary_key_field()) {
3796
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3796
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3797 3797
                                                                                 . "."
3798
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3798
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3799 3799
             }/*else{
3800 3800
                 //@todo NO PK, use other defaults
3801 3801
             }*/
@@ -3901,7 +3901,7 @@  discard block
 block discarded – undo
3901 3901
             foreach ($tables as $table_obj) {
3902 3902
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3903 3903
                                        . $table_obj->get_fully_qualified_pk_column();
3904
-                if (! in_array($qualified_pk_column, $selects)) {
3904
+                if ( ! in_array($qualified_pk_column, $selects)) {
3905 3905
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3906 3906
                 }
3907 3907
             }
@@ -4050,9 +4050,9 @@  discard block
 block discarded – undo
4050 4050
         $query_parameter_type
4051 4051
     ) {
4052 4052
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4053
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4053
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4054 4054
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4055
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4055
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4056 4056
                 if ($possible_join_string === '') {
4057 4057
                     // nothing left to $query_param
4058 4058
                     // we should actually end in a field name, not a model like this!
@@ -4182,7 +4182,7 @@  discard block
 block discarded – undo
4182 4182
     {
4183 4183
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4184 4184
         if ($SQL) {
4185
-            return " WHERE " . $SQL;
4185
+            return " WHERE ".$SQL;
4186 4186
         }
4187 4187
         return '';
4188 4188
     }
@@ -4201,7 +4201,7 @@  discard block
 block discarded – undo
4201 4201
     {
4202 4202
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4203 4203
         if ($SQL) {
4204
-            return " HAVING " . $SQL;
4204
+            return " HAVING ".$SQL;
4205 4205
         }
4206 4206
         return '';
4207 4207
     }
@@ -4220,7 +4220,7 @@  discard block
 block discarded – undo
4220 4220
     {
4221 4221
         $where_clauses = array();
4222 4222
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4223
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4223
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4224 4224
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4225 4225
                 switch ($query_param) {
4226 4226
                     case 'not':
@@ -4254,7 +4254,7 @@  discard block
 block discarded – undo
4254 4254
             } else {
4255 4255
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4256 4256
                 // if it's not a normal field, maybe it's a custom selection?
4257
-                if (! $field_obj) {
4257
+                if ( ! $field_obj) {
4258 4258
                     if ($this->_custom_selections instanceof CustomSelects) {
4259 4259
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4260 4260
                     } else {
@@ -4265,7 +4265,7 @@  discard block
 block discarded – undo
4265 4265
                     }
4266 4266
                 }
4267 4267
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4268
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4268
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4269 4269
             }
4270 4270
         }
4271 4271
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4288,7 +4288,7 @@  discard block
 block discarded – undo
4288 4288
                 $field->get_model_name(),
4289 4289
                 $query_param
4290 4290
             );
4291
-            return $table_alias_prefix . $field->get_qualified_column();
4291
+            return $table_alias_prefix.$field->get_qualified_column();
4292 4292
         }
4293 4293
         if ($this->_custom_selections instanceof CustomSelects
4294 4294
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4347,7 +4347,7 @@  discard block
 block discarded – undo
4347 4347
     {
4348 4348
         if (is_array($op_and_value)) {
4349 4349
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4350
-            if (! $operator) {
4350
+            if ( ! $operator) {
4351 4351
                 $php_array_like_string = array();
4352 4352
                 foreach ($op_and_value as $key => $value) {
4353 4353
                     $php_array_like_string[] = "$key=>$value";
@@ -4369,14 +4369,14 @@  discard block
 block discarded – undo
4369 4369
         }
4370 4370
         // check to see if the value is actually another field
4371 4371
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4372
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4372
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4373 4373
         }
4374 4374
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4375 4375
             // in this case, the value should be an array, or at least a comma-separated list
4376 4376
             // it will need to handle a little differently
4377 4377
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4378 4378
             // note: $cleaned_value has already been run through $wpdb->prepare()
4379
-            return $operator . SP . $cleaned_value;
4379
+            return $operator.SP.$cleaned_value;
4380 4380
         }
4381 4381
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4382 4382
             // the value should be an array with count of two.
@@ -4392,7 +4392,7 @@  discard block
 block discarded – undo
4392 4392
                 );
4393 4393
             }
4394 4394
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4395
-            return $operator . SP . $cleaned_value;
4395
+            return $operator.SP.$cleaned_value;
4396 4396
         }
4397 4397
         if (in_array($operator, $this->valid_null_style_operators())) {
4398 4398
             if ($value !== null) {
@@ -4412,10 +4412,10 @@  discard block
 block discarded – undo
4412 4412
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4413 4413
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4414 4414
             // remove other junk. So just treat it as a string.
4415
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4415
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4416 4416
         }
4417
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4418
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4417
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4418
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4419 4419
         }
4420 4420
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4421 4421
             throw new EE_Error(
@@ -4429,7 +4429,7 @@  discard block
 block discarded – undo
4429 4429
                 )
4430 4430
             );
4431 4431
         }
4432
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4432
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4433 4433
             throw new EE_Error(
4434 4434
                 sprintf(
4435 4435
                     __(
@@ -4469,7 +4469,7 @@  discard block
 block discarded – undo
4469 4469
         foreach ($values as $value) {
4470 4470
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4471 4471
         }
4472
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4472
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4473 4473
     }
4474 4474
 
4475 4475
 
@@ -4503,11 +4503,11 @@  discard block
 block discarded – undo
4503 4503
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4504 4504
         if (empty($prepped)) {
4505 4505
             $all_fields = $this->field_settings();
4506
-            $first_field    = reset($all_fields);
4506
+            $first_field = reset($all_fields);
4507 4507
             $main_table = $this->_get_main_table();
4508 4508
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4509 4509
         }
4510
-        return '(' . implode(',', $prepped) . ')';
4510
+        return '('.implode(',', $prepped).')';
4511 4511
     }
4512 4512
 
4513 4513
 
@@ -4528,7 +4528,7 @@  discard block
 block discarded – undo
4528 4528
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4529 4529
             );
4530 4530
         } //$field_obj should really just be a data type
4531
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4531
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4532 4532
             throw new EE_Error(
4533 4533
                 sprintf(
4534 4534
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4561,14 +4561,14 @@  discard block
 block discarded – undo
4561 4561
             ), $query_param_name));
4562 4562
         }
4563 4563
         $number_of_parts = count($query_param_parts);
4564
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4564
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4565 4565
         if ($number_of_parts === 1) {
4566 4566
             $field_name = $last_query_param_part;
4567 4567
             $model_obj = $this;
4568 4568
         } else {// $number_of_parts >= 2
4569 4569
             // the last part is the column name, and there are only 2parts. therefore...
4570 4570
             $field_name = $last_query_param_part;
4571
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4571
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4572 4572
         }
4573 4573
         try {
4574 4574
             return $model_obj->field_settings_for($field_name);
@@ -4590,7 +4590,7 @@  discard block
 block discarded – undo
4590 4590
     public function _get_qualified_column_for_field($field_name)
4591 4591
     {
4592 4592
         $all_fields = $this->field_settings();
4593
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4593
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4594 4594
         if ($field) {
4595 4595
             return $field->get_qualified_column();
4596 4596
         }
@@ -4661,10 +4661,10 @@  discard block
 block discarded – undo
4661 4661
      */
4662 4662
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4663 4663
     {
4664
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4664
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4665 4665
         $qualified_columns = array();
4666 4666
         foreach ($this->field_settings() as $field_name => $field) {
4667
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4667
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4668 4668
         }
4669 4669
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4670 4670
     }
@@ -4688,11 +4688,11 @@  discard block
 block discarded – undo
4688 4688
             if ($table_obj instanceof EE_Primary_Table) {
4689 4689
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4690 4690
                     ? $table_obj->get_select_join_limit($limit)
4691
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4691
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4692 4692
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4693 4693
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4694 4694
                     ? $table_obj->get_select_join_limit_join($limit)
4695
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4695
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4696 4696
             }
4697 4697
         }
4698 4698
         return $SQL;
@@ -4764,7 +4764,7 @@  discard block
 block discarded – undo
4764 4764
         foreach ($this->field_settings() as $field_obj) {
4765 4765
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4766 4766
             /** @var $field_obj EE_Model_Field_Base */
4767
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4767
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4768 4768
         }
4769 4769
         return $data_types;
4770 4770
     }
@@ -4780,14 +4780,14 @@  discard block
 block discarded – undo
4780 4780
      */
4781 4781
     public function get_related_model_obj($model_name)
4782 4782
     {
4783
-        $model_classname = "EEM_" . $model_name;
4784
-        if (! class_exists($model_classname)) {
4783
+        $model_classname = "EEM_".$model_name;
4784
+        if ( ! class_exists($model_classname)) {
4785 4785
             throw new EE_Error(sprintf(__(
4786 4786
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4787 4787
                 'event_espresso'
4788 4788
             ), $model_name, $model_classname));
4789 4789
         }
4790
-        return call_user_func($model_classname . "::instance");
4790
+        return call_user_func($model_classname."::instance");
4791 4791
     }
4792 4792
 
4793 4793
 
@@ -4816,7 +4816,7 @@  discard block
 block discarded – undo
4816 4816
         $belongs_to_relations = array();
4817 4817
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4818 4818
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4819
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4819
+                $belongs_to_relations[$model_name] = $relation_obj;
4820 4820
             }
4821 4821
         }
4822 4822
         return $belongs_to_relations;
@@ -4834,7 +4834,7 @@  discard block
 block discarded – undo
4834 4834
     public function related_settings_for($relation_name)
4835 4835
     {
4836 4836
         $relatedModels = $this->relation_settings();
4837
-        if (! array_key_exists($relation_name, $relatedModels)) {
4837
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4838 4838
             throw new EE_Error(
4839 4839
                 sprintf(
4840 4840
                     __(
@@ -4847,7 +4847,7 @@  discard block
 block discarded – undo
4847 4847
                 )
4848 4848
             );
4849 4849
         }
4850
-        return $relatedModels[ $relation_name ];
4850
+        return $relatedModels[$relation_name];
4851 4851
     }
4852 4852
 
4853 4853
 
@@ -4864,14 +4864,14 @@  discard block
 block discarded – undo
4864 4864
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4865 4865
     {
4866 4866
         $fieldSettings = $this->field_settings($include_db_only_fields);
4867
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4867
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4868 4868
             throw new EE_Error(sprintf(
4869 4869
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4870 4870
                 $fieldName,
4871 4871
                 get_class($this)
4872 4872
             ));
4873 4873
         }
4874
-        return $fieldSettings[ $fieldName ];
4874
+        return $fieldSettings[$fieldName];
4875 4875
     }
4876 4876
 
4877 4877
 
@@ -4885,7 +4885,7 @@  discard block
 block discarded – undo
4885 4885
     public function has_field($fieldName)
4886 4886
     {
4887 4887
         $fieldSettings = $this->field_settings(true);
4888
-        if (isset($fieldSettings[ $fieldName ])) {
4888
+        if (isset($fieldSettings[$fieldName])) {
4889 4889
             return true;
4890 4890
         }
4891 4891
         return false;
@@ -4902,7 +4902,7 @@  discard block
 block discarded – undo
4902 4902
     public function has_relation($relation_name)
4903 4903
     {
4904 4904
         $relations = $this->relation_settings();
4905
-        if (isset($relations[ $relation_name ])) {
4905
+        if (isset($relations[$relation_name])) {
4906 4906
             return true;
4907 4907
         }
4908 4908
         return false;
@@ -4940,7 +4940,7 @@  discard block
 block discarded – undo
4940 4940
                     break;
4941 4941
                 }
4942 4942
             }
4943
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4943
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4944 4944
                 throw new EE_Error(sprintf(
4945 4945
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4946 4946
                     get_class($this)
@@ -5001,23 +5001,23 @@  discard block
 block discarded – undo
5001 5001
      */
5002 5002
     public function get_foreign_key_to($model_name)
5003 5003
     {
5004
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5004
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5005 5005
             foreach ($this->field_settings() as $field) {
5006 5006
                 if ($field instanceof EE_Foreign_Key_Field_Base
5007 5007
                     && in_array($model_name, $field->get_model_names_pointed_to())
5008 5008
                 ) {
5009
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5009
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5010 5010
                     break;
5011 5011
                 }
5012 5012
             }
5013
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5013
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5014 5014
                 throw new EE_Error(sprintf(__(
5015 5015
                     "There is no foreign key field pointing to model %s on model %s",
5016 5016
                     'event_espresso'
5017 5017
                 ), $model_name, get_class($this)));
5018 5018
             }
5019 5019
         }
5020
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5020
+        return $this->_cache_foreign_key_to_fields[$model_name];
5021 5021
     }
5022 5022
 
5023 5023
 
@@ -5033,7 +5033,7 @@  discard block
 block discarded – undo
5033 5033
     public function get_table_for_alias($table_alias)
5034 5034
     {
5035 5035
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5036
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5036
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5037 5037
     }
5038 5038
 
5039 5039
 
@@ -5052,7 +5052,7 @@  discard block
 block discarded – undo
5052 5052
                 $this->_cached_fields = array();
5053 5053
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5054 5054
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5055
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5055
+                        $this->_cached_fields[$field_name] = $field_obj;
5056 5056
                     }
5057 5057
                 }
5058 5058
             }
@@ -5063,8 +5063,8 @@  discard block
 block discarded – undo
5063 5063
             foreach ($this->_fields as $fields_corresponding_to_table) {
5064 5064
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5065 5065
                     /** @var $field_obj EE_Model_Field_Base */
5066
-                    if (! $field_obj->is_db_only_field()) {
5067
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5066
+                    if ( ! $field_obj->is_db_only_field()) {
5067
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5068 5068
                     }
5069 5069
                 }
5070 5070
             }
@@ -5105,12 +5105,12 @@  discard block
 block discarded – undo
5105 5105
                     $primary_key_field->get_qualified_column(),
5106 5106
                     $primary_key_field->get_table_column()
5107 5107
                 );
5108
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5108
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5109 5109
                     continue;
5110 5110
                 }
5111 5111
             }
5112 5112
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5113
-            if (! $classInstance) {
5113
+            if ( ! $classInstance) {
5114 5114
                 throw new EE_Error(
5115 5115
                     sprintf(
5116 5116
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5123,7 +5123,7 @@  discard block
 block discarded – undo
5123 5123
             $classInstance->set_timezone($this->_timezone);
5124 5124
             // make sure if there is any timezone setting present that we set the timezone for the object
5125 5125
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5126
-            $array_of_objects[ $key ] = $classInstance;
5126
+            $array_of_objects[$key] = $classInstance;
5127 5127
             // also, for all the relations of type BelongsTo, see if we can cache
5128 5128
             // those related models
5129 5129
             // (we could do this for other relations too, but if there are conditions
@@ -5167,9 +5167,9 @@  discard block
 block discarded – undo
5167 5167
         $results = array();
5168 5168
         if ($this->_custom_selections instanceof CustomSelects) {
5169 5169
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5170
-                if (isset($db_results_row[ $alias ])) {
5171
-                    $results[ $alias ] = $this->convertValueToDataType(
5172
-                        $db_results_row[ $alias ],
5170
+                if (isset($db_results_row[$alias])) {
5171
+                    $results[$alias] = $this->convertValueToDataType(
5172
+                        $db_results_row[$alias],
5173 5173
                         $this->_custom_selections->getDataTypeForAlias($alias)
5174 5174
                     );
5175 5175
                 }
@@ -5211,7 +5211,7 @@  discard block
 block discarded – undo
5211 5211
         $this_model_fields_and_values = array();
5212 5212
         // setup the row using default values;
5213 5213
         foreach ($this->field_settings() as $field_name => $field_obj) {
5214
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5214
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5215 5215
         }
5216 5216
         $className = $this->_get_class_name();
5217 5217
         $classInstance = EE_Registry::instance()
@@ -5229,20 +5229,20 @@  discard block
 block discarded – undo
5229 5229
      */
5230 5230
     public function instantiate_class_from_array_or_object($cols_n_values)
5231 5231
     {
5232
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5232
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5233 5233
             $cols_n_values = get_object_vars($cols_n_values);
5234 5234
         }
5235 5235
         $primary_key = null;
5236 5236
         // make sure the array only has keys that are fields/columns on this model
5237 5237
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5238
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5239
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5238
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5239
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5240 5240
         }
5241 5241
         $className = $this->_get_class_name();
5242 5242
         // check we actually found results that we can use to build our model object
5243 5243
         // if not, return null
5244 5244
         if ($this->has_primary_key_field()) {
5245
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5245
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5246 5246
                 return null;
5247 5247
             }
5248 5248
         } elseif ($this->unique_indexes()) {
@@ -5254,7 +5254,7 @@  discard block
 block discarded – undo
5254 5254
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5255 5255
         if ($primary_key) {
5256 5256
             $classInstance = $this->get_from_entity_map($primary_key);
5257
-            if (! $classInstance) {
5257
+            if ( ! $classInstance) {
5258 5258
                 $classInstance = EE_Registry::instance()
5259 5259
                                             ->load_class(
5260 5260
                                                 $className,
@@ -5287,8 +5287,8 @@  discard block
 block discarded – undo
5287 5287
      */
5288 5288
     public function get_from_entity_map($id)
5289 5289
     {
5290
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5291
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5290
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5291
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5292 5292
     }
5293 5293
 
5294 5294
 
@@ -5311,7 +5311,7 @@  discard block
 block discarded – undo
5311 5311
     public function add_to_entity_map(EE_Base_Class $object)
5312 5312
     {
5313 5313
         $className = $this->_get_class_name();
5314
-        if (! $object instanceof $className) {
5314
+        if ( ! $object instanceof $className) {
5315 5315
             throw new EE_Error(sprintf(
5316 5316
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5317 5317
                 is_object($object) ? get_class($object) : $object,
@@ -5319,7 +5319,7 @@  discard block
 block discarded – undo
5319 5319
             ));
5320 5320
         }
5321 5321
         /** @var $object EE_Base_Class */
5322
-        if (! $object->ID()) {
5322
+        if ( ! $object->ID()) {
5323 5323
             throw new EE_Error(sprintf(__(
5324 5324
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5325 5325
                 "event_espresso"
@@ -5330,7 +5330,7 @@  discard block
 block discarded – undo
5330 5330
         if ($classInstance) {
5331 5331
             return $classInstance;
5332 5332
         }
5333
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5333
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5334 5334
         return $object;
5335 5335
     }
5336 5336
 
@@ -5346,11 +5346,11 @@  discard block
 block discarded – undo
5346 5346
     public function clear_entity_map($id = null)
5347 5347
     {
5348 5348
         if (empty($id)) {
5349
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5349
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5350 5350
             return true;
5351 5351
         }
5352
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5353
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5352
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5353
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5354 5354
             return true;
5355 5355
         }
5356 5356
         return false;
@@ -5393,17 +5393,17 @@  discard block
 block discarded – undo
5393 5393
             // there is a primary key on this table and its not set. Use defaults for all its columns
5394 5394
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5395 5395
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5396
-                    if (! $field_obj->is_db_only_field()) {
5396
+                    if ( ! $field_obj->is_db_only_field()) {
5397 5397
                         // prepare field as if its coming from db
5398 5398
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5399
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5399
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5400 5400
                     }
5401 5401
                 }
5402 5402
             } else {
5403 5403
                 // the table's rows existed. Use their values
5404 5404
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5405
-                    if (! $field_obj->is_db_only_field()) {
5406
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5405
+                    if ( ! $field_obj->is_db_only_field()) {
5406
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5407 5407
                             $cols_n_values,
5408 5408
                             $field_obj->get_qualified_column(),
5409 5409
                             $field_obj->get_table_column()
@@ -5430,17 +5430,17 @@  discard block
 block discarded – undo
5430 5430
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5431 5431
         // does the field on the model relate to this column retrieved from the db?
5432 5432
         // or is it a db-only field? (not relating to the model)
5433
-        if (isset($cols_n_values[ $qualified_column ])) {
5434
-            $value = $cols_n_values[ $qualified_column ];
5435
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5436
-            $value = $cols_n_values[ $regular_column ];
5437
-        } elseif (! empty($this->foreign_key_aliases)) {
5433
+        if (isset($cols_n_values[$qualified_column])) {
5434
+            $value = $cols_n_values[$qualified_column];
5435
+        } elseif (isset($cols_n_values[$regular_column])) {
5436
+            $value = $cols_n_values[$regular_column];
5437
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5438 5438
             // no PK?  ok check if there is a foreign key alias set for this table
5439 5439
             // then check if that alias exists in the incoming data
5440 5440
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5441 5441
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5442
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5443
-                    $value = $cols_n_values[ $FK_alias ];
5442
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5443
+                    $value = $cols_n_values[$FK_alias];
5444 5444
                     list($pk_class) = explode('.', $PK_column);
5445 5445
                     $pk_model_name = "EEM_{$pk_class}";
5446 5446
                     /** @var EEM_Base $pk_model */
@@ -5484,7 +5484,7 @@  discard block
 block discarded – undo
5484 5484
                     $obj_in_map->clear_cache($relation_name, null, true);
5485 5485
                 }
5486 5486
             }
5487
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5487
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5488 5488
             return $obj_in_map;
5489 5489
         }
5490 5490
         return $this->get_one_by_ID($id);
@@ -5537,7 +5537,7 @@  discard block
 block discarded – undo
5537 5537
      */
5538 5538
     private function _get_class_name()
5539 5539
     {
5540
-        return "EE_" . $this->get_this_model_name();
5540
+        return "EE_".$this->get_this_model_name();
5541 5541
     }
5542 5542
 
5543 5543
 
@@ -5585,7 +5585,7 @@  discard block
 block discarded – undo
5585 5585
     {
5586 5586
         $className = get_class($this);
5587 5587
         $tagName = "FHEE__{$className}__{$methodName}";
5588
-        if (! has_filter($tagName)) {
5588
+        if ( ! has_filter($tagName)) {
5589 5589
             throw new EE_Error(
5590 5590
                 sprintf(
5591 5591
                     __(
@@ -5756,7 +5756,7 @@  discard block
 block discarded – undo
5756 5756
         $unique_indexes = array();
5757 5757
         foreach ($this->_indexes as $name => $index) {
5758 5758
             if ($index instanceof EE_Unique_Index) {
5759
-                $unique_indexes [ $name ] = $index;
5759
+                $unique_indexes [$name] = $index;
5760 5760
             }
5761 5761
         }
5762 5762
         return $unique_indexes;
@@ -5823,7 +5823,7 @@  discard block
 block discarded – undo
5823 5823
         $key_vals_in_combined_pk = array();
5824 5824
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5825 5825
         foreach ($key_fields as $key_field_name => $field_obj) {
5826
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5826
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5827 5827
                 return null;
5828 5828
             }
5829 5829
         }
@@ -5844,7 +5844,7 @@  discard block
 block discarded – undo
5844 5844
     {
5845 5845
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5846 5846
         foreach ($keys_it_should_have as $key) {
5847
-            if (! isset($key_vals[ $key ])) {
5847
+            if ( ! isset($key_vals[$key])) {
5848 5848
                 return false;
5849 5849
             }
5850 5850
         }
@@ -5877,8 +5877,8 @@  discard block
 block discarded – undo
5877 5877
         }
5878 5878
         // even copies obviously won't have the same ID, so remove the primary key
5879 5879
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5880
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5881
-            unset($attributes_array[ $this->primary_key_name() ]);
5880
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5881
+            unset($attributes_array[$this->primary_key_name()]);
5882 5882
         }
5883 5883
         if (isset($query_params[0])) {
5884 5884
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5900,7 +5900,7 @@  discard block
 block discarded – undo
5900 5900
      */
5901 5901
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5902 5902
     {
5903
-        if (! is_array($query_params)) {
5903
+        if ( ! is_array($query_params)) {
5904 5904
             EE_Error::doing_it_wrong(
5905 5905
                 'EEM_Base::get_one_copy',
5906 5906
                 sprintf(
@@ -5950,7 +5950,7 @@  discard block
 block discarded – undo
5950 5950
      */
5951 5951
     private function _prepare_operator_for_sql($operator_supplied)
5952 5952
     {
5953
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5953
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5954 5954
             : null;
5955 5955
         if ($sql_operator) {
5956 5956
             return $sql_operator;
@@ -6041,7 +6041,7 @@  discard block
 block discarded – undo
6041 6041
         $objs = $this->get_all($query_params);
6042 6042
         $names = array();
6043 6043
         foreach ($objs as $obj) {
6044
-            $names[ $obj->ID() ] = $obj->name();
6044
+            $names[$obj->ID()] = $obj->name();
6045 6045
         }
6046 6046
         return $names;
6047 6047
     }
@@ -6062,7 +6062,7 @@  discard block
 block discarded – undo
6062 6062
      */
6063 6063
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6064 6064
     {
6065
-        if (! $this->has_primary_key_field()) {
6065
+        if ( ! $this->has_primary_key_field()) {
6066 6066
             if (WP_DEBUG) {
6067 6067
                 EE_Error::add_error(
6068 6068
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6075,7 +6075,7 @@  discard block
 block discarded – undo
6075 6075
         $IDs = array();
6076 6076
         foreach ($model_objects as $model_object) {
6077 6077
             $id = $model_object->ID();
6078
-            if (! $id) {
6078
+            if ( ! $id) {
6079 6079
                 if ($filter_out_empty_ids) {
6080 6080
                     continue;
6081 6081
                 }
@@ -6125,22 +6125,22 @@  discard block
 block discarded – undo
6125 6125
     {
6126 6126
         EEM_Base::verify_is_valid_cap_context($context);
6127 6127
         // check if we ought to run the restriction generator first
6128
-        if (isset($this->_cap_restriction_generators[ $context ])
6129
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6130
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6128
+        if (isset($this->_cap_restriction_generators[$context])
6129
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6130
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6131 6131
         ) {
6132
-            $this->_cap_restrictions[ $context ] = array_merge(
6133
-                $this->_cap_restrictions[ $context ],
6134
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6132
+            $this->_cap_restrictions[$context] = array_merge(
6133
+                $this->_cap_restrictions[$context],
6134
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6135 6135
             );
6136 6136
         }
6137 6137
         // and make sure we've finalized the construction of each restriction
6138
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6138
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6139 6139
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6140 6140
                 $where_conditions_obj->_finalize_construct($this);
6141 6141
             }
6142 6142
         }
6143
-        return $this->_cap_restrictions[ $context ];
6143
+        return $this->_cap_restrictions[$context];
6144 6144
     }
6145 6145
 
6146 6146
 
@@ -6170,10 +6170,10 @@  discard block
 block discarded – undo
6170 6170
         $missing_caps = array();
6171 6171
         $cap_restrictions = $this->cap_restrictions($context);
6172 6172
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6173
-            if (! EE_Capabilities::instance()
6174
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6173
+            if ( ! EE_Capabilities::instance()
6174
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6175 6175
             ) {
6176
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6176
+                $missing_caps[$cap] = $restriction_if_no_cap;
6177 6177
             }
6178 6178
         }
6179 6179
         return $missing_caps;
@@ -6208,8 +6208,8 @@  discard block
 block discarded – undo
6208 6208
     public function cap_action_for_context($context)
6209 6209
     {
6210 6210
         $mapping = $this->cap_contexts_to_cap_action_map();
6211
-        if (isset($mapping[ $context ])) {
6212
-            return $mapping[ $context ];
6211
+        if (isset($mapping[$context])) {
6212
+            return $mapping[$context];
6213 6213
         }
6214 6214
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6215 6215
             return $action;
@@ -6326,7 +6326,7 @@  discard block
 block discarded – undo
6326 6326
     {
6327 6327
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6328 6328
             if ($query_param_key === $logic_query_param_key
6329
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6329
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6330 6330
             ) {
6331 6331
                 return true;
6332 6332
             }
@@ -6379,7 +6379,7 @@  discard block
 block discarded – undo
6379 6379
         if ($password_field instanceof EE_Password_Field) {
6380 6380
             $field_names = $password_field->protectedFields();
6381 6381
             foreach ($field_names as $field_name) {
6382
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6382
+                $fields[$field_name] = $this->field_settings_for($field_name);
6383 6383
             }
6384 6384
         }
6385 6385
         return $fields;
@@ -6404,7 +6404,7 @@  discard block
 block discarded – undo
6404 6404
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6405 6405
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6406 6406
         }
6407
-        if (!is_array($model_obj_or_fields_n_values)) {
6407
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6408 6408
             throw new UnexpectedEntityException(
6409 6409
                 $model_obj_or_fields_n_values,
6410 6410
                 'EE_Base_Class',
@@ -6479,7 +6479,7 @@  discard block
 block discarded – undo
6479 6479
                 )
6480 6480
             );
6481 6481
         }
6482
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6482
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6483 6483
     }
6484 6484
 
6485 6485
     /**
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 1 patch
Indentation   +2105 added lines, -2105 removed lines patch added patch discarded remove patch
@@ -17,2109 +17,2109 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws DomainException
146
-     * @throws EE_Error
147
-     * @throws EntityNotFoundException
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     * @throws RuntimeException
153
-     * @throws UnexpectedEntityException
154
-     */
155
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
-    {
157
-        // get current REG_Status
158
-        $old_STS_ID = $this->status_ID();
159
-        // if status has changed
160
-        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
161
-            && ! empty($old_STS_ID) // and that old status is actually set
162
-            && ! empty($new_STS_ID) // as well as the new status
163
-            && $this->ID() // ensure registration is in the db
164
-        ) {
165
-            // update internal status first
166
-            parent::set('STS_ID', $new_STS_ID, $use_default);
167
-            // THEN handle other changes that occur when reg status changes
168
-            // TO approved
169
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
170
-                // reserve a space by incrementing ticket and datetime sold values
171
-                $this->reserveRegistrationSpace();
172
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
173
-                // OR FROM  approved
174
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
175
-                // release a space by decrementing ticket and datetime sold values
176
-                $this->releaseRegistrationSpace();
177
-                do_action(
178
-                    'AHEE__EE_Registration__set_status__from_approved',
179
-                    $this,
180
-                    $old_STS_ID,
181
-                    $new_STS_ID,
182
-                    $context
183
-                );
184
-            }
185
-            // update status
186
-            parent::set('STS_ID', $new_STS_ID, $use_default);
187
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
188
-            if ($this->statusChangeUpdatesTransaction($context)) {
189
-                $this->updateTransactionAfterStatusChange();
190
-            }
191
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
192
-            return true;
193
-        }
194
-        // even though the old value matches the new value, it's still good to
195
-        // allow the parent set method to have a say
196
-        parent::set('STS_ID', $new_STS_ID, $use_default);
197
-        return true;
198
-    }
199
-
200
-
201
-    /**
202
-     * update REGs and TXN when cancelled or declined registrations involved
203
-     *
204
-     * @param string                $new_STS_ID
205
-     * @param string                $old_STS_ID
206
-     * @param ContextInterface|null $context
207
-     * @throws EE_Error
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     * @throws ReflectionException
212
-     * @throws RuntimeException
213
-     */
214
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
215
-    {
216
-        // these reg statuses should not be considered in any calculations involving monies owing
217
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
218
-        // true if registration has been cancelled or declined
219
-        $this->updateIfCanceled(
220
-            $closed_reg_statuses,
221
-            $new_STS_ID,
222
-            $old_STS_ID,
223
-            $context
224
-        );
225
-        $this->updateIfReinstated(
226
-            $closed_reg_statuses,
227
-            $new_STS_ID,
228
-            $old_STS_ID,
229
-            $context
230
-        );
231
-    }
232
-
233
-
234
-    /**
235
-     * update REGs and TXN when cancelled or declined registrations involved
236
-     *
237
-     * @param array                 $closed_reg_statuses
238
-     * @param string                $new_STS_ID
239
-     * @param string                $old_STS_ID
240
-     * @param ContextInterface|null $context
241
-     * @throws EE_Error
242
-     * @throws InvalidArgumentException
243
-     * @throws InvalidDataTypeException
244
-     * @throws InvalidInterfaceException
245
-     * @throws ReflectionException
246
-     * @throws RuntimeException
247
-     */
248
-    private function updateIfCanceled(
249
-        array $closed_reg_statuses,
250
-        $new_STS_ID,
251
-        $old_STS_ID,
252
-        ContextInterface $context = null
253
-    ) {
254
-        // true if registration has been cancelled or declined
255
-        if (in_array($new_STS_ID, $closed_reg_statuses, true)
256
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
257
-        ) {
258
-            /** @type EE_Registration_Processor $registration_processor */
259
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
260
-            /** @type EE_Transaction_Processor $transaction_processor */
261
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
262
-            // cancelled or declined registration
263
-            $registration_processor->update_registration_after_being_canceled_or_declined(
264
-                $this,
265
-                $closed_reg_statuses
266
-            );
267
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
268
-                $this,
269
-                $closed_reg_statuses,
270
-                false
271
-            );
272
-            do_action(
273
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
274
-                $this,
275
-                $old_STS_ID,
276
-                $new_STS_ID,
277
-                $context
278
-            );
279
-            return;
280
-        }
281
-    }
282
-
283
-
284
-    /**
285
-     * update REGs and TXN when cancelled or declined registrations involved
286
-     *
287
-     * @param array                 $closed_reg_statuses
288
-     * @param string                $new_STS_ID
289
-     * @param string                $old_STS_ID
290
-     * @param ContextInterface|null $context
291
-     * @throws EE_Error
292
-     * @throws InvalidArgumentException
293
-     * @throws InvalidDataTypeException
294
-     * @throws InvalidInterfaceException
295
-     * @throws ReflectionException
296
-     */
297
-    private function updateIfReinstated(
298
-        array $closed_reg_statuses,
299
-        $new_STS_ID,
300
-        $old_STS_ID,
301
-        ContextInterface $context = null
302
-    ) {
303
-        // true if reinstating cancelled or declined registration
304
-        if (in_array($old_STS_ID, $closed_reg_statuses, true)
305
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
306
-        ) {
307
-            /** @type EE_Registration_Processor $registration_processor */
308
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
309
-            /** @type EE_Transaction_Processor $transaction_processor */
310
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
311
-            // reinstating cancelled or declined registration
312
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
313
-                $this,
314
-                $closed_reg_statuses
315
-            );
316
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
317
-                $this,
318
-                $closed_reg_statuses,
319
-                false
320
-            );
321
-            do_action(
322
-                'AHEE__EE_Registration__set_status__after_reinstated',
323
-                $this,
324
-                $old_STS_ID,
325
-                $new_STS_ID,
326
-                $context
327
-            );
328
-        }
329
-    }
330
-
331
-
332
-    /**
333
-     * @param ContextInterface|null $context
334
-     * @return bool
335
-     */
336
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
337
-    {
338
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
339
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
340
-            array('spco_reg_step_attendee_information_process_registrations'),
341
-            $context,
342
-            $this
343
-        );
344
-        return ! (
345
-            $context instanceof ContextInterface
346
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
347
-        );
348
-    }
349
-
350
-
351
-    /**
352
-     * @throws EE_Error
353
-     * @throws EntityNotFoundException
354
-     * @throws InvalidArgumentException
355
-     * @throws InvalidDataTypeException
356
-     * @throws InvalidInterfaceException
357
-     * @throws ReflectionException
358
-     * @throws RuntimeException
359
-     */
360
-    private function updateTransactionAfterStatusChange()
361
-    {
362
-        /** @type EE_Transaction_Payments $transaction_payments */
363
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
364
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
365
-        $this->transaction()->update_status_based_on_total_paid(true);
366
-    }
367
-
368
-
369
-    /**
370
-     *        get Status ID
371
-     */
372
-    public function status_ID()
373
-    {
374
-        return $this->get('STS_ID');
375
-    }
376
-
377
-
378
-    /**
379
-     * Gets the ticket this registration is for
380
-     *
381
-     * @param boolean $include_archived whether to include archived tickets or not.
382
-     *
383
-     * @return EE_Ticket|EE_Base_Class
384
-     * @throws EE_Error
385
-     */
386
-    public function ticket($include_archived = true)
387
-    {
388
-        $query_params = array();
389
-        if ($include_archived) {
390
-            $query_params['default_where_conditions'] = 'none';
391
-        }
392
-        return $this->get_first_related('Ticket', $query_params);
393
-    }
394
-
395
-
396
-    /**
397
-     * Gets the event this registration is for
398
-     *
399
-     * @return EE_Event
400
-     * @throws EE_Error
401
-     * @throws EntityNotFoundException
402
-     */
403
-    public function event()
404
-    {
405
-        $event = $this->get_first_related('Event');
406
-        if (! $event instanceof \EE_Event) {
407
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
408
-        }
409
-        return $event;
410
-    }
411
-
412
-
413
-    /**
414
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
415
-     * with the author of the event this registration is for.
416
-     *
417
-     * @since 4.5.0
418
-     * @return int
419
-     * @throws EE_Error
420
-     * @throws EntityNotFoundException
421
-     */
422
-    public function wp_user()
423
-    {
424
-        $event = $this->event();
425
-        if ($event instanceof EE_Event) {
426
-            return $event->wp_user();
427
-        }
428
-        return 0;
429
-    }
430
-
431
-
432
-    /**
433
-     * increments this registration's related ticket sold and corresponding datetime sold values
434
-     *
435
-     * @return void
436
-     * @throws DomainException
437
-     * @throws EE_Error
438
-     * @throws EntityNotFoundException
439
-     * @throws InvalidArgumentException
440
-     * @throws InvalidDataTypeException
441
-     * @throws InvalidInterfaceException
442
-     * @throws ReflectionException
443
-     * @throws UnexpectedEntityException
444
-     */
445
-    private function reserveRegistrationSpace()
446
-    {
447
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
448
-        // so stop tracking that this reg has a ticket reserved
449
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
450
-        $ticket = $this->ticket();
451
-        $ticket->increaseSold();
452
-        // possibly set event status to sold out
453
-        $this->event()->perform_sold_out_status_check();
454
-    }
455
-
456
-
457
-    /**
458
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
459
-     *
460
-     * @return void
461
-     * @throws DomainException
462
-     * @throws EE_Error
463
-     * @throws EntityNotFoundException
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     * @throws ReflectionException
468
-     * @throws UnexpectedEntityException
469
-     */
470
-    private function releaseRegistrationSpace()
471
-    {
472
-        $ticket = $this->ticket();
473
-        $ticket->decreaseSold();
474
-        // possibly change event status from sold out back to previous status
475
-        $this->event()->perform_sold_out_status_check();
476
-    }
477
-
478
-
479
-    /**
480
-     * tracks this registration's ticket reservation in extra meta
481
-     * and can increment related ticket reserved and corresponding datetime reserved values
482
-     *
483
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
484
-     * @return void
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     * @throws ReflectionException
490
-     */
491
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
492
-    {
493
-        // only reserve ticket if space is not currently reserved
494
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
495
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
496
-            // IMPORTANT !!!
497
-            // although checking $update_ticket first would be more efficient,
498
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
499
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
500
-                && $update_ticket
501
-            ) {
502
-                $ticket = $this->ticket();
503
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
504
-                $ticket->save();
505
-            }
506
-        }
507
-    }
508
-
509
-
510
-    /**
511
-     * stops tracking this registration's ticket reservation in extra meta
512
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
513
-     *
514
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
515
-     * @return void
516
-     * @throws EE_Error
517
-     * @throws InvalidArgumentException
518
-     * @throws InvalidDataTypeException
519
-     * @throws InvalidInterfaceException
520
-     * @throws ReflectionException
521
-     */
522
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
523
-    {
524
-        // only release ticket if space is currently reserved
525
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
526
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
527
-            // IMPORTANT !!!
528
-            // although checking $update_ticket first would be more efficient,
529
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
530
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
531
-                && $update_ticket
532
-            ) {
533
-                $ticket = $this->ticket();
534
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
535
-            }
536
-        }
537
-    }
538
-
539
-
540
-    /**
541
-     * Set Attendee ID
542
-     *
543
-     * @param        int $ATT_ID Attendee ID
544
-     * @throws EE_Error
545
-     * @throws RuntimeException
546
-     */
547
-    public function set_attendee_id($ATT_ID = 0)
548
-    {
549
-        $this->set('ATT_ID', $ATT_ID);
550
-    }
551
-
552
-
553
-    /**
554
-     *        Set Transaction ID
555
-     *
556
-     * @param        int $TXN_ID Transaction ID
557
-     * @throws EE_Error
558
-     * @throws RuntimeException
559
-     */
560
-    public function set_transaction_id($TXN_ID = 0)
561
-    {
562
-        $this->set('TXN_ID', $TXN_ID);
563
-    }
564
-
565
-
566
-    /**
567
-     *        Set Session
568
-     *
569
-     * @param    string $REG_session PHP Session ID
570
-     * @throws EE_Error
571
-     * @throws RuntimeException
572
-     */
573
-    public function set_session($REG_session = '')
574
-    {
575
-        $this->set('REG_session', $REG_session);
576
-    }
577
-
578
-
579
-    /**
580
-     *        Set Registration URL Link
581
-     *
582
-     * @param    string $REG_url_link Registration URL Link
583
-     * @throws EE_Error
584
-     * @throws RuntimeException
585
-     */
586
-    public function set_reg_url_link($REG_url_link = '')
587
-    {
588
-        $this->set('REG_url_link', $REG_url_link);
589
-    }
590
-
591
-
592
-    /**
593
-     *        Set Attendee Counter
594
-     *
595
-     * @param        int $REG_count Primary Attendee
596
-     * @throws EE_Error
597
-     * @throws RuntimeException
598
-     */
599
-    public function set_count($REG_count = 1)
600
-    {
601
-        $this->set('REG_count', $REG_count);
602
-    }
603
-
604
-
605
-    /**
606
-     *        Set Group Size
607
-     *
608
-     * @param        boolean $REG_group_size Group Registration
609
-     * @throws EE_Error
610
-     * @throws RuntimeException
611
-     */
612
-    public function set_group_size($REG_group_size = false)
613
-    {
614
-        $this->set('REG_group_size', $REG_group_size);
615
-    }
616
-
617
-
618
-    /**
619
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
620
-     *    EEM_Registration::status_id_not_approved
621
-     *
622
-     * @return        boolean
623
-     */
624
-    public function is_not_approved()
625
-    {
626
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
627
-    }
628
-
629
-
630
-    /**
631
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
632
-     *    EEM_Registration::status_id_pending_payment
633
-     *
634
-     * @return        boolean
635
-     */
636
-    public function is_pending_payment()
637
-    {
638
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
639
-    }
640
-
641
-
642
-    /**
643
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
644
-     *
645
-     * @return        boolean
646
-     */
647
-    public function is_approved()
648
-    {
649
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
650
-    }
651
-
652
-
653
-    /**
654
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
655
-     *
656
-     * @return        boolean
657
-     */
658
-    public function is_cancelled()
659
-    {
660
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
661
-    }
662
-
663
-
664
-    /**
665
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
666
-     *
667
-     * @return        boolean
668
-     */
669
-    public function is_declined()
670
-    {
671
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
672
-    }
673
-
674
-
675
-    /**
676
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
677
-     *    EEM_Registration::status_id_incomplete
678
-     *
679
-     * @return        boolean
680
-     */
681
-    public function is_incomplete()
682
-    {
683
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
684
-    }
685
-
686
-
687
-    /**
688
-     *        Set Registration Date
689
-     *
690
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
691
-     *                                                 Date
692
-     * @throws EE_Error
693
-     * @throws RuntimeException
694
-     */
695
-    public function set_reg_date($REG_date = false)
696
-    {
697
-        $this->set('REG_date', $REG_date);
698
-    }
699
-
700
-
701
-    /**
702
-     *    Set final price owing for this registration after all ticket/price modifications
703
-     *
704
-     * @access    public
705
-     * @param    float $REG_final_price
706
-     * @throws EE_Error
707
-     * @throws RuntimeException
708
-     */
709
-    public function set_final_price($REG_final_price = 0.00)
710
-    {
711
-        $this->set('REG_final_price', $REG_final_price);
712
-    }
713
-
714
-
715
-    /**
716
-     *    Set amount paid towards this registration's final price
717
-     *
718
-     * @access    public
719
-     * @param    float $REG_paid
720
-     * @throws EE_Error
721
-     * @throws RuntimeException
722
-     */
723
-    public function set_paid($REG_paid = 0.00)
724
-    {
725
-        $this->set('REG_paid', $REG_paid);
726
-    }
727
-
728
-
729
-    /**
730
-     *        Attendee Is Going
731
-     *
732
-     * @param        boolean $REG_att_is_going Attendee Is Going
733
-     * @throws EE_Error
734
-     * @throws RuntimeException
735
-     */
736
-    public function set_att_is_going($REG_att_is_going = false)
737
-    {
738
-        $this->set('REG_att_is_going', $REG_att_is_going);
739
-    }
740
-
741
-
742
-    /**
743
-     * Gets the related attendee
744
-     *
745
-     * @return EE_Attendee
746
-     * @throws EE_Error
747
-     */
748
-    public function attendee()
749
-    {
750
-        return $this->get_first_related('Attendee');
751
-    }
752
-
753
-    /**
754
-     * Gets the name of the attendee.
755
-     * @since 4.10.12.p
756
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
757
-     * @return string
758
-     * @throws EE_Error
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     * @throws ReflectionException
763
-     */
764
-    public function attendeeName($apply_html_entities = false)
765
-    {
766
-        $attendee = $this->get_first_related('Attendee');
767
-        if ($attendee instanceof EE_Attendee) {
768
-            $attendee_name = $attendee->full_name($apply_html_entities);
769
-        } else {
770
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
771
-        }
772
-        return $attendee_name;
773
-    }
774
-
775
-
776
-    /**
777
-     *        get Event ID
778
-     */
779
-    public function event_ID()
780
-    {
781
-        return $this->get('EVT_ID');
782
-    }
783
-
784
-
785
-    /**
786
-     *        get Event ID
787
-     */
788
-    public function event_name()
789
-    {
790
-        $event = $this->event_obj();
791
-        if ($event) {
792
-            return $event->name();
793
-        } else {
794
-            return null;
795
-        }
796
-    }
797
-
798
-
799
-    /**
800
-     * Fetches the event this registration is for
801
-     *
802
-     * @return EE_Event
803
-     * @throws EE_Error
804
-     */
805
-    public function event_obj()
806
-    {
807
-        return $this->get_first_related('Event');
808
-    }
809
-
810
-
811
-    /**
812
-     *        get Attendee ID
813
-     */
814
-    public function attendee_ID()
815
-    {
816
-        return $this->get('ATT_ID');
817
-    }
818
-
819
-
820
-    /**
821
-     *        get PHP Session ID
822
-     */
823
-    public function session_ID()
824
-    {
825
-        return $this->get('REG_session');
826
-    }
827
-
828
-
829
-    /**
830
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
831
-     *
832
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
833
-     * @return string
834
-     */
835
-    public function receipt_url($messenger = 'html')
836
-    {
837
-
838
-        /**
839
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
840
-         * already in use on old system.  If there is then we just return the standard url for it.
841
-         *
842
-         * @since 4.5.0
843
-         */
844
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
845
-        $has_custom = EEH_Template::locate_template(
846
-            $template_relative_path,
847
-            array(),
848
-            true,
849
-            true,
850
-            true
851
-        );
852
-
853
-        if ($has_custom) {
854
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
855
-        }
856
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
857
-    }
858
-
859
-
860
-    /**
861
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
862
-     *
863
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
864
-     * @return string
865
-     * @throws EE_Error
866
-     */
867
-    public function invoice_url($messenger = 'html')
868
-    {
869
-        /**
870
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
871
-         * already in use on old system.  If there is then we just return the standard url for it.
872
-         *
873
-         * @since 4.5.0
874
-         */
875
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
876
-        $has_custom = EEH_Template::locate_template(
877
-            $template_relative_path,
878
-            array(),
879
-            true,
880
-            true,
881
-            true
882
-        );
883
-
884
-        if ($has_custom) {
885
-            if ($messenger == 'html') {
886
-                return $this->invoice_url('launch');
887
-            }
888
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
889
-
890
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
891
-            if ($messenger == 'html') {
892
-                $query_args['html'] = true;
893
-            }
894
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
895
-        }
896
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
897
-    }
898
-
899
-
900
-    /**
901
-     * get Registration URL Link
902
-     *
903
-     * @access public
904
-     * @return string
905
-     * @throws EE_Error
906
-     */
907
-    public function reg_url_link()
908
-    {
909
-        return (string) $this->get('REG_url_link');
910
-    }
911
-
912
-
913
-    /**
914
-     * Echoes out invoice_url()
915
-     *
916
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
917
-     * @return void
918
-     * @throws EE_Error
919
-     */
920
-    public function e_invoice_url($type = 'launch')
921
-    {
922
-        echo $this->invoice_url($type);
923
-    }
924
-
925
-
926
-    /**
927
-     * Echoes out payment_overview_url
928
-     */
929
-    public function e_payment_overview_url()
930
-    {
931
-        echo $this->payment_overview_url();
932
-    }
933
-
934
-
935
-    /**
936
-     * Gets the URL for the checkout payment options reg step
937
-     * with this registration's REG_url_link added as a query parameter
938
-     *
939
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
940
-     *                            payment overview url.
941
-     * @return string
942
-     * @throws InvalidInterfaceException
943
-     * @throws InvalidDataTypeException
944
-     * @throws EE_Error
945
-     * @throws InvalidArgumentException
946
-     */
947
-    public function payment_overview_url($clear_session = false)
948
-    {
949
-        return add_query_arg(
950
-            (array) apply_filters(
951
-                'FHEE__EE_Registration__payment_overview_url__query_args',
952
-                array(
953
-                    'e_reg_url_link' => $this->reg_url_link(),
954
-                    'step'           => 'payment_options',
955
-                    'revisit'        => true,
956
-                    'clear_session'  => (bool) $clear_session,
957
-                ),
958
-                $this
959
-            ),
960
-            EE_Registry::instance()->CFG->core->reg_page_url()
961
-        );
962
-    }
963
-
964
-
965
-    /**
966
-     * Gets the URL for the checkout attendee information reg step
967
-     * with this registration's REG_url_link added as a query parameter
968
-     *
969
-     * @return string
970
-     * @throws InvalidInterfaceException
971
-     * @throws InvalidDataTypeException
972
-     * @throws EE_Error
973
-     * @throws InvalidArgumentException
974
-     */
975
-    public function edit_attendee_information_url()
976
-    {
977
-        return add_query_arg(
978
-            (array) apply_filters(
979
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
980
-                array(
981
-                    'e_reg_url_link' => $this->reg_url_link(),
982
-                    'step'           => 'attendee_information',
983
-                    'revisit'        => true,
984
-                ),
985
-                $this
986
-            ),
987
-            EE_Registry::instance()->CFG->core->reg_page_url()
988
-        );
989
-    }
990
-
991
-
992
-    /**
993
-     * Simply generates and returns the appropriate admin_url link to edit this registration
994
-     *
995
-     * @return string
996
-     * @throws EE_Error
997
-     */
998
-    public function get_admin_edit_url()
999
-    {
1000
-        return EEH_URL::add_query_args_and_nonce(
1001
-            array(
1002
-                'page'    => 'espresso_registrations',
1003
-                'action'  => 'view_registration',
1004
-                '_REG_ID' => $this->ID(),
1005
-            ),
1006
-            admin_url('admin.php')
1007
-        );
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     *    is_primary_registrant?
1013
-     */
1014
-    public function is_primary_registrant()
1015
-    {
1016
-        return $this->get('REG_count') === 1 ? true : false;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * This returns the primary registration object for this registration group (which may be this object).
1022
-     *
1023
-     * @return EE_Registration
1024
-     * @throws EE_Error
1025
-     */
1026
-    public function get_primary_registration()
1027
-    {
1028
-        if ($this->is_primary_registrant()) {
1029
-            return $this;
1030
-        }
1031
-
1032
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1033
-        /** @var EE_Registration $primary_registrant */
1034
-        $primary_registrant = EEM_Registration::instance()->get_one(
1035
-            array(
1036
-                array(
1037
-                    'TXN_ID'    => $this->transaction_ID(),
1038
-                    'REG_count' => 1,
1039
-                ),
1040
-            )
1041
-        );
1042
-        return $primary_registrant;
1043
-    }
1044
-
1045
-
1046
-    /**
1047
-     *        get  Attendee Number
1048
-     *
1049
-     * @access        public
1050
-     */
1051
-    public function count()
1052
-    {
1053
-        return $this->get('REG_count');
1054
-    }
1055
-
1056
-
1057
-    /**
1058
-     *        get Group Size
1059
-     */
1060
-    public function group_size()
1061
-    {
1062
-        return $this->get('REG_group_size');
1063
-    }
1064
-
1065
-
1066
-    /**
1067
-     *        get Registration Date
1068
-     */
1069
-    public function date()
1070
-    {
1071
-        return $this->get('REG_date');
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * gets a pretty date
1077
-     *
1078
-     * @param string $date_format
1079
-     * @param string $time_format
1080
-     * @return string
1081
-     * @throws EE_Error
1082
-     */
1083
-    public function pretty_date($date_format = null, $time_format = null)
1084
-    {
1085
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     * final_price
1091
-     * the registration's share of the transaction total, so that the
1092
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1093
-     *
1094
-     * @return float
1095
-     * @throws EE_Error
1096
-     */
1097
-    public function final_price()
1098
-    {
1099
-        return $this->get('REG_final_price');
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     * pretty_final_price
1105
-     *  final price as formatted string, with correct decimal places and currency symbol
1106
-     *
1107
-     * @return string
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function pretty_final_price()
1111
-    {
1112
-        return $this->get_pretty('REG_final_price');
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * get paid (yeah)
1118
-     *
1119
-     * @return float
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function paid()
1123
-    {
1124
-        return $this->get('REG_paid');
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * pretty_paid
1130
-     *
1131
-     * @return float
1132
-     * @throws EE_Error
1133
-     */
1134
-    public function pretty_paid()
1135
-    {
1136
-        return $this->get_pretty('REG_paid');
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * owes_monies_and_can_pay
1142
-     * whether or not this registration has monies owing and it's' status allows payment
1143
-     *
1144
-     * @param array $requires_payment
1145
-     * @return bool
1146
-     * @throws EE_Error
1147
-     */
1148
-    public function owes_monies_and_can_pay($requires_payment = array())
1149
-    {
1150
-        // these reg statuses require payment (if event is not free)
1151
-        $requires_payment = ! empty($requires_payment)
1152
-            ? $requires_payment
1153
-            : EEM_Registration::reg_statuses_that_allow_payment();
1154
-        if (in_array($this->status_ID(), $requires_payment) &&
1155
-            $this->final_price() != 0 &&
1156
-            $this->final_price() != $this->paid()
1157
-        ) {
1158
-            return true;
1159
-        } else {
1160
-            return false;
1161
-        }
1162
-    }
1163
-
1164
-
1165
-    /**
1166
-     * Prints out the return value of $this->pretty_status()
1167
-     *
1168
-     * @param bool $show_icons
1169
-     * @return void
1170
-     * @throws EE_Error
1171
-     */
1172
-    public function e_pretty_status($show_icons = false)
1173
-    {
1174
-        echo $this->pretty_status($show_icons);
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * Returns a nice version of the status for displaying to customers
1180
-     *
1181
-     * @param bool $show_icons
1182
-     * @return string
1183
-     * @throws EE_Error
1184
-     */
1185
-    public function pretty_status($show_icons = false)
1186
-    {
1187
-        $status = EEM_Status::instance()->localized_status(
1188
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1189
-            false,
1190
-            'sentence'
1191
-        );
1192
-        $icon = '';
1193
-        switch ($this->status_ID()) {
1194
-            case EEM_Registration::status_id_approved:
1195
-                $icon = $show_icons
1196
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1197
-                    : '';
1198
-                break;
1199
-            case EEM_Registration::status_id_pending_payment:
1200
-                $icon = $show_icons
1201
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1202
-                    : '';
1203
-                break;
1204
-            case EEM_Registration::status_id_not_approved:
1205
-                $icon = $show_icons
1206
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1207
-                    : '';
1208
-                break;
1209
-            case EEM_Registration::status_id_cancelled:
1210
-                $icon = $show_icons
1211
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1212
-                    : '';
1213
-                break;
1214
-            case EEM_Registration::status_id_incomplete:
1215
-                $icon = $show_icons
1216
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1217
-                    : '';
1218
-                break;
1219
-            case EEM_Registration::status_id_declined:
1220
-                $icon = $show_icons
1221
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1222
-                    : '';
1223
-                break;
1224
-            case EEM_Registration::status_id_wait_list:
1225
-                $icon = $show_icons
1226
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1227
-                    : '';
1228
-                break;
1229
-        }
1230
-        return $icon . $status[ $this->status_ID() ];
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     *        get Attendee Is Going
1236
-     */
1237
-    public function att_is_going()
1238
-    {
1239
-        return $this->get('REG_att_is_going');
1240
-    }
1241
-
1242
-
1243
-    /**
1244
-     * Gets related answers
1245
-     *
1246
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1247
-     * @return EE_Answer[]
1248
-     * @throws EE_Error
1249
-     */
1250
-    public function answers($query_params = null)
1251
-    {
1252
-        return $this->get_many_related('Answer', $query_params);
1253
-    }
1254
-
1255
-
1256
-    /**
1257
-     * Gets the registration's answer value to the specified question
1258
-     * (either the question's ID or a question object)
1259
-     *
1260
-     * @param EE_Question|int $question
1261
-     * @param bool            $pretty_value
1262
-     * @return array|string if pretty_value= true, the result will always be a string
1263
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1264
-     * will convert it into some kind of string)
1265
-     * @throws EE_Error
1266
-     */
1267
-    public function answer_value_to_question($question, $pretty_value = true)
1268
-    {
1269
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1270
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1271
-    }
1272
-
1273
-
1274
-    /**
1275
-     * question_groups
1276
-     * returns an array of EE_Question_Group objects for this registration
1277
-     *
1278
-     * @return EE_Question_Group[]
1279
-     * @throws EE_Error
1280
-     * @throws InvalidArgumentException
1281
-     * @throws InvalidDataTypeException
1282
-     * @throws InvalidInterfaceException
1283
-     * @throws ReflectionException
1284
-     */
1285
-    public function question_groups()
1286
-    {
1287
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * count_question_groups
1293
-     * returns a count of the number of EE_Question_Group objects for this registration
1294
-     *
1295
-     * @return int
1296
-     * @throws EE_Error
1297
-     * @throws EntityNotFoundException
1298
-     * @throws InvalidArgumentException
1299
-     * @throws InvalidDataTypeException
1300
-     * @throws InvalidInterfaceException
1301
-     * @throws ReflectionException
1302
-     */
1303
-    public function count_question_groups()
1304
-    {
1305
-        return EEM_Event::instance()->count_related(
1306
-            $this->event_ID(),
1307
-            'Question_Group',
1308
-            [
1309
-                [
1310
-                    'Event_Question_Group.'
1311
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1312
-                ]
1313
-            ]
1314
-        );
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * Returns the registration date in the 'standard' string format
1320
-     * (function may be improved in the future to allow for different formats and timezones)
1321
-     *
1322
-     * @return string
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function reg_date()
1326
-    {
1327
-        return $this->get_datetime('REG_date');
1328
-    }
1329
-
1330
-
1331
-    /**
1332
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1333
-     * the ticket this registration purchased, or the datetime they have registered
1334
-     * to attend)
1335
-     *
1336
-     * @return EE_Datetime_Ticket
1337
-     * @throws EE_Error
1338
-     */
1339
-    public function datetime_ticket()
1340
-    {
1341
-        return $this->get_first_related('Datetime_Ticket');
1342
-    }
1343
-
1344
-
1345
-    /**
1346
-     * Sets the registration's datetime_ticket.
1347
-     *
1348
-     * @param EE_Datetime_Ticket $datetime_ticket
1349
-     * @return EE_Datetime_Ticket
1350
-     * @throws EE_Error
1351
-     */
1352
-    public function set_datetime_ticket($datetime_ticket)
1353
-    {
1354
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1355
-    }
1356
-
1357
-    /**
1358
-     * Gets deleted
1359
-     *
1360
-     * @return bool
1361
-     * @throws EE_Error
1362
-     */
1363
-    public function deleted()
1364
-    {
1365
-        return $this->get('REG_deleted');
1366
-    }
1367
-
1368
-    /**
1369
-     * Sets deleted
1370
-     *
1371
-     * @param boolean $deleted
1372
-     * @return bool
1373
-     * @throws EE_Error
1374
-     * @throws RuntimeException
1375
-     */
1376
-    public function set_deleted($deleted)
1377
-    {
1378
-        if ($deleted) {
1379
-            $this->delete();
1380
-        } else {
1381
-            $this->restore();
1382
-        }
1383
-    }
1384
-
1385
-
1386
-    /**
1387
-     * Get the status object of this object
1388
-     *
1389
-     * @return EE_Status
1390
-     * @throws EE_Error
1391
-     */
1392
-    public function status_obj()
1393
-    {
1394
-        return $this->get_first_related('Status');
1395
-    }
1396
-
1397
-
1398
-    /**
1399
-     * Returns the number of times this registration has checked into any of the datetimes
1400
-     * its available for
1401
-     *
1402
-     * @return int
1403
-     * @throws EE_Error
1404
-     */
1405
-    public function count_checkins()
1406
-    {
1407
-        return $this->get_model()->count_related($this, 'Checkin');
1408
-    }
1409
-
1410
-
1411
-    /**
1412
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1413
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1414
-     *
1415
-     * @return int
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function count_checkins_not_checkedout()
1419
-    {
1420
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1426
-     *
1427
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1428
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1429
-     *                                          consider registration status as well as datetime access.
1430
-     * @return bool
1431
-     * @throws EE_Error
1432
-     */
1433
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1434
-    {
1435
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1436
-
1437
-        // first check registration status
1438
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1439
-            return false;
1440
-        }
1441
-        // is there a datetime ticket that matches this dtt_ID?
1442
-        if (! (EEM_Datetime_Ticket::instance()->exists(
1443
-            array(
1444
-                array(
1445
-                    'TKT_ID' => $this->get('TKT_ID'),
1446
-                    'DTT_ID' => $DTT_ID,
1447
-                ),
1448
-            )
1449
-        ))
1450
-        ) {
1451
-            return false;
1452
-        }
1453
-
1454
-        // final check is against TKT_uses
1455
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1461
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1462
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1463
-     * then return false.  Otherwise return true.
1464
-     *
1465
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1466
-     * @return bool true means can checkin.  false means cannot checkin.
1467
-     * @throws EE_Error
1468
-     */
1469
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1470
-    {
1471
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1472
-
1473
-        if (! $DTT_ID) {
1474
-            return false;
1475
-        }
1476
-
1477
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1478
-
1479
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1480
-        // check-in or not.
1481
-        if (! $max_uses || $max_uses === EE_INF) {
1482
-            return true;
1483
-        }
1484
-
1485
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1486
-        // go ahead and toggle.
1487
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1488
-            return true;
1489
-        }
1490
-
1491
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1492
-        // disallows further check-ins.
1493
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1494
-            array(
1495
-                array(
1496
-                    'REG_ID' => $this->ID(),
1497
-                    'CHK_in' => true,
1498
-                ),
1499
-            ),
1500
-            'DTT_ID',
1501
-            true
1502
-        );
1503
-        // checkins have already reached their max number of uses
1504
-        // so registrant can NOT checkin
1505
-        if ($count_unique_dtt_checkins >= $max_uses) {
1506
-            EE_Error::add_error(
1507
-                esc_html__(
1508
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1509
-                    'event_espresso'
1510
-                ),
1511
-                __FILE__,
1512
-                __FUNCTION__,
1513
-                __LINE__
1514
-            );
1515
-            return false;
1516
-        }
1517
-        return true;
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     * toggle Check-in status for this registration
1523
-     * Check-ins are toggled in the following order:
1524
-     * never checked in -> checked in
1525
-     * checked in -> checked out
1526
-     * checked out -> checked in
1527
-     *
1528
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1529
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1530
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1531
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1532
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1533
-     * @throws EE_Error
1534
-     */
1535
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1536
-    {
1537
-        if (empty($DTT_ID)) {
1538
-            $datetime = $this->get_latest_related_datetime();
1539
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1540
-            // verify the registration can checkin for the given DTT_ID
1541
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1542
-            EE_Error::add_error(
1543
-                sprintf(
1544
-                    esc_html__(
1545
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1546
-                        'event_espresso'
1547
-                    ),
1548
-                    $this->ID(),
1549
-                    $DTT_ID
1550
-                ),
1551
-                __FILE__,
1552
-                __FUNCTION__,
1553
-                __LINE__
1554
-            );
1555
-            return false;
1556
-        }
1557
-        $status_paths = array(
1558
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1559
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1560
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1561
-        );
1562
-        // start by getting the current status so we know what status we'll be changing to.
1563
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1564
-        $status_to = $status_paths[ $cur_status ];
1565
-        // database only records true for checked IN or false for checked OUT
1566
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1567
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1568
-        // add relation - note Check-ins are always creating new rows
1569
-        // because we are keeping track of Check-ins over time.
1570
-        // Eventually we'll probably want to show a list table
1571
-        // for the individual Check-ins so that they can be managed.
1572
-        $checkin = EE_Checkin::new_instance(
1573
-            array(
1574
-                'REG_ID' => $this->ID(),
1575
-                'DTT_ID' => $DTT_ID,
1576
-                'CHK_in' => $new_status,
1577
-            )
1578
-        );
1579
-        // if the record could not be saved then return false
1580
-        if ($checkin->save() === 0) {
1581
-            if (WP_DEBUG) {
1582
-                global $wpdb;
1583
-                $error = sprintf(
1584
-                    esc_html__(
1585
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1586
-                        'event_espresso'
1587
-                    ),
1588
-                    '<br />',
1589
-                    $wpdb->last_error
1590
-                );
1591
-            } else {
1592
-                $error = esc_html__(
1593
-                    'Registration check in update failed because of an unknown database error',
1594
-                    'event_espresso'
1595
-                );
1596
-            }
1597
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1598
-            return false;
1599
-        }
1600
-        // Fire a checked_in and checkout_out action.
1601
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1602
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1603
-        return $status_to;
1604
-    }
1605
-
1606
-
1607
-    /**
1608
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1609
-     * "Latest" is defined by the `DTT_EVT_start` column.
1610
-     *
1611
-     * @return EE_Datetime|null
1612
-     * @throws EE_Error
1613
-     */
1614
-    public function get_latest_related_datetime()
1615
-    {
1616
-        return EEM_Datetime::instance()->get_one(
1617
-            array(
1618
-                array(
1619
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1620
-                ),
1621
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1622
-            )
1623
-        );
1624
-    }
1625
-
1626
-
1627
-    /**
1628
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1629
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1630
-     *
1631
-     * @throws EE_Error
1632
-     */
1633
-    public function get_earliest_related_datetime()
1634
-    {
1635
-        return EEM_Datetime::instance()->get_one(
1636
-            array(
1637
-                array(
1638
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1639
-                ),
1640
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1641
-            )
1642
-        );
1643
-    }
1644
-
1645
-
1646
-    /**
1647
-     * This method simply returns the check-in status for this registration and the given datetime.
1648
-     * If neither the datetime nor the checkin values are provided as arguments,
1649
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1650
-     *
1651
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1652
-     *                            (if empty we'll get the primary datetime for
1653
-     *                            this registration (via event) and use it's ID);
1654
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1655
-     *
1656
-     * @return int                Integer representing Check-in status.
1657
-     * @throws EE_Error
1658
-     */
1659
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1660
-    {
1661
-        $checkin_query_params = array(
1662
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1663
-        );
1664
-
1665
-        if ($DTT_ID > 0) {
1666
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1667
-        }
1668
-
1669
-        // get checkin object (if exists)
1670
-        $checkin = $checkin instanceof EE_Checkin
1671
-            ? $checkin
1672
-            : $this->get_first_related('Checkin', $checkin_query_params);
1673
-        if ($checkin instanceof EE_Checkin) {
1674
-            if ($checkin->get('CHK_in')) {
1675
-                return EE_Checkin::status_checked_in; // checked in
1676
-            }
1677
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1678
-        }
1679
-        return EE_Checkin::status_checked_never; // never been checked in
1680
-    }
1681
-
1682
-
1683
-    /**
1684
-     * This method returns a localized message for the toggled Check-in message.
1685
-     *
1686
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1687
-     *                     then it is assumed Check-in for primary datetime was toggled.
1688
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1689
-     *                     message can be customized with the attendee name.
1690
-     * @return string internationalized message
1691
-     * @throws EE_Error
1692
-     */
1693
-    public function get_checkin_msg($DTT_ID, $error = false)
1694
-    {
1695
-        // let's get the attendee first so we can include the name of the attendee
1696
-        $attendee = $this->get_first_related('Attendee');
1697
-        if ($attendee instanceof EE_Attendee) {
1698
-            if ($error) {
1699
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1700
-            }
1701
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1702
-            // what is the status message going to be?
1703
-            switch ($cur_status) {
1704
-                case EE_Checkin::status_checked_never:
1705
-                    return sprintf(
1706
-                        __("%s has been removed from Check-in records", "event_espresso"),
1707
-                        $attendee->full_name()
1708
-                    );
1709
-                    break;
1710
-                case EE_Checkin::status_checked_in:
1711
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1712
-                    break;
1713
-                case EE_Checkin::status_checked_out:
1714
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1715
-                    break;
1716
-            }
1717
-        }
1718
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1719
-    }
1720
-
1721
-
1722
-    /**
1723
-     * Returns the related EE_Transaction to this registration
1724
-     *
1725
-     * @return EE_Transaction
1726
-     * @throws EE_Error
1727
-     * @throws EntityNotFoundException
1728
-     */
1729
-    public function transaction()
1730
-    {
1731
-        $transaction = $this->get_first_related('Transaction');
1732
-        if (! $transaction instanceof \EE_Transaction) {
1733
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1734
-        }
1735
-        return $transaction;
1736
-    }
1737
-
1738
-
1739
-    /**
1740
-     *        get Registration Code
1741
-     */
1742
-    public function reg_code()
1743
-    {
1744
-        return $this->get('REG_code');
1745
-    }
1746
-
1747
-
1748
-    /**
1749
-     *        get Transaction ID
1750
-     */
1751
-    public function transaction_ID()
1752
-    {
1753
-        return $this->get('TXN_ID');
1754
-    }
1755
-
1756
-
1757
-    /**
1758
-     * @return int
1759
-     * @throws EE_Error
1760
-     */
1761
-    public function ticket_ID()
1762
-    {
1763
-        return $this->get('TKT_ID');
1764
-    }
1765
-
1766
-
1767
-    /**
1768
-     *        Set Registration Code
1769
-     *
1770
-     * @access    public
1771
-     * @param    string  $REG_code Registration Code
1772
-     * @param    boolean $use_default
1773
-     * @throws EE_Error
1774
-     */
1775
-    public function set_reg_code($REG_code, $use_default = false)
1776
-    {
1777
-        if (empty($REG_code)) {
1778
-            EE_Error::add_error(
1779
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1780
-                __FILE__,
1781
-                __FUNCTION__,
1782
-                __LINE__
1783
-            );
1784
-            return;
1785
-        }
1786
-        if (! $this->reg_code()) {
1787
-            parent::set('REG_code', $REG_code, $use_default);
1788
-        } else {
1789
-            EE_Error::doing_it_wrong(
1790
-                __CLASS__ . '::' . __FUNCTION__,
1791
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1792
-                '4.6.0'
1793
-            );
1794
-        }
1795
-    }
1796
-
1797
-
1798
-    /**
1799
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1800
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1801
-     *    $registration->transaction()->registrations();
1802
-     *
1803
-     * @since 4.5.0
1804
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1805
-     * @throws EE_Error
1806
-     */
1807
-    public function get_all_other_registrations_in_group()
1808
-    {
1809
-        if ($this->group_size() < 2) {
1810
-            return array();
1811
-        }
1812
-
1813
-        $query[0] = array(
1814
-            'TXN_ID' => $this->transaction_ID(),
1815
-            'REG_ID' => array('!=', $this->ID()),
1816
-            'TKT_ID' => $this->ticket_ID(),
1817
-        );
1818
-        /** @var EE_Registration[] $registrations */
1819
-        $registrations = $this->get_model()->get_all($query);
1820
-        return $registrations;
1821
-    }
1822
-
1823
-    /**
1824
-     * Return the link to the admin details for the object.
1825
-     *
1826
-     * @return string
1827
-     * @throws EE_Error
1828
-     */
1829
-    public function get_admin_details_link()
1830
-    {
1831
-        EE_Registry::instance()->load_helper('URL');
1832
-        return EEH_URL::add_query_args_and_nonce(
1833
-            array(
1834
-                'page'    => 'espresso_registrations',
1835
-                'action'  => 'view_registration',
1836
-                '_REG_ID' => $this->ID(),
1837
-            ),
1838
-            admin_url('admin.php')
1839
-        );
1840
-    }
1841
-
1842
-    /**
1843
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1844
-     *
1845
-     * @return string
1846
-     * @throws EE_Error
1847
-     */
1848
-    public function get_admin_edit_link()
1849
-    {
1850
-        return $this->get_admin_details_link();
1851
-    }
1852
-
1853
-    /**
1854
-     * Returns the link to a settings page for the object.
1855
-     *
1856
-     * @return string
1857
-     * @throws EE_Error
1858
-     */
1859
-    public function get_admin_settings_link()
1860
-    {
1861
-        return $this->get_admin_details_link();
1862
-    }
1863
-
1864
-    /**
1865
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1866
-     *
1867
-     * @return string
1868
-     */
1869
-    public function get_admin_overview_link()
1870
-    {
1871
-        EE_Registry::instance()->load_helper('URL');
1872
-        return EEH_URL::add_query_args_and_nonce(
1873
-            array(
1874
-                'page' => 'espresso_registrations',
1875
-            ),
1876
-            admin_url('admin.php')
1877
-        );
1878
-    }
1879
-
1880
-
1881
-    /**
1882
-     * @param array $query_params
1883
-     *
1884
-     * @return \EE_Registration[]
1885
-     * @throws EE_Error
1886
-     */
1887
-    public function payments($query_params = array())
1888
-    {
1889
-        return $this->get_many_related('Payment', $query_params);
1890
-    }
1891
-
1892
-
1893
-    /**
1894
-     * @param array $query_params
1895
-     *
1896
-     * @return \EE_Registration_Payment[]
1897
-     * @throws EE_Error
1898
-     */
1899
-    public function registration_payments($query_params = array())
1900
-    {
1901
-        return $this->get_many_related('Registration_Payment', $query_params);
1902
-    }
1903
-
1904
-
1905
-    /**
1906
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1907
-     * Note: if there are no payments on the registration there will be no payment method returned.
1908
-     *
1909
-     * @return EE_Payment_Method|null
1910
-     */
1911
-    public function payment_method()
1912
-    {
1913
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1914
-    }
1915
-
1916
-
1917
-    /**
1918
-     * @return \EE_Line_Item
1919
-     * @throws EntityNotFoundException
1920
-     * @throws EE_Error
1921
-     */
1922
-    public function ticket_line_item()
1923
-    {
1924
-        $ticket = $this->ticket();
1925
-        $transaction = $this->transaction();
1926
-        $line_item = null;
1927
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1928
-            $transaction->total_line_item(),
1929
-            'Ticket',
1930
-            array($ticket->ID())
1931
-        );
1932
-        foreach ($ticket_line_items as $ticket_line_item) {
1933
-            if ($ticket_line_item instanceof \EE_Line_Item
1934
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1935
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1936
-            ) {
1937
-                $line_item = $ticket_line_item;
1938
-                break;
1939
-            }
1940
-        }
1941
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1942
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1943
-        }
1944
-        return $line_item;
1945
-    }
1946
-
1947
-
1948
-    /**
1949
-     * Soft Deletes this model object.
1950
-     *
1951
-     * @return boolean | int
1952
-     * @throws RuntimeException
1953
-     * @throws EE_Error
1954
-     */
1955
-    public function delete()
1956
-    {
1957
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1958
-            $this->set_status(EEM_Registration::status_id_cancelled);
1959
-        }
1960
-        return parent::delete();
1961
-    }
1962
-
1963
-
1964
-    /**
1965
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1966
-     *
1967
-     * @throws EE_Error
1968
-     * @throws RuntimeException
1969
-     */
1970
-    public function restore()
1971
-    {
1972
-        $previous_status = $this->get_extra_meta(
1973
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1974
-            true,
1975
-            EEM_Registration::status_id_cancelled
1976
-        );
1977
-        if ($previous_status) {
1978
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1979
-            $this->set_status($previous_status);
1980
-        }
1981
-        return parent::restore();
1982
-    }
1983
-
1984
-
1985
-    /**
1986
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1987
-     *
1988
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1989
-     *                                           depending on whether the reg status changes to or from "Approved"
1990
-     * @return boolean whether the Registration status was updated
1991
-     * @throws EE_Error
1992
-     * @throws RuntimeException
1993
-     */
1994
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1995
-    {
1996
-        $paid = $this->paid();
1997
-        $price = $this->final_price();
1998
-        switch (true) {
1999
-            // overpaid or paid
2000
-            case EEH_Money::compare_floats($paid, $price, '>'):
2001
-            case EEH_Money::compare_floats($paid, $price):
2002
-                $new_status = EEM_Registration::status_id_approved;
2003
-                break;
2004
-            //  underpaid
2005
-            case EEH_Money::compare_floats($paid, $price, '<'):
2006
-                $new_status = EEM_Registration::status_id_pending_payment;
2007
-                break;
2008
-            // uhhh Houston...
2009
-            default:
2010
-                throw new RuntimeException(
2011
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2012
-                );
2013
-        }
2014
-        if ($new_status !== $this->status_ID()) {
2015
-            if ($trigger_set_status_logic) {
2016
-                return $this->set_status($new_status);
2017
-            }
2018
-            parent::set('STS_ID', $new_status);
2019
-            return true;
2020
-        }
2021
-        return false;
2022
-    }
2023
-
2024
-
2025
-    /*************************** DEPRECATED ***************************/
2026
-
2027
-
2028
-    /**
2029
-     * @deprecated
2030
-     * @since     4.7.0
2031
-     * @access    public
2032
-     */
2033
-    public function price_paid()
2034
-    {
2035
-        EE_Error::doing_it_wrong(
2036
-            'EE_Registration::price_paid()',
2037
-            esc_html__(
2038
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2039
-                'event_espresso'
2040
-            ),
2041
-            '4.7.0'
2042
-        );
2043
-        return $this->final_price();
2044
-    }
2045
-
2046
-
2047
-    /**
2048
-     * @deprecated
2049
-     * @since     4.7.0
2050
-     * @access    public
2051
-     * @param    float $REG_final_price
2052
-     * @throws EE_Error
2053
-     * @throws RuntimeException
2054
-     */
2055
-    public function set_price_paid($REG_final_price = 0.00)
2056
-    {
2057
-        EE_Error::doing_it_wrong(
2058
-            'EE_Registration::set_price_paid()',
2059
-            esc_html__(
2060
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2061
-                'event_espresso'
2062
-            ),
2063
-            '4.7.0'
2064
-        );
2065
-        $this->set_final_price($REG_final_price);
2066
-    }
2067
-
2068
-
2069
-    /**
2070
-     * @deprecated
2071
-     * @since 4.7.0
2072
-     * @return string
2073
-     * @throws EE_Error
2074
-     */
2075
-    public function pretty_price_paid()
2076
-    {
2077
-        EE_Error::doing_it_wrong(
2078
-            'EE_Registration::pretty_price_paid()',
2079
-            esc_html__(
2080
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2081
-                'event_espresso'
2082
-            ),
2083
-            '4.7.0'
2084
-        );
2085
-        return $this->pretty_final_price();
2086
-    }
2087
-
2088
-
2089
-    /**
2090
-     * Gets the primary datetime related to this registration via the related Event to this registration
2091
-     *
2092
-     * @deprecated 4.9.17
2093
-     * @return EE_Datetime
2094
-     * @throws EE_Error
2095
-     * @throws EntityNotFoundException
2096
-     */
2097
-    public function get_related_primary_datetime()
2098
-    {
2099
-        EE_Error::doing_it_wrong(
2100
-            __METHOD__,
2101
-            esc_html__(
2102
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2103
-                'event_espresso'
2104
-            ),
2105
-            '4.9.17',
2106
-            '5.0.0'
2107
-        );
2108
-        return $this->event()->primary_datetime();
2109
-    }
2110
-
2111
-    /**
2112
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2113
-     * @since 4.10.12.p
2114
-     * @return string
2115
-     * @throws EE_Error
2116
-     * @throws InvalidArgumentException
2117
-     * @throws InvalidDataTypeException
2118
-     * @throws InvalidInterfaceException
2119
-     * @throws ReflectionException
2120
-     */
2121
-    public function name()
2122
-    {
2123
-        return $this->attendeeName();
2124
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws DomainException
146
+	 * @throws EE_Error
147
+	 * @throws EntityNotFoundException
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 * @throws RuntimeException
153
+	 * @throws UnexpectedEntityException
154
+	 */
155
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
+	{
157
+		// get current REG_Status
158
+		$old_STS_ID = $this->status_ID();
159
+		// if status has changed
160
+		if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
161
+			&& ! empty($old_STS_ID) // and that old status is actually set
162
+			&& ! empty($new_STS_ID) // as well as the new status
163
+			&& $this->ID() // ensure registration is in the db
164
+		) {
165
+			// update internal status first
166
+			parent::set('STS_ID', $new_STS_ID, $use_default);
167
+			// THEN handle other changes that occur when reg status changes
168
+			// TO approved
169
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
170
+				// reserve a space by incrementing ticket and datetime sold values
171
+				$this->reserveRegistrationSpace();
172
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
173
+				// OR FROM  approved
174
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
175
+				// release a space by decrementing ticket and datetime sold values
176
+				$this->releaseRegistrationSpace();
177
+				do_action(
178
+					'AHEE__EE_Registration__set_status__from_approved',
179
+					$this,
180
+					$old_STS_ID,
181
+					$new_STS_ID,
182
+					$context
183
+				);
184
+			}
185
+			// update status
186
+			parent::set('STS_ID', $new_STS_ID, $use_default);
187
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
188
+			if ($this->statusChangeUpdatesTransaction($context)) {
189
+				$this->updateTransactionAfterStatusChange();
190
+			}
191
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
192
+			return true;
193
+		}
194
+		// even though the old value matches the new value, it's still good to
195
+		// allow the parent set method to have a say
196
+		parent::set('STS_ID', $new_STS_ID, $use_default);
197
+		return true;
198
+	}
199
+
200
+
201
+	/**
202
+	 * update REGs and TXN when cancelled or declined registrations involved
203
+	 *
204
+	 * @param string                $new_STS_ID
205
+	 * @param string                $old_STS_ID
206
+	 * @param ContextInterface|null $context
207
+	 * @throws EE_Error
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 * @throws ReflectionException
212
+	 * @throws RuntimeException
213
+	 */
214
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
215
+	{
216
+		// these reg statuses should not be considered in any calculations involving monies owing
217
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
218
+		// true if registration has been cancelled or declined
219
+		$this->updateIfCanceled(
220
+			$closed_reg_statuses,
221
+			$new_STS_ID,
222
+			$old_STS_ID,
223
+			$context
224
+		);
225
+		$this->updateIfReinstated(
226
+			$closed_reg_statuses,
227
+			$new_STS_ID,
228
+			$old_STS_ID,
229
+			$context
230
+		);
231
+	}
232
+
233
+
234
+	/**
235
+	 * update REGs and TXN when cancelled or declined registrations involved
236
+	 *
237
+	 * @param array                 $closed_reg_statuses
238
+	 * @param string                $new_STS_ID
239
+	 * @param string                $old_STS_ID
240
+	 * @param ContextInterface|null $context
241
+	 * @throws EE_Error
242
+	 * @throws InvalidArgumentException
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws ReflectionException
246
+	 * @throws RuntimeException
247
+	 */
248
+	private function updateIfCanceled(
249
+		array $closed_reg_statuses,
250
+		$new_STS_ID,
251
+		$old_STS_ID,
252
+		ContextInterface $context = null
253
+	) {
254
+		// true if registration has been cancelled or declined
255
+		if (in_array($new_STS_ID, $closed_reg_statuses, true)
256
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
257
+		) {
258
+			/** @type EE_Registration_Processor $registration_processor */
259
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
260
+			/** @type EE_Transaction_Processor $transaction_processor */
261
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
262
+			// cancelled or declined registration
263
+			$registration_processor->update_registration_after_being_canceled_or_declined(
264
+				$this,
265
+				$closed_reg_statuses
266
+			);
267
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
268
+				$this,
269
+				$closed_reg_statuses,
270
+				false
271
+			);
272
+			do_action(
273
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
274
+				$this,
275
+				$old_STS_ID,
276
+				$new_STS_ID,
277
+				$context
278
+			);
279
+			return;
280
+		}
281
+	}
282
+
283
+
284
+	/**
285
+	 * update REGs and TXN when cancelled or declined registrations involved
286
+	 *
287
+	 * @param array                 $closed_reg_statuses
288
+	 * @param string                $new_STS_ID
289
+	 * @param string                $old_STS_ID
290
+	 * @param ContextInterface|null $context
291
+	 * @throws EE_Error
292
+	 * @throws InvalidArgumentException
293
+	 * @throws InvalidDataTypeException
294
+	 * @throws InvalidInterfaceException
295
+	 * @throws ReflectionException
296
+	 */
297
+	private function updateIfReinstated(
298
+		array $closed_reg_statuses,
299
+		$new_STS_ID,
300
+		$old_STS_ID,
301
+		ContextInterface $context = null
302
+	) {
303
+		// true if reinstating cancelled or declined registration
304
+		if (in_array($old_STS_ID, $closed_reg_statuses, true)
305
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
306
+		) {
307
+			/** @type EE_Registration_Processor $registration_processor */
308
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
309
+			/** @type EE_Transaction_Processor $transaction_processor */
310
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
311
+			// reinstating cancelled or declined registration
312
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
313
+				$this,
314
+				$closed_reg_statuses
315
+			);
316
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
317
+				$this,
318
+				$closed_reg_statuses,
319
+				false
320
+			);
321
+			do_action(
322
+				'AHEE__EE_Registration__set_status__after_reinstated',
323
+				$this,
324
+				$old_STS_ID,
325
+				$new_STS_ID,
326
+				$context
327
+			);
328
+		}
329
+	}
330
+
331
+
332
+	/**
333
+	 * @param ContextInterface|null $context
334
+	 * @return bool
335
+	 */
336
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
337
+	{
338
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
339
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
340
+			array('spco_reg_step_attendee_information_process_registrations'),
341
+			$context,
342
+			$this
343
+		);
344
+		return ! (
345
+			$context instanceof ContextInterface
346
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
347
+		);
348
+	}
349
+
350
+
351
+	/**
352
+	 * @throws EE_Error
353
+	 * @throws EntityNotFoundException
354
+	 * @throws InvalidArgumentException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws InvalidInterfaceException
357
+	 * @throws ReflectionException
358
+	 * @throws RuntimeException
359
+	 */
360
+	private function updateTransactionAfterStatusChange()
361
+	{
362
+		/** @type EE_Transaction_Payments $transaction_payments */
363
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
364
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
365
+		$this->transaction()->update_status_based_on_total_paid(true);
366
+	}
367
+
368
+
369
+	/**
370
+	 *        get Status ID
371
+	 */
372
+	public function status_ID()
373
+	{
374
+		return $this->get('STS_ID');
375
+	}
376
+
377
+
378
+	/**
379
+	 * Gets the ticket this registration is for
380
+	 *
381
+	 * @param boolean $include_archived whether to include archived tickets or not.
382
+	 *
383
+	 * @return EE_Ticket|EE_Base_Class
384
+	 * @throws EE_Error
385
+	 */
386
+	public function ticket($include_archived = true)
387
+	{
388
+		$query_params = array();
389
+		if ($include_archived) {
390
+			$query_params['default_where_conditions'] = 'none';
391
+		}
392
+		return $this->get_first_related('Ticket', $query_params);
393
+	}
394
+
395
+
396
+	/**
397
+	 * Gets the event this registration is for
398
+	 *
399
+	 * @return EE_Event
400
+	 * @throws EE_Error
401
+	 * @throws EntityNotFoundException
402
+	 */
403
+	public function event()
404
+	{
405
+		$event = $this->get_first_related('Event');
406
+		if (! $event instanceof \EE_Event) {
407
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
408
+		}
409
+		return $event;
410
+	}
411
+
412
+
413
+	/**
414
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
415
+	 * with the author of the event this registration is for.
416
+	 *
417
+	 * @since 4.5.0
418
+	 * @return int
419
+	 * @throws EE_Error
420
+	 * @throws EntityNotFoundException
421
+	 */
422
+	public function wp_user()
423
+	{
424
+		$event = $this->event();
425
+		if ($event instanceof EE_Event) {
426
+			return $event->wp_user();
427
+		}
428
+		return 0;
429
+	}
430
+
431
+
432
+	/**
433
+	 * increments this registration's related ticket sold and corresponding datetime sold values
434
+	 *
435
+	 * @return void
436
+	 * @throws DomainException
437
+	 * @throws EE_Error
438
+	 * @throws EntityNotFoundException
439
+	 * @throws InvalidArgumentException
440
+	 * @throws InvalidDataTypeException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws ReflectionException
443
+	 * @throws UnexpectedEntityException
444
+	 */
445
+	private function reserveRegistrationSpace()
446
+	{
447
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
448
+		// so stop tracking that this reg has a ticket reserved
449
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
450
+		$ticket = $this->ticket();
451
+		$ticket->increaseSold();
452
+		// possibly set event status to sold out
453
+		$this->event()->perform_sold_out_status_check();
454
+	}
455
+
456
+
457
+	/**
458
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
459
+	 *
460
+	 * @return void
461
+	 * @throws DomainException
462
+	 * @throws EE_Error
463
+	 * @throws EntityNotFoundException
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws ReflectionException
468
+	 * @throws UnexpectedEntityException
469
+	 */
470
+	private function releaseRegistrationSpace()
471
+	{
472
+		$ticket = $this->ticket();
473
+		$ticket->decreaseSold();
474
+		// possibly change event status from sold out back to previous status
475
+		$this->event()->perform_sold_out_status_check();
476
+	}
477
+
478
+
479
+	/**
480
+	 * tracks this registration's ticket reservation in extra meta
481
+	 * and can increment related ticket reserved and corresponding datetime reserved values
482
+	 *
483
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
484
+	 * @return void
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 * @throws ReflectionException
490
+	 */
491
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
492
+	{
493
+		// only reserve ticket if space is not currently reserved
494
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
495
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
496
+			// IMPORTANT !!!
497
+			// although checking $update_ticket first would be more efficient,
498
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
499
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
500
+				&& $update_ticket
501
+			) {
502
+				$ticket = $this->ticket();
503
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
504
+				$ticket->save();
505
+			}
506
+		}
507
+	}
508
+
509
+
510
+	/**
511
+	 * stops tracking this registration's ticket reservation in extra meta
512
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
513
+	 *
514
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
515
+	 * @return void
516
+	 * @throws EE_Error
517
+	 * @throws InvalidArgumentException
518
+	 * @throws InvalidDataTypeException
519
+	 * @throws InvalidInterfaceException
520
+	 * @throws ReflectionException
521
+	 */
522
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
523
+	{
524
+		// only release ticket if space is currently reserved
525
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
526
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
527
+			// IMPORTANT !!!
528
+			// although checking $update_ticket first would be more efficient,
529
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
530
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
531
+				&& $update_ticket
532
+			) {
533
+				$ticket = $this->ticket();
534
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
535
+			}
536
+		}
537
+	}
538
+
539
+
540
+	/**
541
+	 * Set Attendee ID
542
+	 *
543
+	 * @param        int $ATT_ID Attendee ID
544
+	 * @throws EE_Error
545
+	 * @throws RuntimeException
546
+	 */
547
+	public function set_attendee_id($ATT_ID = 0)
548
+	{
549
+		$this->set('ATT_ID', $ATT_ID);
550
+	}
551
+
552
+
553
+	/**
554
+	 *        Set Transaction ID
555
+	 *
556
+	 * @param        int $TXN_ID Transaction ID
557
+	 * @throws EE_Error
558
+	 * @throws RuntimeException
559
+	 */
560
+	public function set_transaction_id($TXN_ID = 0)
561
+	{
562
+		$this->set('TXN_ID', $TXN_ID);
563
+	}
564
+
565
+
566
+	/**
567
+	 *        Set Session
568
+	 *
569
+	 * @param    string $REG_session PHP Session ID
570
+	 * @throws EE_Error
571
+	 * @throws RuntimeException
572
+	 */
573
+	public function set_session($REG_session = '')
574
+	{
575
+		$this->set('REG_session', $REG_session);
576
+	}
577
+
578
+
579
+	/**
580
+	 *        Set Registration URL Link
581
+	 *
582
+	 * @param    string $REG_url_link Registration URL Link
583
+	 * @throws EE_Error
584
+	 * @throws RuntimeException
585
+	 */
586
+	public function set_reg_url_link($REG_url_link = '')
587
+	{
588
+		$this->set('REG_url_link', $REG_url_link);
589
+	}
590
+
591
+
592
+	/**
593
+	 *        Set Attendee Counter
594
+	 *
595
+	 * @param        int $REG_count Primary Attendee
596
+	 * @throws EE_Error
597
+	 * @throws RuntimeException
598
+	 */
599
+	public function set_count($REG_count = 1)
600
+	{
601
+		$this->set('REG_count', $REG_count);
602
+	}
603
+
604
+
605
+	/**
606
+	 *        Set Group Size
607
+	 *
608
+	 * @param        boolean $REG_group_size Group Registration
609
+	 * @throws EE_Error
610
+	 * @throws RuntimeException
611
+	 */
612
+	public function set_group_size($REG_group_size = false)
613
+	{
614
+		$this->set('REG_group_size', $REG_group_size);
615
+	}
616
+
617
+
618
+	/**
619
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
620
+	 *    EEM_Registration::status_id_not_approved
621
+	 *
622
+	 * @return        boolean
623
+	 */
624
+	public function is_not_approved()
625
+	{
626
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
627
+	}
628
+
629
+
630
+	/**
631
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
632
+	 *    EEM_Registration::status_id_pending_payment
633
+	 *
634
+	 * @return        boolean
635
+	 */
636
+	public function is_pending_payment()
637
+	{
638
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
639
+	}
640
+
641
+
642
+	/**
643
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
644
+	 *
645
+	 * @return        boolean
646
+	 */
647
+	public function is_approved()
648
+	{
649
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
650
+	}
651
+
652
+
653
+	/**
654
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
655
+	 *
656
+	 * @return        boolean
657
+	 */
658
+	public function is_cancelled()
659
+	{
660
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
661
+	}
662
+
663
+
664
+	/**
665
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
666
+	 *
667
+	 * @return        boolean
668
+	 */
669
+	public function is_declined()
670
+	{
671
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
672
+	}
673
+
674
+
675
+	/**
676
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
677
+	 *    EEM_Registration::status_id_incomplete
678
+	 *
679
+	 * @return        boolean
680
+	 */
681
+	public function is_incomplete()
682
+	{
683
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
684
+	}
685
+
686
+
687
+	/**
688
+	 *        Set Registration Date
689
+	 *
690
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
691
+	 *                                                 Date
692
+	 * @throws EE_Error
693
+	 * @throws RuntimeException
694
+	 */
695
+	public function set_reg_date($REG_date = false)
696
+	{
697
+		$this->set('REG_date', $REG_date);
698
+	}
699
+
700
+
701
+	/**
702
+	 *    Set final price owing for this registration after all ticket/price modifications
703
+	 *
704
+	 * @access    public
705
+	 * @param    float $REG_final_price
706
+	 * @throws EE_Error
707
+	 * @throws RuntimeException
708
+	 */
709
+	public function set_final_price($REG_final_price = 0.00)
710
+	{
711
+		$this->set('REG_final_price', $REG_final_price);
712
+	}
713
+
714
+
715
+	/**
716
+	 *    Set amount paid towards this registration's final price
717
+	 *
718
+	 * @access    public
719
+	 * @param    float $REG_paid
720
+	 * @throws EE_Error
721
+	 * @throws RuntimeException
722
+	 */
723
+	public function set_paid($REG_paid = 0.00)
724
+	{
725
+		$this->set('REG_paid', $REG_paid);
726
+	}
727
+
728
+
729
+	/**
730
+	 *        Attendee Is Going
731
+	 *
732
+	 * @param        boolean $REG_att_is_going Attendee Is Going
733
+	 * @throws EE_Error
734
+	 * @throws RuntimeException
735
+	 */
736
+	public function set_att_is_going($REG_att_is_going = false)
737
+	{
738
+		$this->set('REG_att_is_going', $REG_att_is_going);
739
+	}
740
+
741
+
742
+	/**
743
+	 * Gets the related attendee
744
+	 *
745
+	 * @return EE_Attendee
746
+	 * @throws EE_Error
747
+	 */
748
+	public function attendee()
749
+	{
750
+		return $this->get_first_related('Attendee');
751
+	}
752
+
753
+	/**
754
+	 * Gets the name of the attendee.
755
+	 * @since 4.10.12.p
756
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
757
+	 * @return string
758
+	 * @throws EE_Error
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 * @throws ReflectionException
763
+	 */
764
+	public function attendeeName($apply_html_entities = false)
765
+	{
766
+		$attendee = $this->get_first_related('Attendee');
767
+		if ($attendee instanceof EE_Attendee) {
768
+			$attendee_name = $attendee->full_name($apply_html_entities);
769
+		} else {
770
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
771
+		}
772
+		return $attendee_name;
773
+	}
774
+
775
+
776
+	/**
777
+	 *        get Event ID
778
+	 */
779
+	public function event_ID()
780
+	{
781
+		return $this->get('EVT_ID');
782
+	}
783
+
784
+
785
+	/**
786
+	 *        get Event ID
787
+	 */
788
+	public function event_name()
789
+	{
790
+		$event = $this->event_obj();
791
+		if ($event) {
792
+			return $event->name();
793
+		} else {
794
+			return null;
795
+		}
796
+	}
797
+
798
+
799
+	/**
800
+	 * Fetches the event this registration is for
801
+	 *
802
+	 * @return EE_Event
803
+	 * @throws EE_Error
804
+	 */
805
+	public function event_obj()
806
+	{
807
+		return $this->get_first_related('Event');
808
+	}
809
+
810
+
811
+	/**
812
+	 *        get Attendee ID
813
+	 */
814
+	public function attendee_ID()
815
+	{
816
+		return $this->get('ATT_ID');
817
+	}
818
+
819
+
820
+	/**
821
+	 *        get PHP Session ID
822
+	 */
823
+	public function session_ID()
824
+	{
825
+		return $this->get('REG_session');
826
+	}
827
+
828
+
829
+	/**
830
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
831
+	 *
832
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
833
+	 * @return string
834
+	 */
835
+	public function receipt_url($messenger = 'html')
836
+	{
837
+
838
+		/**
839
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
840
+		 * already in use on old system.  If there is then we just return the standard url for it.
841
+		 *
842
+		 * @since 4.5.0
843
+		 */
844
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
845
+		$has_custom = EEH_Template::locate_template(
846
+			$template_relative_path,
847
+			array(),
848
+			true,
849
+			true,
850
+			true
851
+		);
852
+
853
+		if ($has_custom) {
854
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
855
+		}
856
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
857
+	}
858
+
859
+
860
+	/**
861
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
862
+	 *
863
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
864
+	 * @return string
865
+	 * @throws EE_Error
866
+	 */
867
+	public function invoice_url($messenger = 'html')
868
+	{
869
+		/**
870
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
871
+		 * already in use on old system.  If there is then we just return the standard url for it.
872
+		 *
873
+		 * @since 4.5.0
874
+		 */
875
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
876
+		$has_custom = EEH_Template::locate_template(
877
+			$template_relative_path,
878
+			array(),
879
+			true,
880
+			true,
881
+			true
882
+		);
883
+
884
+		if ($has_custom) {
885
+			if ($messenger == 'html') {
886
+				return $this->invoice_url('launch');
887
+			}
888
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
889
+
890
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
891
+			if ($messenger == 'html') {
892
+				$query_args['html'] = true;
893
+			}
894
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
895
+		}
896
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
897
+	}
898
+
899
+
900
+	/**
901
+	 * get Registration URL Link
902
+	 *
903
+	 * @access public
904
+	 * @return string
905
+	 * @throws EE_Error
906
+	 */
907
+	public function reg_url_link()
908
+	{
909
+		return (string) $this->get('REG_url_link');
910
+	}
911
+
912
+
913
+	/**
914
+	 * Echoes out invoice_url()
915
+	 *
916
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
917
+	 * @return void
918
+	 * @throws EE_Error
919
+	 */
920
+	public function e_invoice_url($type = 'launch')
921
+	{
922
+		echo $this->invoice_url($type);
923
+	}
924
+
925
+
926
+	/**
927
+	 * Echoes out payment_overview_url
928
+	 */
929
+	public function e_payment_overview_url()
930
+	{
931
+		echo $this->payment_overview_url();
932
+	}
933
+
934
+
935
+	/**
936
+	 * Gets the URL for the checkout payment options reg step
937
+	 * with this registration's REG_url_link added as a query parameter
938
+	 *
939
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
940
+	 *                            payment overview url.
941
+	 * @return string
942
+	 * @throws InvalidInterfaceException
943
+	 * @throws InvalidDataTypeException
944
+	 * @throws EE_Error
945
+	 * @throws InvalidArgumentException
946
+	 */
947
+	public function payment_overview_url($clear_session = false)
948
+	{
949
+		return add_query_arg(
950
+			(array) apply_filters(
951
+				'FHEE__EE_Registration__payment_overview_url__query_args',
952
+				array(
953
+					'e_reg_url_link' => $this->reg_url_link(),
954
+					'step'           => 'payment_options',
955
+					'revisit'        => true,
956
+					'clear_session'  => (bool) $clear_session,
957
+				),
958
+				$this
959
+			),
960
+			EE_Registry::instance()->CFG->core->reg_page_url()
961
+		);
962
+	}
963
+
964
+
965
+	/**
966
+	 * Gets the URL for the checkout attendee information reg step
967
+	 * with this registration's REG_url_link added as a query parameter
968
+	 *
969
+	 * @return string
970
+	 * @throws InvalidInterfaceException
971
+	 * @throws InvalidDataTypeException
972
+	 * @throws EE_Error
973
+	 * @throws InvalidArgumentException
974
+	 */
975
+	public function edit_attendee_information_url()
976
+	{
977
+		return add_query_arg(
978
+			(array) apply_filters(
979
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
980
+				array(
981
+					'e_reg_url_link' => $this->reg_url_link(),
982
+					'step'           => 'attendee_information',
983
+					'revisit'        => true,
984
+				),
985
+				$this
986
+			),
987
+			EE_Registry::instance()->CFG->core->reg_page_url()
988
+		);
989
+	}
990
+
991
+
992
+	/**
993
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
994
+	 *
995
+	 * @return string
996
+	 * @throws EE_Error
997
+	 */
998
+	public function get_admin_edit_url()
999
+	{
1000
+		return EEH_URL::add_query_args_and_nonce(
1001
+			array(
1002
+				'page'    => 'espresso_registrations',
1003
+				'action'  => 'view_registration',
1004
+				'_REG_ID' => $this->ID(),
1005
+			),
1006
+			admin_url('admin.php')
1007
+		);
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 *    is_primary_registrant?
1013
+	 */
1014
+	public function is_primary_registrant()
1015
+	{
1016
+		return $this->get('REG_count') === 1 ? true : false;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * This returns the primary registration object for this registration group (which may be this object).
1022
+	 *
1023
+	 * @return EE_Registration
1024
+	 * @throws EE_Error
1025
+	 */
1026
+	public function get_primary_registration()
1027
+	{
1028
+		if ($this->is_primary_registrant()) {
1029
+			return $this;
1030
+		}
1031
+
1032
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1033
+		/** @var EE_Registration $primary_registrant */
1034
+		$primary_registrant = EEM_Registration::instance()->get_one(
1035
+			array(
1036
+				array(
1037
+					'TXN_ID'    => $this->transaction_ID(),
1038
+					'REG_count' => 1,
1039
+				),
1040
+			)
1041
+		);
1042
+		return $primary_registrant;
1043
+	}
1044
+
1045
+
1046
+	/**
1047
+	 *        get  Attendee Number
1048
+	 *
1049
+	 * @access        public
1050
+	 */
1051
+	public function count()
1052
+	{
1053
+		return $this->get('REG_count');
1054
+	}
1055
+
1056
+
1057
+	/**
1058
+	 *        get Group Size
1059
+	 */
1060
+	public function group_size()
1061
+	{
1062
+		return $this->get('REG_group_size');
1063
+	}
1064
+
1065
+
1066
+	/**
1067
+	 *        get Registration Date
1068
+	 */
1069
+	public function date()
1070
+	{
1071
+		return $this->get('REG_date');
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * gets a pretty date
1077
+	 *
1078
+	 * @param string $date_format
1079
+	 * @param string $time_format
1080
+	 * @return string
1081
+	 * @throws EE_Error
1082
+	 */
1083
+	public function pretty_date($date_format = null, $time_format = null)
1084
+	{
1085
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 * final_price
1091
+	 * the registration's share of the transaction total, so that the
1092
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1093
+	 *
1094
+	 * @return float
1095
+	 * @throws EE_Error
1096
+	 */
1097
+	public function final_price()
1098
+	{
1099
+		return $this->get('REG_final_price');
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 * pretty_final_price
1105
+	 *  final price as formatted string, with correct decimal places and currency symbol
1106
+	 *
1107
+	 * @return string
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function pretty_final_price()
1111
+	{
1112
+		return $this->get_pretty('REG_final_price');
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * get paid (yeah)
1118
+	 *
1119
+	 * @return float
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function paid()
1123
+	{
1124
+		return $this->get('REG_paid');
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * pretty_paid
1130
+	 *
1131
+	 * @return float
1132
+	 * @throws EE_Error
1133
+	 */
1134
+	public function pretty_paid()
1135
+	{
1136
+		return $this->get_pretty('REG_paid');
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * owes_monies_and_can_pay
1142
+	 * whether or not this registration has monies owing and it's' status allows payment
1143
+	 *
1144
+	 * @param array $requires_payment
1145
+	 * @return bool
1146
+	 * @throws EE_Error
1147
+	 */
1148
+	public function owes_monies_and_can_pay($requires_payment = array())
1149
+	{
1150
+		// these reg statuses require payment (if event is not free)
1151
+		$requires_payment = ! empty($requires_payment)
1152
+			? $requires_payment
1153
+			: EEM_Registration::reg_statuses_that_allow_payment();
1154
+		if (in_array($this->status_ID(), $requires_payment) &&
1155
+			$this->final_price() != 0 &&
1156
+			$this->final_price() != $this->paid()
1157
+		) {
1158
+			return true;
1159
+		} else {
1160
+			return false;
1161
+		}
1162
+	}
1163
+
1164
+
1165
+	/**
1166
+	 * Prints out the return value of $this->pretty_status()
1167
+	 *
1168
+	 * @param bool $show_icons
1169
+	 * @return void
1170
+	 * @throws EE_Error
1171
+	 */
1172
+	public function e_pretty_status($show_icons = false)
1173
+	{
1174
+		echo $this->pretty_status($show_icons);
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * Returns a nice version of the status for displaying to customers
1180
+	 *
1181
+	 * @param bool $show_icons
1182
+	 * @return string
1183
+	 * @throws EE_Error
1184
+	 */
1185
+	public function pretty_status($show_icons = false)
1186
+	{
1187
+		$status = EEM_Status::instance()->localized_status(
1188
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1189
+			false,
1190
+			'sentence'
1191
+		);
1192
+		$icon = '';
1193
+		switch ($this->status_ID()) {
1194
+			case EEM_Registration::status_id_approved:
1195
+				$icon = $show_icons
1196
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1197
+					: '';
1198
+				break;
1199
+			case EEM_Registration::status_id_pending_payment:
1200
+				$icon = $show_icons
1201
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1202
+					: '';
1203
+				break;
1204
+			case EEM_Registration::status_id_not_approved:
1205
+				$icon = $show_icons
1206
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1207
+					: '';
1208
+				break;
1209
+			case EEM_Registration::status_id_cancelled:
1210
+				$icon = $show_icons
1211
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1212
+					: '';
1213
+				break;
1214
+			case EEM_Registration::status_id_incomplete:
1215
+				$icon = $show_icons
1216
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1217
+					: '';
1218
+				break;
1219
+			case EEM_Registration::status_id_declined:
1220
+				$icon = $show_icons
1221
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1222
+					: '';
1223
+				break;
1224
+			case EEM_Registration::status_id_wait_list:
1225
+				$icon = $show_icons
1226
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1227
+					: '';
1228
+				break;
1229
+		}
1230
+		return $icon . $status[ $this->status_ID() ];
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 *        get Attendee Is Going
1236
+	 */
1237
+	public function att_is_going()
1238
+	{
1239
+		return $this->get('REG_att_is_going');
1240
+	}
1241
+
1242
+
1243
+	/**
1244
+	 * Gets related answers
1245
+	 *
1246
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1247
+	 * @return EE_Answer[]
1248
+	 * @throws EE_Error
1249
+	 */
1250
+	public function answers($query_params = null)
1251
+	{
1252
+		return $this->get_many_related('Answer', $query_params);
1253
+	}
1254
+
1255
+
1256
+	/**
1257
+	 * Gets the registration's answer value to the specified question
1258
+	 * (either the question's ID or a question object)
1259
+	 *
1260
+	 * @param EE_Question|int $question
1261
+	 * @param bool            $pretty_value
1262
+	 * @return array|string if pretty_value= true, the result will always be a string
1263
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1264
+	 * will convert it into some kind of string)
1265
+	 * @throws EE_Error
1266
+	 */
1267
+	public function answer_value_to_question($question, $pretty_value = true)
1268
+	{
1269
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1270
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1271
+	}
1272
+
1273
+
1274
+	/**
1275
+	 * question_groups
1276
+	 * returns an array of EE_Question_Group objects for this registration
1277
+	 *
1278
+	 * @return EE_Question_Group[]
1279
+	 * @throws EE_Error
1280
+	 * @throws InvalidArgumentException
1281
+	 * @throws InvalidDataTypeException
1282
+	 * @throws InvalidInterfaceException
1283
+	 * @throws ReflectionException
1284
+	 */
1285
+	public function question_groups()
1286
+	{
1287
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * count_question_groups
1293
+	 * returns a count of the number of EE_Question_Group objects for this registration
1294
+	 *
1295
+	 * @return int
1296
+	 * @throws EE_Error
1297
+	 * @throws EntityNotFoundException
1298
+	 * @throws InvalidArgumentException
1299
+	 * @throws InvalidDataTypeException
1300
+	 * @throws InvalidInterfaceException
1301
+	 * @throws ReflectionException
1302
+	 */
1303
+	public function count_question_groups()
1304
+	{
1305
+		return EEM_Event::instance()->count_related(
1306
+			$this->event_ID(),
1307
+			'Question_Group',
1308
+			[
1309
+				[
1310
+					'Event_Question_Group.'
1311
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1312
+				]
1313
+			]
1314
+		);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * Returns the registration date in the 'standard' string format
1320
+	 * (function may be improved in the future to allow for different formats and timezones)
1321
+	 *
1322
+	 * @return string
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function reg_date()
1326
+	{
1327
+		return $this->get_datetime('REG_date');
1328
+	}
1329
+
1330
+
1331
+	/**
1332
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1333
+	 * the ticket this registration purchased, or the datetime they have registered
1334
+	 * to attend)
1335
+	 *
1336
+	 * @return EE_Datetime_Ticket
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	public function datetime_ticket()
1340
+	{
1341
+		return $this->get_first_related('Datetime_Ticket');
1342
+	}
1343
+
1344
+
1345
+	/**
1346
+	 * Sets the registration's datetime_ticket.
1347
+	 *
1348
+	 * @param EE_Datetime_Ticket $datetime_ticket
1349
+	 * @return EE_Datetime_Ticket
1350
+	 * @throws EE_Error
1351
+	 */
1352
+	public function set_datetime_ticket($datetime_ticket)
1353
+	{
1354
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1355
+	}
1356
+
1357
+	/**
1358
+	 * Gets deleted
1359
+	 *
1360
+	 * @return bool
1361
+	 * @throws EE_Error
1362
+	 */
1363
+	public function deleted()
1364
+	{
1365
+		return $this->get('REG_deleted');
1366
+	}
1367
+
1368
+	/**
1369
+	 * Sets deleted
1370
+	 *
1371
+	 * @param boolean $deleted
1372
+	 * @return bool
1373
+	 * @throws EE_Error
1374
+	 * @throws RuntimeException
1375
+	 */
1376
+	public function set_deleted($deleted)
1377
+	{
1378
+		if ($deleted) {
1379
+			$this->delete();
1380
+		} else {
1381
+			$this->restore();
1382
+		}
1383
+	}
1384
+
1385
+
1386
+	/**
1387
+	 * Get the status object of this object
1388
+	 *
1389
+	 * @return EE_Status
1390
+	 * @throws EE_Error
1391
+	 */
1392
+	public function status_obj()
1393
+	{
1394
+		return $this->get_first_related('Status');
1395
+	}
1396
+
1397
+
1398
+	/**
1399
+	 * Returns the number of times this registration has checked into any of the datetimes
1400
+	 * its available for
1401
+	 *
1402
+	 * @return int
1403
+	 * @throws EE_Error
1404
+	 */
1405
+	public function count_checkins()
1406
+	{
1407
+		return $this->get_model()->count_related($this, 'Checkin');
1408
+	}
1409
+
1410
+
1411
+	/**
1412
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1413
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1414
+	 *
1415
+	 * @return int
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function count_checkins_not_checkedout()
1419
+	{
1420
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1426
+	 *
1427
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1428
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1429
+	 *                                          consider registration status as well as datetime access.
1430
+	 * @return bool
1431
+	 * @throws EE_Error
1432
+	 */
1433
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1434
+	{
1435
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1436
+
1437
+		// first check registration status
1438
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1439
+			return false;
1440
+		}
1441
+		// is there a datetime ticket that matches this dtt_ID?
1442
+		if (! (EEM_Datetime_Ticket::instance()->exists(
1443
+			array(
1444
+				array(
1445
+					'TKT_ID' => $this->get('TKT_ID'),
1446
+					'DTT_ID' => $DTT_ID,
1447
+				),
1448
+			)
1449
+		))
1450
+		) {
1451
+			return false;
1452
+		}
1453
+
1454
+		// final check is against TKT_uses
1455
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1461
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1462
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1463
+	 * then return false.  Otherwise return true.
1464
+	 *
1465
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1466
+	 * @return bool true means can checkin.  false means cannot checkin.
1467
+	 * @throws EE_Error
1468
+	 */
1469
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1470
+	{
1471
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1472
+
1473
+		if (! $DTT_ID) {
1474
+			return false;
1475
+		}
1476
+
1477
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1478
+
1479
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1480
+		// check-in or not.
1481
+		if (! $max_uses || $max_uses === EE_INF) {
1482
+			return true;
1483
+		}
1484
+
1485
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1486
+		// go ahead and toggle.
1487
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1488
+			return true;
1489
+		}
1490
+
1491
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1492
+		// disallows further check-ins.
1493
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1494
+			array(
1495
+				array(
1496
+					'REG_ID' => $this->ID(),
1497
+					'CHK_in' => true,
1498
+				),
1499
+			),
1500
+			'DTT_ID',
1501
+			true
1502
+		);
1503
+		// checkins have already reached their max number of uses
1504
+		// so registrant can NOT checkin
1505
+		if ($count_unique_dtt_checkins >= $max_uses) {
1506
+			EE_Error::add_error(
1507
+				esc_html__(
1508
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1509
+					'event_espresso'
1510
+				),
1511
+				__FILE__,
1512
+				__FUNCTION__,
1513
+				__LINE__
1514
+			);
1515
+			return false;
1516
+		}
1517
+		return true;
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 * toggle Check-in status for this registration
1523
+	 * Check-ins are toggled in the following order:
1524
+	 * never checked in -> checked in
1525
+	 * checked in -> checked out
1526
+	 * checked out -> checked in
1527
+	 *
1528
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1529
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1530
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1531
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1532
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1533
+	 * @throws EE_Error
1534
+	 */
1535
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1536
+	{
1537
+		if (empty($DTT_ID)) {
1538
+			$datetime = $this->get_latest_related_datetime();
1539
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1540
+			// verify the registration can checkin for the given DTT_ID
1541
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1542
+			EE_Error::add_error(
1543
+				sprintf(
1544
+					esc_html__(
1545
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1546
+						'event_espresso'
1547
+					),
1548
+					$this->ID(),
1549
+					$DTT_ID
1550
+				),
1551
+				__FILE__,
1552
+				__FUNCTION__,
1553
+				__LINE__
1554
+			);
1555
+			return false;
1556
+		}
1557
+		$status_paths = array(
1558
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1559
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1560
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1561
+		);
1562
+		// start by getting the current status so we know what status we'll be changing to.
1563
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1564
+		$status_to = $status_paths[ $cur_status ];
1565
+		// database only records true for checked IN or false for checked OUT
1566
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1567
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1568
+		// add relation - note Check-ins are always creating new rows
1569
+		// because we are keeping track of Check-ins over time.
1570
+		// Eventually we'll probably want to show a list table
1571
+		// for the individual Check-ins so that they can be managed.
1572
+		$checkin = EE_Checkin::new_instance(
1573
+			array(
1574
+				'REG_ID' => $this->ID(),
1575
+				'DTT_ID' => $DTT_ID,
1576
+				'CHK_in' => $new_status,
1577
+			)
1578
+		);
1579
+		// if the record could not be saved then return false
1580
+		if ($checkin->save() === 0) {
1581
+			if (WP_DEBUG) {
1582
+				global $wpdb;
1583
+				$error = sprintf(
1584
+					esc_html__(
1585
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1586
+						'event_espresso'
1587
+					),
1588
+					'<br />',
1589
+					$wpdb->last_error
1590
+				);
1591
+			} else {
1592
+				$error = esc_html__(
1593
+					'Registration check in update failed because of an unknown database error',
1594
+					'event_espresso'
1595
+				);
1596
+			}
1597
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1598
+			return false;
1599
+		}
1600
+		// Fire a checked_in and checkout_out action.
1601
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1602
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1603
+		return $status_to;
1604
+	}
1605
+
1606
+
1607
+	/**
1608
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1609
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1610
+	 *
1611
+	 * @return EE_Datetime|null
1612
+	 * @throws EE_Error
1613
+	 */
1614
+	public function get_latest_related_datetime()
1615
+	{
1616
+		return EEM_Datetime::instance()->get_one(
1617
+			array(
1618
+				array(
1619
+					'Ticket.Registration.REG_ID' => $this->ID(),
1620
+				),
1621
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1622
+			)
1623
+		);
1624
+	}
1625
+
1626
+
1627
+	/**
1628
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1629
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1630
+	 *
1631
+	 * @throws EE_Error
1632
+	 */
1633
+	public function get_earliest_related_datetime()
1634
+	{
1635
+		return EEM_Datetime::instance()->get_one(
1636
+			array(
1637
+				array(
1638
+					'Ticket.Registration.REG_ID' => $this->ID(),
1639
+				),
1640
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1641
+			)
1642
+		);
1643
+	}
1644
+
1645
+
1646
+	/**
1647
+	 * This method simply returns the check-in status for this registration and the given datetime.
1648
+	 * If neither the datetime nor the checkin values are provided as arguments,
1649
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1650
+	 *
1651
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1652
+	 *                            (if empty we'll get the primary datetime for
1653
+	 *                            this registration (via event) and use it's ID);
1654
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1655
+	 *
1656
+	 * @return int                Integer representing Check-in status.
1657
+	 * @throws EE_Error
1658
+	 */
1659
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1660
+	{
1661
+		$checkin_query_params = array(
1662
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1663
+		);
1664
+
1665
+		if ($DTT_ID > 0) {
1666
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1667
+		}
1668
+
1669
+		// get checkin object (if exists)
1670
+		$checkin = $checkin instanceof EE_Checkin
1671
+			? $checkin
1672
+			: $this->get_first_related('Checkin', $checkin_query_params);
1673
+		if ($checkin instanceof EE_Checkin) {
1674
+			if ($checkin->get('CHK_in')) {
1675
+				return EE_Checkin::status_checked_in; // checked in
1676
+			}
1677
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1678
+		}
1679
+		return EE_Checkin::status_checked_never; // never been checked in
1680
+	}
1681
+
1682
+
1683
+	/**
1684
+	 * This method returns a localized message for the toggled Check-in message.
1685
+	 *
1686
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1687
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1688
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1689
+	 *                     message can be customized with the attendee name.
1690
+	 * @return string internationalized message
1691
+	 * @throws EE_Error
1692
+	 */
1693
+	public function get_checkin_msg($DTT_ID, $error = false)
1694
+	{
1695
+		// let's get the attendee first so we can include the name of the attendee
1696
+		$attendee = $this->get_first_related('Attendee');
1697
+		if ($attendee instanceof EE_Attendee) {
1698
+			if ($error) {
1699
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1700
+			}
1701
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1702
+			// what is the status message going to be?
1703
+			switch ($cur_status) {
1704
+				case EE_Checkin::status_checked_never:
1705
+					return sprintf(
1706
+						__("%s has been removed from Check-in records", "event_espresso"),
1707
+						$attendee->full_name()
1708
+					);
1709
+					break;
1710
+				case EE_Checkin::status_checked_in:
1711
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1712
+					break;
1713
+				case EE_Checkin::status_checked_out:
1714
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1715
+					break;
1716
+			}
1717
+		}
1718
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1719
+	}
1720
+
1721
+
1722
+	/**
1723
+	 * Returns the related EE_Transaction to this registration
1724
+	 *
1725
+	 * @return EE_Transaction
1726
+	 * @throws EE_Error
1727
+	 * @throws EntityNotFoundException
1728
+	 */
1729
+	public function transaction()
1730
+	{
1731
+		$transaction = $this->get_first_related('Transaction');
1732
+		if (! $transaction instanceof \EE_Transaction) {
1733
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1734
+		}
1735
+		return $transaction;
1736
+	}
1737
+
1738
+
1739
+	/**
1740
+	 *        get Registration Code
1741
+	 */
1742
+	public function reg_code()
1743
+	{
1744
+		return $this->get('REG_code');
1745
+	}
1746
+
1747
+
1748
+	/**
1749
+	 *        get Transaction ID
1750
+	 */
1751
+	public function transaction_ID()
1752
+	{
1753
+		return $this->get('TXN_ID');
1754
+	}
1755
+
1756
+
1757
+	/**
1758
+	 * @return int
1759
+	 * @throws EE_Error
1760
+	 */
1761
+	public function ticket_ID()
1762
+	{
1763
+		return $this->get('TKT_ID');
1764
+	}
1765
+
1766
+
1767
+	/**
1768
+	 *        Set Registration Code
1769
+	 *
1770
+	 * @access    public
1771
+	 * @param    string  $REG_code Registration Code
1772
+	 * @param    boolean $use_default
1773
+	 * @throws EE_Error
1774
+	 */
1775
+	public function set_reg_code($REG_code, $use_default = false)
1776
+	{
1777
+		if (empty($REG_code)) {
1778
+			EE_Error::add_error(
1779
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1780
+				__FILE__,
1781
+				__FUNCTION__,
1782
+				__LINE__
1783
+			);
1784
+			return;
1785
+		}
1786
+		if (! $this->reg_code()) {
1787
+			parent::set('REG_code', $REG_code, $use_default);
1788
+		} else {
1789
+			EE_Error::doing_it_wrong(
1790
+				__CLASS__ . '::' . __FUNCTION__,
1791
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1792
+				'4.6.0'
1793
+			);
1794
+		}
1795
+	}
1796
+
1797
+
1798
+	/**
1799
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1800
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1801
+	 *    $registration->transaction()->registrations();
1802
+	 *
1803
+	 * @since 4.5.0
1804
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1805
+	 * @throws EE_Error
1806
+	 */
1807
+	public function get_all_other_registrations_in_group()
1808
+	{
1809
+		if ($this->group_size() < 2) {
1810
+			return array();
1811
+		}
1812
+
1813
+		$query[0] = array(
1814
+			'TXN_ID' => $this->transaction_ID(),
1815
+			'REG_ID' => array('!=', $this->ID()),
1816
+			'TKT_ID' => $this->ticket_ID(),
1817
+		);
1818
+		/** @var EE_Registration[] $registrations */
1819
+		$registrations = $this->get_model()->get_all($query);
1820
+		return $registrations;
1821
+	}
1822
+
1823
+	/**
1824
+	 * Return the link to the admin details for the object.
1825
+	 *
1826
+	 * @return string
1827
+	 * @throws EE_Error
1828
+	 */
1829
+	public function get_admin_details_link()
1830
+	{
1831
+		EE_Registry::instance()->load_helper('URL');
1832
+		return EEH_URL::add_query_args_and_nonce(
1833
+			array(
1834
+				'page'    => 'espresso_registrations',
1835
+				'action'  => 'view_registration',
1836
+				'_REG_ID' => $this->ID(),
1837
+			),
1838
+			admin_url('admin.php')
1839
+		);
1840
+	}
1841
+
1842
+	/**
1843
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1844
+	 *
1845
+	 * @return string
1846
+	 * @throws EE_Error
1847
+	 */
1848
+	public function get_admin_edit_link()
1849
+	{
1850
+		return $this->get_admin_details_link();
1851
+	}
1852
+
1853
+	/**
1854
+	 * Returns the link to a settings page for the object.
1855
+	 *
1856
+	 * @return string
1857
+	 * @throws EE_Error
1858
+	 */
1859
+	public function get_admin_settings_link()
1860
+	{
1861
+		return $this->get_admin_details_link();
1862
+	}
1863
+
1864
+	/**
1865
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1866
+	 *
1867
+	 * @return string
1868
+	 */
1869
+	public function get_admin_overview_link()
1870
+	{
1871
+		EE_Registry::instance()->load_helper('URL');
1872
+		return EEH_URL::add_query_args_and_nonce(
1873
+			array(
1874
+				'page' => 'espresso_registrations',
1875
+			),
1876
+			admin_url('admin.php')
1877
+		);
1878
+	}
1879
+
1880
+
1881
+	/**
1882
+	 * @param array $query_params
1883
+	 *
1884
+	 * @return \EE_Registration[]
1885
+	 * @throws EE_Error
1886
+	 */
1887
+	public function payments($query_params = array())
1888
+	{
1889
+		return $this->get_many_related('Payment', $query_params);
1890
+	}
1891
+
1892
+
1893
+	/**
1894
+	 * @param array $query_params
1895
+	 *
1896
+	 * @return \EE_Registration_Payment[]
1897
+	 * @throws EE_Error
1898
+	 */
1899
+	public function registration_payments($query_params = array())
1900
+	{
1901
+		return $this->get_many_related('Registration_Payment', $query_params);
1902
+	}
1903
+
1904
+
1905
+	/**
1906
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1907
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1908
+	 *
1909
+	 * @return EE_Payment_Method|null
1910
+	 */
1911
+	public function payment_method()
1912
+	{
1913
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1914
+	}
1915
+
1916
+
1917
+	/**
1918
+	 * @return \EE_Line_Item
1919
+	 * @throws EntityNotFoundException
1920
+	 * @throws EE_Error
1921
+	 */
1922
+	public function ticket_line_item()
1923
+	{
1924
+		$ticket = $this->ticket();
1925
+		$transaction = $this->transaction();
1926
+		$line_item = null;
1927
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1928
+			$transaction->total_line_item(),
1929
+			'Ticket',
1930
+			array($ticket->ID())
1931
+		);
1932
+		foreach ($ticket_line_items as $ticket_line_item) {
1933
+			if ($ticket_line_item instanceof \EE_Line_Item
1934
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1935
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1936
+			) {
1937
+				$line_item = $ticket_line_item;
1938
+				break;
1939
+			}
1940
+		}
1941
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1942
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1943
+		}
1944
+		return $line_item;
1945
+	}
1946
+
1947
+
1948
+	/**
1949
+	 * Soft Deletes this model object.
1950
+	 *
1951
+	 * @return boolean | int
1952
+	 * @throws RuntimeException
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	public function delete()
1956
+	{
1957
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1958
+			$this->set_status(EEM_Registration::status_id_cancelled);
1959
+		}
1960
+		return parent::delete();
1961
+	}
1962
+
1963
+
1964
+	/**
1965
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1966
+	 *
1967
+	 * @throws EE_Error
1968
+	 * @throws RuntimeException
1969
+	 */
1970
+	public function restore()
1971
+	{
1972
+		$previous_status = $this->get_extra_meta(
1973
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1974
+			true,
1975
+			EEM_Registration::status_id_cancelled
1976
+		);
1977
+		if ($previous_status) {
1978
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1979
+			$this->set_status($previous_status);
1980
+		}
1981
+		return parent::restore();
1982
+	}
1983
+
1984
+
1985
+	/**
1986
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1987
+	 *
1988
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1989
+	 *                                           depending on whether the reg status changes to or from "Approved"
1990
+	 * @return boolean whether the Registration status was updated
1991
+	 * @throws EE_Error
1992
+	 * @throws RuntimeException
1993
+	 */
1994
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1995
+	{
1996
+		$paid = $this->paid();
1997
+		$price = $this->final_price();
1998
+		switch (true) {
1999
+			// overpaid or paid
2000
+			case EEH_Money::compare_floats($paid, $price, '>'):
2001
+			case EEH_Money::compare_floats($paid, $price):
2002
+				$new_status = EEM_Registration::status_id_approved;
2003
+				break;
2004
+			//  underpaid
2005
+			case EEH_Money::compare_floats($paid, $price, '<'):
2006
+				$new_status = EEM_Registration::status_id_pending_payment;
2007
+				break;
2008
+			// uhhh Houston...
2009
+			default:
2010
+				throw new RuntimeException(
2011
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2012
+				);
2013
+		}
2014
+		if ($new_status !== $this->status_ID()) {
2015
+			if ($trigger_set_status_logic) {
2016
+				return $this->set_status($new_status);
2017
+			}
2018
+			parent::set('STS_ID', $new_status);
2019
+			return true;
2020
+		}
2021
+		return false;
2022
+	}
2023
+
2024
+
2025
+	/*************************** DEPRECATED ***************************/
2026
+
2027
+
2028
+	/**
2029
+	 * @deprecated
2030
+	 * @since     4.7.0
2031
+	 * @access    public
2032
+	 */
2033
+	public function price_paid()
2034
+	{
2035
+		EE_Error::doing_it_wrong(
2036
+			'EE_Registration::price_paid()',
2037
+			esc_html__(
2038
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2039
+				'event_espresso'
2040
+			),
2041
+			'4.7.0'
2042
+		);
2043
+		return $this->final_price();
2044
+	}
2045
+
2046
+
2047
+	/**
2048
+	 * @deprecated
2049
+	 * @since     4.7.0
2050
+	 * @access    public
2051
+	 * @param    float $REG_final_price
2052
+	 * @throws EE_Error
2053
+	 * @throws RuntimeException
2054
+	 */
2055
+	public function set_price_paid($REG_final_price = 0.00)
2056
+	{
2057
+		EE_Error::doing_it_wrong(
2058
+			'EE_Registration::set_price_paid()',
2059
+			esc_html__(
2060
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2061
+				'event_espresso'
2062
+			),
2063
+			'4.7.0'
2064
+		);
2065
+		$this->set_final_price($REG_final_price);
2066
+	}
2067
+
2068
+
2069
+	/**
2070
+	 * @deprecated
2071
+	 * @since 4.7.0
2072
+	 * @return string
2073
+	 * @throws EE_Error
2074
+	 */
2075
+	public function pretty_price_paid()
2076
+	{
2077
+		EE_Error::doing_it_wrong(
2078
+			'EE_Registration::pretty_price_paid()',
2079
+			esc_html__(
2080
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2081
+				'event_espresso'
2082
+			),
2083
+			'4.7.0'
2084
+		);
2085
+		return $this->pretty_final_price();
2086
+	}
2087
+
2088
+
2089
+	/**
2090
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2091
+	 *
2092
+	 * @deprecated 4.9.17
2093
+	 * @return EE_Datetime
2094
+	 * @throws EE_Error
2095
+	 * @throws EntityNotFoundException
2096
+	 */
2097
+	public function get_related_primary_datetime()
2098
+	{
2099
+		EE_Error::doing_it_wrong(
2100
+			__METHOD__,
2101
+			esc_html__(
2102
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2103
+				'event_espresso'
2104
+			),
2105
+			'4.9.17',
2106
+			'5.0.0'
2107
+		);
2108
+		return $this->event()->primary_datetime();
2109
+	}
2110
+
2111
+	/**
2112
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2113
+	 * @since 4.10.12.p
2114
+	 * @return string
2115
+	 * @throws EE_Error
2116
+	 * @throws InvalidArgumentException
2117
+	 * @throws InvalidDataTypeException
2118
+	 * @throws InvalidInterfaceException
2119
+	 * @throws ReflectionException
2120
+	 */
2121
+	public function name()
2122
+	{
2123
+		return $this->attendeeName();
2124
+	}
2125 2125
 }
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_Page.core.php 1 patch
Indentation   +2641 added lines, -2641 removed lines patch added patch discarded remove patch
@@ -19,2645 +19,2645 @@
 block discarded – undo
19 19
 class Events_Admin_Page extends EE_Admin_Page_CPT
20 20
 {
21 21
 
22
-    /**
23
-     * This will hold the event object for event_details screen.
24
-     *
25
-     * @access protected
26
-     * @var EE_Event $_event
27
-     */
28
-    protected $_event;
29
-
30
-
31
-    /**
32
-     * This will hold the category object for category_details screen.
33
-     *
34
-     * @var stdClass $_category
35
-     */
36
-    protected $_category;
37
-
38
-
39
-    /**
40
-     * This will hold the event model instance
41
-     *
42
-     * @var EEM_Event $_event_model
43
-     */
44
-    protected $_event_model;
45
-
46
-
47
-    /**
48
-     * @var EE_Event
49
-     */
50
-    protected $_cpt_model_obj = false;
51
-
52
-
53
-    /**
54
-     * @var NodeGroupDao
55
-     */
56
-    protected $model_obj_node_group_persister;
57
-
58
-    /**
59
-     * Initialize page props for this admin page group.
60
-     */
61
-    protected function _init_page_props()
62
-    {
63
-        $this->page_slug = EVENTS_PG_SLUG;
64
-        $this->page_label = EVENTS_LABEL;
65
-        $this->_admin_base_url = EVENTS_ADMIN_URL;
66
-        $this->_admin_base_path = EVENTS_ADMIN;
67
-        $this->_cpt_model_names = array(
68
-            'create_new' => 'EEM_Event',
69
-            'edit'       => 'EEM_Event',
70
-        );
71
-        $this->_cpt_edit_routes = array(
72
-            'espresso_events' => 'edit',
73
-        );
74
-        add_action(
75
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
76
-            array($this, 'verify_event_edit'),
77
-            10,
78
-            2
79
-        );
80
-    }
81
-
82
-
83
-    /**
84
-     * Sets the ajax hooks used for this admin page group.
85
-     */
86
-    protected function _ajax_hooks()
87
-    {
88
-        add_action('wp_ajax_ee_save_timezone_setting', array($this, 'save_timezonestring_setting'));
89
-    }
90
-
91
-
92
-    /**
93
-     * Sets the page properties for this admin page group.
94
-     */
95
-    protected function _define_page_props()
96
-    {
97
-        $this->_admin_page_title = EVENTS_LABEL;
98
-        $this->_labels = array(
99
-            'buttons'      => array(
100
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
101
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
102
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
103
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
104
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
105
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
106
-            ),
107
-            'editor_title' => array(
108
-                'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
109
-            ),
110
-            'publishbox'   => array(
111
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
112
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
113
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
114
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
115
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
116
-            ),
117
-        );
118
-    }
119
-
120
-
121
-    /**
122
-     * Sets the page routes property for this admin page group.
123
-     */
124
-    protected function _set_page_routes()
125
-    {
126
-        // load formatter helper
127
-        // load field generator helper
128
-        // is there a evt_id in the request?
129
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
130
-            ? $this->_req_data['EVT_ID']
131
-            : 0;
132
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
133
-        $this->_page_routes = array(
134
-            'default'                       => array(
135
-                'func'       => '_events_overview_list_table',
136
-                'capability' => 'ee_read_events',
137
-            ),
138
-            'create_new'                    => array(
139
-                'func'       => '_create_new_cpt_item',
140
-                'capability' => 'ee_edit_events',
141
-            ),
142
-            'edit'                          => array(
143
-                'func'       => '_edit_cpt_item',
144
-                'capability' => 'ee_edit_event',
145
-                'obj_id'     => $evt_id,
146
-            ),
147
-            'copy_event'                    => array(
148
-                'func'       => '_copy_events',
149
-                'capability' => 'ee_edit_event',
150
-                'obj_id'     => $evt_id,
151
-                'noheader'   => true,
152
-            ),
153
-            'trash_event'                   => array(
154
-                'func'       => '_trash_or_restore_event',
155
-                'args'       => array('event_status' => 'trash'),
156
-                'capability' => 'ee_delete_event',
157
-                'obj_id'     => $evt_id,
158
-                'noheader'   => true,
159
-            ),
160
-            'trash_events'                  => array(
161
-                'func'       => '_trash_or_restore_events',
162
-                'args'       => array('event_status' => 'trash'),
163
-                'capability' => 'ee_delete_events',
164
-                'noheader'   => true,
165
-            ),
166
-            'restore_event'                 => array(
167
-                'func'       => '_trash_or_restore_event',
168
-                'args'       => array('event_status' => 'draft'),
169
-                'capability' => 'ee_delete_event',
170
-                'obj_id'     => $evt_id,
171
-                'noheader'   => true,
172
-            ),
173
-            'restore_events'                => array(
174
-                'func'       => '_trash_or_restore_events',
175
-                'args'       => array('event_status' => 'draft'),
176
-                'capability' => 'ee_delete_events',
177
-                'noheader'   => true,
178
-            ),
179
-            'delete_event'                  => array(
180
-                'func'       => '_delete_event',
181
-                'capability' => 'ee_delete_event',
182
-                'obj_id'     => $evt_id,
183
-                'noheader'   => true,
184
-            ),
185
-            'delete_events'                 => array(
186
-                'func'       => '_delete_events',
187
-                'capability' => 'ee_delete_events',
188
-                'noheader'   => true,
189
-            ),
190
-            'view_report'                   => array(
191
-                'func'      => '_view_report',
192
-                'capablity' => 'ee_edit_events',
193
-            ),
194
-            'default_event_settings'        => array(
195
-                'func'       => '_default_event_settings',
196
-                'capability' => 'manage_options',
197
-            ),
198
-            'update_default_event_settings' => array(
199
-                'func'       => '_update_default_event_settings',
200
-                'capability' => 'manage_options',
201
-                'noheader'   => true,
202
-            ),
203
-            'template_settings'             => array(
204
-                'func'       => '_template_settings',
205
-                'capability' => 'manage_options',
206
-            ),
207
-            // event category tab related
208
-            'add_category'                  => array(
209
-                'func'       => '_category_details',
210
-                'capability' => 'ee_edit_event_category',
211
-                'args'       => array('add'),
212
-            ),
213
-            'edit_category'                 => array(
214
-                'func'       => '_category_details',
215
-                'capability' => 'ee_edit_event_category',
216
-                'args'       => array('edit'),
217
-            ),
218
-            'delete_categories'             => array(
219
-                'func'       => '_delete_categories',
220
-                'capability' => 'ee_delete_event_category',
221
-                'noheader'   => true,
222
-            ),
223
-            'delete_category'               => array(
224
-                'func'       => '_delete_categories',
225
-                'capability' => 'ee_delete_event_category',
226
-                'noheader'   => true,
227
-            ),
228
-            'insert_category'               => array(
229
-                'func'       => '_insert_or_update_category',
230
-                'args'       => array('new_category' => true),
231
-                'capability' => 'ee_edit_event_category',
232
-                'noheader'   => true,
233
-            ),
234
-            'update_category'               => array(
235
-                'func'       => '_insert_or_update_category',
236
-                'args'       => array('new_category' => false),
237
-                'capability' => 'ee_edit_event_category',
238
-                'noheader'   => true,
239
-            ),
240
-            'category_list'                 => array(
241
-                'func'       => '_category_list_table',
242
-                'capability' => 'ee_manage_event_categories',
243
-            ),
244
-            'preview_deletion' => [
245
-                'func' => 'previewDeletion',
246
-                'capability' => 'ee_delete_events',
247
-            ],
248
-            'confirm_deletion' => [
249
-                'func' => 'confirmDeletion',
250
-                'capability' => 'ee_delete_events',
251
-                'noheader' => true,
252
-            ]
253
-        );
254
-    }
255
-
256
-
257
-    /**
258
-     * Set the _page_config property for this admin page group.
259
-     */
260
-    protected function _set_page_config()
261
-    {
262
-        $this->_page_config = array(
263
-            'default'                => array(
264
-                'nav'           => array(
265
-                    'label' => esc_html__('Overview', 'event_espresso'),
266
-                    'order' => 10,
267
-                ),
268
-                'list_table'    => 'Events_Admin_List_Table',
269
-                'help_tabs'     => array(
270
-                    'events_overview_help_tab'                       => array(
271
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
272
-                        'filename' => 'events_overview',
273
-                    ),
274
-                    'events_overview_table_column_headings_help_tab' => array(
275
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
276
-                        'filename' => 'events_overview_table_column_headings',
277
-                    ),
278
-                    'events_overview_filters_help_tab'               => array(
279
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
280
-                        'filename' => 'events_overview_filters',
281
-                    ),
282
-                    'events_overview_view_help_tab'                  => array(
283
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
284
-                        'filename' => 'events_overview_views',
285
-                    ),
286
-                    'events_overview_other_help_tab'                 => array(
287
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
288
-                        'filename' => 'events_overview_other',
289
-                    ),
290
-                ),
291
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
292
-                // 'help_tour'     => array(
293
-                //     'Event_Overview_Help_Tour',
294
-                //     // 'New_Features_Test_Help_Tour' for testing multiple help tour
295
-                // ),
296
-                'qtips'         => array(
297
-                    'EE_Event_List_Table_Tips',
298
-                ),
299
-                'require_nonce' => false,
300
-            ),
301
-            'create_new'             => array(
302
-                'nav'           => array(
303
-                    'label'      => esc_html__('Add Event', 'event_espresso'),
304
-                    'order'      => 5,
305
-                    'persistent' => false,
306
-                ),
307
-                'metaboxes'     => array('_register_event_editor_meta_boxes'),
308
-                'help_tabs'     => array(
309
-                    'event_editor_help_tab'                            => array(
310
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
311
-                        'filename' => 'event_editor',
312
-                    ),
313
-                    'event_editor_title_richtexteditor_help_tab'       => array(
314
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
315
-                        'filename' => 'event_editor_title_richtexteditor',
316
-                    ),
317
-                    'event_editor_venue_details_help_tab'              => array(
318
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
319
-                        'filename' => 'event_editor_venue_details',
320
-                    ),
321
-                    'event_editor_event_datetimes_help_tab'            => array(
322
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
323
-                        'filename' => 'event_editor_event_datetimes',
324
-                    ),
325
-                    'event_editor_event_tickets_help_tab'              => array(
326
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
327
-                        'filename' => 'event_editor_event_tickets',
328
-                    ),
329
-                    'event_editor_event_registration_options_help_tab' => array(
330
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
331
-                        'filename' => 'event_editor_event_registration_options',
332
-                    ),
333
-                    'event_editor_tags_categories_help_tab'            => array(
334
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
335
-                        'filename' => 'event_editor_tags_categories',
336
-                    ),
337
-                    'event_editor_questions_registrants_help_tab'      => array(
338
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
339
-                        'filename' => 'event_editor_questions_registrants',
340
-                    ),
341
-                    'event_editor_save_new_event_help_tab'             => array(
342
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
343
-                        'filename' => 'event_editor_save_new_event',
344
-                    ),
345
-                    'event_editor_other_help_tab'                      => array(
346
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
347
-                        'filename' => 'event_editor_other',
348
-                    ),
349
-                ),
350
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
351
-                // 'help_tour'     => array(
352
-                //     'Event_Editor_Help_Tour',
353
-                // ),
354
-                'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
355
-                'require_nonce' => false,
356
-            ),
357
-            'edit'                   => array(
358
-                'nav'           => array(
359
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
360
-                    'order'      => 5,
361
-                    'persistent' => false,
362
-                    'url'        => isset($this->_req_data['post'])
363
-                        ? EE_Admin_Page::add_query_args_and_nonce(
364
-                            array('post' => $this->_req_data['post'], 'action' => 'edit'),
365
-                            $this->_current_page_view_url
366
-                        )
367
-                        : $this->_admin_base_url,
368
-                ),
369
-                'metaboxes'     => array('_register_event_editor_meta_boxes'),
370
-                'help_tabs'     => array(
371
-                    'event_editor_help_tab'                            => array(
372
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
373
-                        'filename' => 'event_editor',
374
-                    ),
375
-                    'event_editor_title_richtexteditor_help_tab'       => array(
376
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
377
-                        'filename' => 'event_editor_title_richtexteditor',
378
-                    ),
379
-                    'event_editor_venue_details_help_tab'              => array(
380
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
381
-                        'filename' => 'event_editor_venue_details',
382
-                    ),
383
-                    'event_editor_event_datetimes_help_tab'            => array(
384
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
385
-                        'filename' => 'event_editor_event_datetimes',
386
-                    ),
387
-                    'event_editor_event_tickets_help_tab'              => array(
388
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
389
-                        'filename' => 'event_editor_event_tickets',
390
-                    ),
391
-                    'event_editor_event_registration_options_help_tab' => array(
392
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
393
-                        'filename' => 'event_editor_event_registration_options',
394
-                    ),
395
-                    'event_editor_tags_categories_help_tab'            => array(
396
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
397
-                        'filename' => 'event_editor_tags_categories',
398
-                    ),
399
-                    'event_editor_questions_registrants_help_tab'      => array(
400
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
401
-                        'filename' => 'event_editor_questions_registrants',
402
-                    ),
403
-                    'event_editor_save_new_event_help_tab'             => array(
404
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
405
-                        'filename' => 'event_editor_save_new_event',
406
-                    ),
407
-                    'event_editor_other_help_tab'                      => array(
408
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
409
-                        'filename' => 'event_editor_other',
410
-                    ),
411
-                ),
412
-                'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
413
-                'require_nonce' => false,
414
-            ),
415
-            'default_event_settings' => array(
416
-                'nav'           => array(
417
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
418
-                    'order' => 40,
419
-                ),
420
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
421
-                'labels'        => array(
422
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
423
-                ),
424
-                'help_tabs'     => array(
425
-                    'default_settings_help_tab'        => array(
426
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
427
-                        'filename' => 'events_default_settings',
428
-                    ),
429
-                    'default_settings_status_help_tab' => array(
430
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
431
-                        'filename' => 'events_default_settings_status',
432
-                    ),
433
-                    'default_maximum_tickets_help_tab' => array(
434
-                        'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
435
-                        'filename' => 'events_default_settings_max_tickets',
436
-                    ),
437
-                ),
438
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
439
-                // 'help_tour'     => array('Event_Default_Settings_Help_Tour'),
440
-                'require_nonce' => false,
441
-            ),
442
-            // template settings
443
-            'template_settings'      => array(
444
-                'nav'           => array(
445
-                    'label' => esc_html__('Templates', 'event_espresso'),
446
-                    'order' => 30,
447
-                ),
448
-                'metaboxes'     => $this->_default_espresso_metaboxes,
449
-                'help_tabs'     => array(
450
-                    'general_settings_templates_help_tab' => array(
451
-                        'title'    => esc_html__('Templates', 'event_espresso'),
452
-                        'filename' => 'general_settings_templates',
453
-                    ),
454
-                ),
455
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
456
-                // 'help_tour'     => array('Templates_Help_Tour'),
457
-                'require_nonce' => false,
458
-            ),
459
-            // event category stuff
460
-            'add_category'           => array(
461
-                'nav'           => array(
462
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
463
-                    'order'      => 15,
464
-                    'persistent' => false,
465
-                ),
466
-                'help_tabs'     => array(
467
-                    'add_category_help_tab' => array(
468
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
469
-                        'filename' => 'events_add_category',
470
-                    ),
471
-                ),
472
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
473
-                // 'help_tour'     => array('Event_Add_Category_Help_Tour'),
474
-                'metaboxes'     => array('_publish_post_box'),
475
-                'require_nonce' => false,
476
-            ),
477
-            'edit_category'          => array(
478
-                'nav'           => array(
479
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
480
-                    'order'      => 15,
481
-                    'persistent' => false,
482
-                    'url'        => isset($this->_req_data['EVT_CAT_ID'])
483
-                        ? add_query_arg(
484
-                            array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID']),
485
-                            $this->_current_page_view_url
486
-                        )
487
-                        : $this->_admin_base_url,
488
-                ),
489
-                'help_tabs'     => array(
490
-                    'edit_category_help_tab' => array(
491
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
492
-                        'filename' => 'events_edit_category',
493
-                    ),
494
-                ),
495
-                /*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
496
-                'metaboxes'     => array('_publish_post_box'),
497
-                'require_nonce' => false,
498
-            ),
499
-            'category_list'          => array(
500
-                'nav'           => array(
501
-                    'label' => esc_html__('Categories', 'event_espresso'),
502
-                    'order' => 20,
503
-                ),
504
-                'list_table'    => 'Event_Categories_Admin_List_Table',
505
-                'help_tabs'     => array(
506
-                    'events_categories_help_tab'                       => array(
507
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
508
-                        'filename' => 'events_categories',
509
-                    ),
510
-                    'events_categories_table_column_headings_help_tab' => array(
511
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'events_categories_table_column_headings',
513
-                    ),
514
-                    'events_categories_view_help_tab'                  => array(
515
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
516
-                        'filename' => 'events_categories_views',
517
-                    ),
518
-                    'events_categories_other_help_tab'                 => array(
519
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
520
-                        'filename' => 'events_categories_other',
521
-                    ),
522
-                ),
523
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
524
-                // 'help_tour'     => array(
525
-                //     'Event_Categories_Help_Tour',
526
-                // ),
527
-                'metaboxes'     => $this->_default_espresso_metaboxes,
528
-                'require_nonce' => false,
529
-            ),
530
-            'preview_deletion'           => array(
531
-                'nav'           => array(
532
-                    'label'      => esc_html__('Preview Deletion', 'event_espresso'),
533
-                    'order'      => 15,
534
-                    'persistent' => false,
535
-                    'url'        => '',
536
-                ),
537
-                'require_nonce' => false
538
-            )
539
-        );
540
-    }
541
-
542
-
543
-    /**
544
-     * Used to register any global screen options if necessary for every route in this admin page group.
545
-     */
546
-    protected function _add_screen_options()
547
-    {
548
-    }
549
-
550
-
551
-    /**
552
-     * Implementing the screen options for the 'default' route.
553
-     */
554
-    protected function _add_screen_options_default()
555
-    {
556
-        $this->_per_page_screen_option();
557
-    }
558
-
559
-
560
-    /**
561
-     * Implementing screen options for the category list route.
562
-     */
563
-    protected function _add_screen_options_category_list()
564
-    {
565
-        $page_title = $this->_admin_page_title;
566
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
567
-        $this->_per_page_screen_option();
568
-        $this->_admin_page_title = $page_title;
569
-    }
570
-
571
-
572
-    /**
573
-     * Used to register any global feature pointers for the admin page group.
574
-     */
575
-    protected function _add_feature_pointers()
576
-    {
577
-    }
578
-
579
-
580
-    /**
581
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
582
-     */
583
-    public function load_scripts_styles()
584
-    {
585
-        wp_register_style(
586
-            'events-admin-css',
587
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
588
-            array(),
589
-            EVENT_ESPRESSO_VERSION
590
-        );
591
-        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION);
592
-        wp_enqueue_style('events-admin-css');
593
-        wp_enqueue_style('ee-cat-admin');
594
-        // todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
595
-        // registers for all views
596
-        // scripts
597
-        wp_register_script(
598
-            'event_editor_js',
599
-            EVENTS_ASSETS_URL . 'event_editor.js',
600
-            array('ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'),
601
-            EVENT_ESPRESSO_VERSION,
602
-            true
603
-        );
604
-    }
605
-
606
-
607
-    /**
608
-     * Enqueuing scripts and styles specific to this view
609
-     */
610
-    public function load_scripts_styles_create_new()
611
-    {
612
-        $this->load_scripts_styles_edit();
613
-    }
614
-
615
-
616
-    /**
617
-     * Enqueuing scripts and styles specific to this view
618
-     */
619
-    public function load_scripts_styles_edit()
620
-    {
621
-        // styles
622
-        wp_enqueue_style('espresso-ui-theme');
623
-        wp_register_style(
624
-            'event-editor-css',
625
-            EVENTS_ASSETS_URL . 'event-editor.css',
626
-            array('ee-admin-css'),
627
-            EVENT_ESPRESSO_VERSION
628
-        );
629
-        wp_enqueue_style('event-editor-css');
630
-        // scripts
631
-        wp_register_script(
632
-            'event-datetime-metabox',
633
-            EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
634
-            array('event_editor_js', 'ee-datepicker'),
635
-            EVENT_ESPRESSO_VERSION
636
-        );
637
-        wp_enqueue_script('event-datetime-metabox');
638
-    }
639
-
640
-
641
-    /**
642
-     * Populating the _views property for the category list table view.
643
-     */
644
-    protected function _set_list_table_views_category_list()
645
-    {
646
-        $this->_views = array(
647
-            'all' => array(
648
-                'slug'        => 'all',
649
-                'label'       => esc_html__('All', 'event_espresso'),
650
-                'count'       => 0,
651
-                'bulk_action' => array(
652
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
653
-                ),
654
-            ),
655
-        );
656
-    }
657
-
658
-
659
-    /**
660
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
661
-     */
662
-    public function admin_init()
663
-    {
664
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
665
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
666
-            'event_espresso'
667
-        );
668
-    }
669
-
670
-
671
-    /**
672
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
673
-     * group.
674
-     */
675
-    public function admin_notices()
676
-    {
677
-    }
678
-
679
-
680
-    /**
681
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
682
-     * this admin page group.
683
-     */
684
-    public function admin_footer_scripts()
685
-    {
686
-    }
687
-
688
-
689
-    /**
690
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
691
-     * warning (via EE_Error::add_error());
692
-     *
693
-     * @param  EE_Event $event Event object
694
-     * @param string    $req_type
695
-     * @return void
696
-     * @throws EE_Error
697
-     * @access public
698
-     */
699
-    public function verify_event_edit($event = null, $req_type = '')
700
-    {
701
-        // don't need to do this when processing
702
-        if (! empty($req_type)) {
703
-            return;
704
-        }
705
-        // no event?
706
-        if (empty($event)) {
707
-            // set event
708
-            $event = $this->_cpt_model_obj;
709
-        }
710
-        // STILL no event?
711
-        if (! $event instanceof EE_Event) {
712
-            return;
713
-        }
714
-        $orig_status = $event->status();
715
-        // first check if event is active.
716
-        if ($orig_status === EEM_Event::cancelled
717
-            || $orig_status === EEM_Event::postponed
718
-            || $event->is_expired()
719
-            || $event->is_inactive()
720
-        ) {
721
-            return;
722
-        }
723
-        // made it here so it IS active... next check that any of the tickets are sold.
724
-        if ($event->is_sold_out(true)) {
725
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
726
-                EE_Error::add_attention(
727
-                    sprintf(
728
-                        esc_html__(
729
-                            'Please note that the Event Status has automatically been changed to %s because there are no more spaces available for this event.  However, this change is not permanent until you update the event.  You can change the status back to something else before updating if you wish.',
730
-                            'event_espresso'
731
-                        ),
732
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
733
-                    )
734
-                );
735
-            }
736
-            return;
737
-        } elseif ($orig_status === EEM_Event::sold_out) {
738
-            EE_Error::add_attention(
739
-                sprintf(
740
-                    esc_html__(
741
-                        'Please note that the Event Status has automatically been changed to %s because more spaces have become available for this event, most likely due to abandoned transactions freeing up reserved tickets.  However, this change is not permanent until you update the event. If you wish, you can change the status back to something else before updating.',
742
-                        'event_espresso'
743
-                    ),
744
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
745
-                )
746
-            );
747
-        }
748
-        // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
749
-        if (! $event->tickets_on_sale()) {
750
-            return;
751
-        }
752
-        // made it here so show warning
753
-        $this->_edit_event_warning();
754
-    }
755
-
756
-
757
-    /**
758
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
759
-     * When needed, hook this into a EE_Error::add_error() notice.
760
-     *
761
-     * @access protected
762
-     * @return void
763
-     */
764
-    protected function _edit_event_warning()
765
-    {
766
-        // we don't want to add warnings during these requests
767
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'editpost') {
768
-            return;
769
-        }
770
-        EE_Error::add_attention(
771
-            sprintf(
772
-                esc_html__(
773
-                    'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
774
-                    'event_espresso'
775
-                ),
776
-                '<a class="espresso-help-tab-lnk">',
777
-                '</a>'
778
-            )
779
-        );
780
-    }
781
-
782
-
783
-    /**
784
-     * When a user is creating a new event, notify them if they haven't set their timezone.
785
-     * Otherwise, do the normal logic
786
-     *
787
-     * @return string
788
-     * @throws \EE_Error
789
-     */
790
-    protected function _create_new_cpt_item()
791
-    {
792
-        $has_timezone_string = get_option('timezone_string');
793
-        // only nag them about setting their timezone if it's their first event, and they haven't already done it
794
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists(array())) {
795
-            EE_Error::add_attention(
796
-                sprintf(
797
-                    __(
798
-                        'Your website\'s timezone is currently set to a UTC offset. We recommend updating your timezone to a city or region near you before you create an event. Change your timezone now:%1$s%2$s%3$sChange Timezone%4$s',
799
-                        'event_espresso'
800
-                    ),
801
-                    '<br>',
802
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
803
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
804
-                    . '</select>',
805
-                    '<button class="button button-secondary timezone-submit">',
806
-                    '</button><span class="spinner"></span>'
807
-                ),
808
-                __FILE__,
809
-                __FUNCTION__,
810
-                __LINE__
811
-            );
812
-        }
813
-        return parent::_create_new_cpt_item();
814
-    }
815
-
816
-
817
-    /**
818
-     * Sets the _views property for the default route in this admin page group.
819
-     */
820
-    protected function _set_list_table_views_default()
821
-    {
822
-        $this->_views = array(
823
-            'all'   => array(
824
-                'slug'        => 'all',
825
-                'label'       => esc_html__('View All Events', 'event_espresso'),
826
-                'count'       => 0,
827
-                'bulk_action' => array(
828
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
829
-                ),
830
-            ),
831
-            'draft' => array(
832
-                'slug'        => 'draft',
833
-                'label'       => esc_html__('Draft', 'event_espresso'),
834
-                'count'       => 0,
835
-                'bulk_action' => array(
836
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
837
-                ),
838
-            ),
839
-        );
840
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
841
-            $this->_views['trash'] = array(
842
-                'slug'        => 'trash',
843
-                'label'       => esc_html__('Trash', 'event_espresso'),
844
-                'count'       => 0,
845
-                'bulk_action' => array(
846
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
847
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
848
-                ),
849
-            );
850
-        }
851
-    }
852
-
853
-
854
-    /**
855
-     * Provides the legend item array for the default list table view.
856
-     *
857
-     * @return array
858
-     */
859
-    protected function _event_legend_items()
860
-    {
861
-        $items = array(
862
-            'view_details'   => array(
863
-                'class' => 'dashicons dashicons-search',
864
-                'desc'  => esc_html__('View Event', 'event_espresso'),
865
-            ),
866
-            'edit_event'     => array(
867
-                'class' => 'ee-icon ee-icon-calendar-edit',
868
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
869
-            ),
870
-            'view_attendees' => array(
871
-                'class' => 'dashicons dashicons-groups',
872
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
873
-            ),
874
-        );
875
-        $items = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
876
-        $statuses = array(
877
-            'sold_out_status'  => array(
878
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
879
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
880
-            ),
881
-            'active_status'    => array(
882
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
883
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
884
-            ),
885
-            'upcoming_status'  => array(
886
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
887
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
888
-            ),
889
-            'postponed_status' => array(
890
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
891
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
892
-            ),
893
-            'cancelled_status' => array(
894
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
895
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
896
-            ),
897
-            'expired_status'   => array(
898
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
899
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
900
-            ),
901
-            'inactive_status'  => array(
902
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
903
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
904
-            ),
905
-        );
906
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
907
-        return array_merge($items, $statuses);
908
-    }
909
-
910
-
911
-    /**
912
-     * @return EEM_Event
913
-     */
914
-    private function _event_model()
915
-    {
916
-        if (! $this->_event_model instanceof EEM_Event) {
917
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
918
-        }
919
-        return $this->_event_model;
920
-    }
921
-
922
-
923
-    /**
924
-     * Adds extra buttons to the WP CPT permalink field row.
925
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
926
-     *
927
-     * @param  string $return    the current html
928
-     * @param  int    $id        the post id for the page
929
-     * @param  string $new_title What the title is
930
-     * @param  string $new_slug  what the slug is
931
-     * @return string            The new html string for the permalink area
932
-     */
933
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
934
-    {
935
-        // make sure this is only when editing
936
-        if (! empty($id)) {
937
-            $post = get_post($id);
938
-            $return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
939
-                       . esc_html__('Shortcode', 'event_espresso')
940
-                       . '</a> ';
941
-            $return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
942
-                       . $post->ID
943
-                       . ']">';
944
-        }
945
-        return $return;
946
-    }
947
-
948
-
949
-    /**
950
-     * _events_overview_list_table
951
-     * This contains the logic for showing the events_overview list
952
-     *
953
-     * @access protected
954
-     * @return void
955
-     * @throws \EE_Error
956
-     */
957
-    protected function _events_overview_list_table()
958
-    {
959
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
960
-        $this->_template_args['after_list_table'] = ! empty($this->_template_args['after_list_table'])
961
-            ? (array) $this->_template_args['after_list_table']
962
-            : array();
963
-        $this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
964
-                . EEH_Template::get_button_or_link(
965
-                    get_post_type_archive_link('espresso_events'),
966
-                    esc_html__("View Event Archive Page", "event_espresso"),
967
-                    'button'
968
-                );
969
-        $this->_template_args['after_list_table']['legend'] = $this->_display_legend($this->_event_legend_items());
970
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
971
-            'create_new',
972
-            'add',
973
-            array(),
974
-            'add-new-h2'
975
-        );
976
-        $this->display_admin_list_table_page_with_no_sidebar();
977
-    }
978
-
979
-
980
-    /**
981
-     * this allows for extra misc actions in the default WP publish box
982
-     *
983
-     * @return void
984
-     */
985
-    public function extra_misc_actions_publish_box()
986
-    {
987
-        $this->_generate_publish_box_extra_content();
988
-    }
989
-
990
-
991
-    /**
992
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
993
-     * saved.
994
-     * Typically you would use this to save any additional data.
995
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
996
-     * ALSO very important.  When a post transitions from scheduled to published,
997
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
998
-     * other meta saves. So MAKE sure that you handle this accordingly.
999
-     *
1000
-     * @access protected
1001
-     * @abstract
1002
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
1003
-     * @param  object $post    The post object of the cpt that was saved.
1004
-     * @return void
1005
-     * @throws \EE_Error
1006
-     */
1007
-    protected function _insert_update_cpt_item($post_id, $post)
1008
-    {
1009
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1010
-            // get out we're not processing an event save.
1011
-            return;
1012
-        }
1013
-        $event_values = array(
1014
-            'EVT_display_desc'                => ! empty($this->_req_data['display_desc']) ? 1 : 0,
1015
-            'EVT_display_ticket_selector'     => ! empty($this->_req_data['display_ticket_selector']) ? 1 : 0,
1016
-            'EVT_additional_limit'            => min(
1017
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1018
-                ! empty($this->_req_data['additional_limit']) ? $this->_req_data['additional_limit'] : null
1019
-            ),
1020
-            'EVT_default_registration_status' => ! empty($this->_req_data['EVT_default_registration_status'])
1021
-                ? $this->_req_data['EVT_default_registration_status']
1022
-                : EE_Registry::instance()->CFG->registration->default_STS_ID,
1023
-            'EVT_member_only'                 => ! empty($this->_req_data['member_only']) ? 1 : 0,
1024
-            'EVT_allow_overflow'              => ! empty($this->_req_data['EVT_allow_overflow']) ? 1 : 0,
1025
-            'EVT_timezone_string'             => ! empty($this->_req_data['timezone_string'])
1026
-                ? $this->_req_data['timezone_string'] : null,
1027
-            'EVT_external_URL'                => ! empty($this->_req_data['externalURL'])
1028
-                ? $this->_req_data['externalURL'] : null,
1029
-            'EVT_phone'                       => ! empty($this->_req_data['event_phone'])
1030
-                ? $this->_req_data['event_phone'] : null,
1031
-        );
1032
-        // update event
1033
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1034
-        // get event_object for other metaboxes... though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id ).. i have to setup where conditions to override the filters in the model that filter out autodraft and inherit statuses so we GET the inherit id!
1035
-        $get_one_where = array(
1036
-            $this->_event_model()->primary_key_name() => $post_id,
1037
-            'OR'                                      => array(
1038
-                'status'   => $post->post_status,
1039
-                // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1040
-                // but the returned object here has a status of "publish", so use the original post status as well
1041
-                'status*1' => $this->_req_data['original_post_status'],
1042
-            ),
1043
-        );
1044
-        $event = $this->_event_model()->get_one(array($get_one_where));
1045
-        // the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1046
-        $event_update_callbacks = apply_filters(
1047
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1048
-            array(
1049
-                array($this, '_default_venue_update'),
1050
-                array($this, '_default_tickets_update'),
1051
-            )
1052
-        );
1053
-        $att_success = true;
1054
-        foreach ($event_update_callbacks as $e_callback) {
1055
-            $_success = is_callable($e_callback)
1056
-                ? call_user_func($e_callback, $event, $this->_req_data)
1057
-                : false;
1058
-            // if ANY of these updates fail then we want the appropriate global error message
1059
-            $att_success = ! $att_success ? $att_success : $_success;
1060
-        }
1061
-        // any errors?
1062
-        if ($success && false === $att_success) {
1063
-            EE_Error::add_error(
1064
-                esc_html__(
1065
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1066
-                    'event_espresso'
1067
-                ),
1068
-                __FILE__,
1069
-                __FUNCTION__,
1070
-                __LINE__
1071
-            );
1072
-        } elseif ($success === false) {
1073
-            EE_Error::add_error(
1074
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1075
-                __FILE__,
1076
-                __FUNCTION__,
1077
-                __LINE__
1078
-            );
1079
-        }
1080
-    }
1081
-
1082
-
1083
-    /**
1084
-     * @see parent::restore_item()
1085
-     * @param int $post_id
1086
-     * @param int $revision_id
1087
-     */
1088
-    protected function _restore_cpt_item($post_id, $revision_id)
1089
-    {
1090
-        // copy existing event meta to new post
1091
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1092
-        if ($post_evt instanceof EE_Event) {
1093
-            // meta revision restore
1094
-            $post_evt->restore_revision($revision_id);
1095
-            // related objs restore
1096
-            $post_evt->restore_revision($revision_id, array('Venue', 'Datetime', 'Price'));
1097
-        }
1098
-    }
1099
-
1100
-
1101
-    /**
1102
-     * Attach the venue to the Event
1103
-     *
1104
-     * @param  \EE_Event $evtobj Event Object to add the venue to
1105
-     * @param  array     $data   The request data from the form
1106
-     * @return bool           Success or fail.
1107
-     */
1108
-    protected function _default_venue_update(\EE_Event $evtobj, $data)
1109
-    {
1110
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1111
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1112
-        $rows_affected = null;
1113
-        $venue_id = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1114
-        // very important.  If we don't have a venue name...
1115
-        // then we'll get out because not necessary to create empty venue
1116
-        if (empty($data['venue_title'])) {
1117
-            return false;
1118
-        }
1119
-        $venue_array = array(
1120
-            'VNU_wp_user'         => $evtobj->get('EVT_wp_user'),
1121
-            'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1122
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1123
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1124
-            'VNU_short_desc'      => ! empty($data['venue_short_description']) ? $data['venue_short_description']
1125
-                : null,
1126
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1127
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1128
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1129
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1130
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1131
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1132
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1133
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1134
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1135
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1136
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1137
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1138
-            'status'              => 'publish',
1139
-        );
1140
-        // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1141
-        if (! empty($venue_id)) {
1142
-            $update_where = array($venue_model->primary_key_name() => $venue_id);
1143
-            $rows_affected = $venue_model->update($venue_array, array($update_where));
1144
-            // we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1145
-            $evtobj->_add_relation_to($venue_id, 'Venue');
1146
-            return $rows_affected > 0 ? true : false;
1147
-        } else {
1148
-            // we insert the venue
1149
-            $venue_id = $venue_model->insert($venue_array);
1150
-            $evtobj->_add_relation_to($venue_id, 'Venue');
1151
-            return ! empty($venue_id) ? true : false;
1152
-        }
1153
-        // when we have the ancestor come in it's already been handled by the revision save.
1154
-    }
1155
-
1156
-
1157
-    /**
1158
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1159
-     *
1160
-     * @param  EE_Event $evtobj The Event object we're attaching data to
1161
-     * @param  array    $data   The request data from the form
1162
-     * @return array
1163
-     */
1164
-    protected function _default_tickets_update(EE_Event $evtobj, $data)
1165
-    {
1166
-        $success = true;
1167
-        $saved_dtt = null;
1168
-        $saved_tickets = array();
1169
-        $incoming_date_formats = array('Y-m-d', 'h:i a');
1170
-        foreach ($data['edit_event_datetimes'] as $row => $dtt) {
1171
-            // trim all values to ensure any excess whitespace is removed.
1172
-            $dtt = array_map('trim', $dtt);
1173
-            $dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end']
1174
-                : $dtt['DTT_EVT_start'];
1175
-            $datetime_values = array(
1176
-                'DTT_ID'        => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
1177
-                'DTT_EVT_start' => $dtt['DTT_EVT_start'],
1178
-                'DTT_EVT_end'   => $dtt['DTT_EVT_end'],
1179
-                'DTT_reg_limit' => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
1180
-                'DTT_order'     => $row,
1181
-            );
1182
-            // if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
1183
-            if (! empty($dtt['DTT_ID'])) {
1184
-                $DTM = EE_Registry::instance()
1185
-                                  ->load_model('Datetime', array($evtobj->get_timezone()))
1186
-                                  ->get_one_by_ID($dtt['DTT_ID']);
1187
-                $DTM->set_date_format($incoming_date_formats[0]);
1188
-                $DTM->set_time_format($incoming_date_formats[1]);
1189
-                foreach ($datetime_values as $field => $value) {
1190
-                    $DTM->set($field, $value);
1191
-                }
1192
-                // make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.  We need to do this so we dont' TRASH the parent DTT.
1193
-                $saved_dtts[ $DTM->ID() ] = $DTM;
1194
-            } else {
1195
-                $DTM = EE_Registry::instance()->load_class(
1196
-                    'Datetime',
1197
-                    array($datetime_values, $evtobj->get_timezone(), $incoming_date_formats),
1198
-                    false,
1199
-                    false
1200
-                );
1201
-                foreach ($datetime_values as $field => $value) {
1202
-                    $DTM->set($field, $value);
1203
-                }
1204
-            }
1205
-            $DTM->save();
1206
-            $DTT = $evtobj->_add_relation_to($DTM, 'Datetime');
1207
-            // load DTT helper
1208
-            // before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1209
-            if ($DTT->get_raw('DTT_EVT_start') > $DTT->get_raw('DTT_EVT_end')) {
1210
-                $DTT->set('DTT_EVT_end', $DTT->get('DTT_EVT_start'));
1211
-                $DTT = EEH_DTT_Helper::date_time_add($DTT, 'DTT_EVT_end', 'days');
1212
-                $DTT->save();
1213
-            }
1214
-            // now we got to make sure we add the new DTT_ID to the $saved_dtts array  because it is possible there was a new one created for the autosave.
1215
-            $saved_dtt = $DTT;
1216
-            $success = ! $success ? $success : $DTT;
1217
-            // if ANY of these updates fail then we want the appropriate global error message.
1218
-            // //todo this is actually sucky we need a better error message but this is what it is for now.
1219
-        }
1220
-        // no dtts get deleted so we don't do any of that logic here.
1221
-        // update tickets next
1222
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
1223
-        foreach ($data['edit_tickets'] as $row => $tkt) {
1224
-            $incoming_date_formats = array('Y-m-d', 'h:i a');
1225
-            $update_prices = false;
1226
-            $ticket_price = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1227
-                ? $data['edit_prices'][ $row ][1]['PRC_amount'] : 0;
1228
-            // trim inputs to ensure any excess whitespace is removed.
1229
-            $tkt = array_map('trim', $tkt);
1230
-            if (empty($tkt['TKT_start_date'])) {
1231
-                // let's use now in the set timezone.
1232
-                $now = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
1233
-                $tkt['TKT_start_date'] = $now->format($incoming_date_formats[0] . ' ' . $incoming_date_formats[1]);
1234
-            }
1235
-            if (empty($tkt['TKT_end_date'])) {
1236
-                // use the start date of the first datetime
1237
-                $dtt = $evtobj->first_datetime();
1238
-                $tkt['TKT_end_date'] = $dtt->start_date_and_time(
1239
-                    $incoming_date_formats[0],
1240
-                    $incoming_date_formats[1]
1241
-                );
1242
-            }
1243
-            $TKT_values = array(
1244
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
1245
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
1246
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
1247
-                'TKT_description' => ! empty($tkt['TKT_description']) ? $tkt['TKT_description'] : '',
1248
-                'TKT_start_date'  => $tkt['TKT_start_date'],
1249
-                'TKT_end_date'    => $tkt['TKT_end_date'],
1250
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
1251
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
1252
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
1253
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
1254
-                'TKT_row'         => $row,
1255
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : $row,
1256
-                'TKT_price'       => $ticket_price,
1257
-            );
1258
-            // if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
1259
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
1260
-                $TKT_values['TKT_ID'] = 0;
1261
-                $TKT_values['TKT_is_default'] = 0;
1262
-                $TKT_values['TKT_price'] = $ticket_price;
1263
-                $update_prices = true;
1264
-            }
1265
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
1266
-            // we actually do our saves a head of doing any add_relations to because its entirely possible that this ticket didn't removed or added to any datetime in the session but DID have it's items modified.
1267
-            // keep in mind that if the TKT has been sold (and we have changed pricing information), then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1268
-            if (! empty($tkt['TKT_ID'])) {
1269
-                $TKT = EE_Registry::instance()
1270
-                                  ->load_model('Ticket', array($evtobj->get_timezone()))
1271
-                                  ->get_one_by_ID($tkt['TKT_ID']);
1272
-                if ($TKT instanceof EE_Ticket) {
1273
-                    $ticket_sold = $TKT->count_related(
1274
-                        'Registration',
1275
-                        array(
1276
-                            array(
1277
-                                'STS_ID' => array(
1278
-                                    'NOT IN',
1279
-                                    array(EEM_Registration::status_id_incomplete),
1280
-                                ),
1281
-                            ),
1282
-                        )
1283
-                    ) > 0 ? true : false;
1284
-                    // let's just check the total price for the existing ticket and determine if it matches the new total price.  if they are different then we create a new ticket (if tkts sold) if they aren't different then we go ahead and modify existing ticket.
1285
-                    $create_new_TKT = $ticket_sold && $ticket_price != $TKT->get('TKT_price')
1286
-                                      && ! $TKT->get('TKT_deleted');
1287
-                    $TKT->set_date_format($incoming_date_formats[0]);
1288
-                    $TKT->set_time_format($incoming_date_formats[1]);
1289
-                    // set new values
1290
-                    foreach ($TKT_values as $field => $value) {
1291
-                        if ($field == 'TKT_qty') {
1292
-                            $TKT->set_qty($value);
1293
-                        } else {
1294
-                            $TKT->set($field, $value);
1295
-                        }
1296
-                    }
1297
-                    // if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
1298
-                    if ($create_new_TKT) {
1299
-                        // archive the old ticket first
1300
-                        $TKT->set('TKT_deleted', 1);
1301
-                        $TKT->save();
1302
-                        // make sure this ticket is still recorded in our saved_tkts so we don't run it through the regular trash routine.
1303
-                        $saved_tickets[ $TKT->ID() ] = $TKT;
1304
-                        // create new ticket that's a copy of the existing except a new id of course (and not archived) AND has the new TKT_price associated with it.
1305
-                        $TKT = clone $TKT;
1306
-                        $TKT->set('TKT_ID', 0);
1307
-                        $TKT->set('TKT_deleted', 0);
1308
-                        $TKT->set('TKT_price', $ticket_price);
1309
-                        $TKT->set('TKT_sold', 0);
1310
-                        // now we need to make sure that $new prices are created as well and attached to new ticket.
1311
-                        $update_prices = true;
1312
-                    }
1313
-                    // make sure price is set if it hasn't been already
1314
-                    $TKT->set('TKT_price', $ticket_price);
1315
-                }
1316
-            } else {
1317
-                // no TKT_id so a new TKT
1318
-                $TKT_values['TKT_price'] = $ticket_price;
1319
-                $TKT = EE_Registry::instance()->load_class('Ticket', array($TKT_values), false, false);
1320
-                if ($TKT instanceof EE_Ticket) {
1321
-                    // need to reset values to properly account for the date formats
1322
-                    $TKT->set_date_format($incoming_date_formats[0]);
1323
-                    $TKT->set_time_format($incoming_date_formats[1]);
1324
-                    $TKT->set_timezone($evtobj->get_timezone());
1325
-                    // set new values
1326
-                    foreach ($TKT_values as $field => $value) {
1327
-                        if ($field == 'TKT_qty') {
1328
-                            $TKT->set_qty($value);
1329
-                        } else {
1330
-                            $TKT->set($field, $value);
1331
-                        }
1332
-                    }
1333
-                    $update_prices = true;
1334
-                }
1335
-            }
1336
-            // cap ticket qty by datetime reg limits
1337
-            $TKT->set_qty(min($TKT->qty(), $TKT->qty('reg_limit')));
1338
-            // update ticket.
1339
-            $TKT->save();
1340
-            // before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1341
-            if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
1342
-                $TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
1343
-                $TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
1344
-                $TKT->save();
1345
-            }
1346
-            // initially let's add the ticket to the dtt
1347
-            $saved_dtt->_add_relation_to($TKT, 'Ticket');
1348
-            $saved_tickets[ $TKT->ID() ] = $TKT;
1349
-            // add prices to ticket
1350
-            $this->_add_prices_to_ticket($data['edit_prices'][ $row ], $TKT, $update_prices);
1351
-        }
1352
-        // however now we need to handle permanently deleting tickets via the ui.  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.  However, it does allow for deleting tickets that have no tickets sold, in which case we want to get rid of permanently because there is no need to save in db.
1353
-        $old_tickets = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
1354
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1355
-        foreach ($tickets_removed as $id) {
1356
-            $id = absint($id);
1357
-            // get the ticket for this id
1358
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
1359
-            // need to get all the related datetimes on this ticket and remove from every single one of them (remember this process can ONLY kick off if there are NO tkts_sold)
1360
-            $dtts = $tkt_to_remove->get_many_related('Datetime');
1361
-            foreach ($dtts as $dtt) {
1362
-                $tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
1363
-            }
1364
-            // need to do the same for prices (except these prices can also be deleted because again, tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1365
-            $tkt_to_remove->delete_related_permanently('Price');
1366
-            // finally let's delete this ticket (which should not be blocked at this point b/c we've removed all our relationships)
1367
-            $tkt_to_remove->delete_permanently();
1368
-        }
1369
-        return array($saved_dtt, $saved_tickets);
1370
-    }
1371
-
1372
-
1373
-    /**
1374
-     * This attaches a list of given prices to a ticket.
1375
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1376
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1377
-     * price info and prices are automatically "archived" via the ticket.
1378
-     *
1379
-     * @access  private
1380
-     * @param array     $prices     Array of prices from the form.
1381
-     * @param EE_Ticket $ticket     EE_Ticket object that prices are being attached to.
1382
-     * @param bool      $new_prices Whether attach existing incoming prices or create new ones.
1383
-     * @return  void
1384
-     */
1385
-    private function _add_prices_to_ticket($prices, EE_Ticket $ticket, $new_prices = false)
1386
-    {
1387
-        foreach ($prices as $row => $prc) {
1388
-            $PRC_values = array(
1389
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
1390
-                'PRT_ID'         => ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null,
1391
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
1392
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
1393
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
1394
-                'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1395
-                'PRC_order'      => $row,
1396
-            );
1397
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
1398
-                $PRC_values['PRC_ID'] = 0;
1399
-                $PRC = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
1400
-            } else {
1401
-                $PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
1402
-                // update this price with new values
1403
-                foreach ($PRC_values as $field => $newprc) {
1404
-                    $PRC->set($field, $newprc);
1405
-                }
1406
-                $PRC->save();
1407
-            }
1408
-            $ticket->_add_relation_to($PRC, 'Price');
1409
-        }
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * Add in our autosave ajax handlers
1415
-     *
1416
-     */
1417
-    protected function _ee_autosave_create_new()
1418
-    {
1419
-    }
1420
-
1421
-
1422
-    /**
1423
-     * More autosave handlers.
1424
-     */
1425
-    protected function _ee_autosave_edit()
1426
-    {
1427
-        return; // TEMPORARILY EXITING CAUSE THIS IS A TODO
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     *    _generate_publish_box_extra_content
1433
-     */
1434
-    private function _generate_publish_box_extra_content()
1435
-    {
1436
-        // load formatter helper
1437
-        // args for getting related registrations
1438
-        $approved_query_args = array(
1439
-            array(
1440
-                'REG_deleted' => 0,
1441
-                'STS_ID'      => EEM_Registration::status_id_approved,
1442
-            ),
1443
-        );
1444
-        $not_approved_query_args = array(
1445
-            array(
1446
-                'REG_deleted' => 0,
1447
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1448
-            ),
1449
-        );
1450
-        $pending_payment_query_args = array(
1451
-            array(
1452
-                'REG_deleted' => 0,
1453
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1454
-            ),
1455
-        );
1456
-        // publish box
1457
-        $publish_box_extra_args = array(
1458
-            'view_approved_reg_url'        => add_query_arg(
1459
-                array(
1460
-                    'action'      => 'default',
1461
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1462
-                    '_reg_status' => EEM_Registration::status_id_approved,
1463
-                ),
1464
-                REG_ADMIN_URL
1465
-            ),
1466
-            'view_not_approved_reg_url'    => add_query_arg(
1467
-                array(
1468
-                    'action'      => 'default',
1469
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1470
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1471
-                ),
1472
-                REG_ADMIN_URL
1473
-            ),
1474
-            'view_pending_payment_reg_url' => add_query_arg(
1475
-                array(
1476
-                    'action'      => 'default',
1477
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1478
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1479
-                ),
1480
-                REG_ADMIN_URL
1481
-            ),
1482
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1483
-                'Registration',
1484
-                $approved_query_args
1485
-            ),
1486
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1487
-                'Registration',
1488
-                $not_approved_query_args
1489
-            ),
1490
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1491
-                'Registration',
1492
-                $pending_payment_query_args
1493
-            ),
1494
-            'misc_pub_section_class'       => apply_filters(
1495
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1496
-                'misc-pub-section'
1497
-            ),
1498
-        );
1499
-        ob_start();
1500
-        do_action(
1501
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1502
-            $this->_cpt_model_obj
1503
-        );
1504
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1505
-        // load template
1506
-        EEH_Template::display_template(
1507
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1508
-            $publish_box_extra_args
1509
-        );
1510
-    }
1511
-
1512
-
1513
-    /**
1514
-     * @return EE_Event
1515
-     */
1516
-    public function get_event_object()
1517
-    {
1518
-        return $this->_cpt_model_obj;
1519
-    }
1520
-
1521
-
1522
-
1523
-
1524
-    /** METABOXES * */
1525
-    /**
1526
-     * _register_event_editor_meta_boxes
1527
-     * add all metaboxes related to the event_editor
1528
-     *
1529
-     * @return void
1530
-     */
1531
-    protected function _register_event_editor_meta_boxes()
1532
-    {
1533
-        $this->verify_cpt_object();
1534
-        add_meta_box(
1535
-            'espresso_event_editor_tickets',
1536
-            esc_html__('Event Datetime & Ticket', 'event_espresso'),
1537
-            array($this, 'ticket_metabox'),
1538
-            $this->page_slug,
1539
-            'normal',
1540
-            'high'
1541
-        );
1542
-        add_meta_box(
1543
-            'espresso_event_editor_event_options',
1544
-            esc_html__('Event Registration Options', 'event_espresso'),
1545
-            array($this, 'registration_options_meta_box'),
1546
-            $this->page_slug,
1547
-            'side',
1548
-            'default'
1549
-        );
1550
-        // NOTE: if you're looking for other metaboxes in here,
1551
-        // where a metabox has a related management page in the admin
1552
-        // you will find it setup in the related management page's "_Hooks" file.
1553
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1554
-    }
1555
-
1556
-
1557
-    /**
1558
-     * @throws DomainException
1559
-     * @throws EE_Error
1560
-     */
1561
-    public function ticket_metabox()
1562
-    {
1563
-        $existing_datetime_ids = $existing_ticket_ids = array();
1564
-        // defaults for template args
1565
-        $template_args = array(
1566
-            'existing_datetime_ids'    => '',
1567
-            'event_datetime_help_link' => '',
1568
-            'ticket_options_help_link' => '',
1569
-            'time'                     => null,
1570
-            'ticket_rows'              => '',
1571
-            'existing_ticket_ids'      => '',
1572
-            'total_ticket_rows'        => 1,
1573
-            'ticket_js_structure'      => '',
1574
-            'trash_icon'               => 'ee-lock-icon',
1575
-            'disabled'                 => '',
1576
-        );
1577
-        $event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1578
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1579
-        /**
1580
-         * 1. Start with retrieving Datetimes
1581
-         * 2. Fore each datetime get related tickets
1582
-         * 3. For each ticket get related prices
1583
-         */
1584
-        $times = EE_Registry::instance()->load_model('Datetime')->get_all_event_dates($event_id);
1585
-        /** @type EE_Datetime $first_datetime */
1586
-        $first_datetime = reset($times);
1587
-        // do we get related tickets?
1588
-        if ($first_datetime instanceof EE_Datetime
1589
-            && $first_datetime->ID() !== 0
1590
-        ) {
1591
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1592
-            $template_args['time'] = $first_datetime;
1593
-            $related_tickets = $first_datetime->tickets(
1594
-                array(
1595
-                    array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
1596
-                    'default_where_conditions' => 'none',
1597
-                )
1598
-            );
1599
-            if (! empty($related_tickets)) {
1600
-                $template_args['total_ticket_rows'] = count($related_tickets);
1601
-                $row = 0;
1602
-                foreach ($related_tickets as $ticket) {
1603
-                    $existing_ticket_ids[] = $ticket->get('TKT_ID');
1604
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1605
-                    $row++;
1606
-                }
1607
-            } else {
1608
-                $template_args['total_ticket_rows'] = 1;
1609
-                /** @type EE_Ticket $ticket */
1610
-                $ticket = EE_Registry::instance()->load_model('Ticket')->create_default_object();
1611
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1612
-            }
1613
-        } else {
1614
-            $template_args['time'] = $times[0];
1615
-            /** @type EE_Ticket $ticket */
1616
-            $ticket = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
1617
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket[1]);
1618
-            // NOTE: we're just sending the first default row
1619
-            // (decaf can't manage default tickets so this should be sufficient);
1620
-        }
1621
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1622
-            'event_editor_event_datetimes_help_tab'
1623
-        );
1624
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1625
-        $template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1626
-        $template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1627
-        $template_args['ticket_js_structure'] = $this->_get_ticket_row(
1628
-            EE_Registry::instance()->load_model('Ticket')->create_default_object(),
1629
-            true
1630
-        );
1631
-        $template = apply_filters(
1632
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1633
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1634
-        );
1635
-        EEH_Template::display_template($template, $template_args);
1636
-    }
1637
-
1638
-
1639
-    /**
1640
-     * Setup an individual ticket form for the decaf event editor page
1641
-     *
1642
-     * @access private
1643
-     * @param  EE_Ticket $ticket   the ticket object
1644
-     * @param  boolean   $skeleton whether we're generating a skeleton for js manipulation
1645
-     * @param int        $row
1646
-     * @return string generated html for the ticket row.
1647
-     */
1648
-    private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1649
-    {
1650
-        $template_args = array(
1651
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1652
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1653
-                : '',
1654
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1655
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1656
-            'TKT_name'            => $ticket->get('TKT_name'),
1657
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1658
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1659
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1660
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1661
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1662
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1663
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1664
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1665
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1666
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1667
-                : ' disabled=disabled',
1668
-        );
1669
-        $price = $ticket->ID() !== 0
1670
-            ? $ticket->get_first_related('Price', array('default_where_conditions' => 'none'))
1671
-            : EE_Registry::instance()->load_model('Price')->create_default_object();
1672
-        $price_args = array(
1673
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1674
-            'PRC_amount'            => $price->get('PRC_amount'),
1675
-            'PRT_ID'                => $price->get('PRT_ID'),
1676
-            'PRC_ID'                => $price->get('PRC_ID'),
1677
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1678
-        );
1679
-        // make sure we have default start and end dates if skeleton
1680
-        // handle rows that should NOT be empty
1681
-        if (empty($template_args['TKT_start_date'])) {
1682
-            // if empty then the start date will be now.
1683
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1684
-        }
1685
-        if (empty($template_args['TKT_end_date'])) {
1686
-            // get the earliest datetime (if present);
1687
-            $earliest_dtt = $this->_cpt_model_obj->ID() > 0
1688
-                ? $this->_cpt_model_obj->get_first_related(
1689
-                    'Datetime',
1690
-                    array('order_by' => array('DTT_EVT_start' => 'ASC'))
1691
-                )
1692
-                : null;
1693
-            if (! empty($earliest_dtt)) {
1694
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a');
1695
-            } else {
1696
-                $template_args['TKT_end_date'] = date(
1697
-                    'Y-m-d h:i a',
1698
-                    mktime(0, 0, 0, date("m"), date("d") + 7, date("Y"))
1699
-                );
1700
-            }
1701
-        }
1702
-        $template_args = array_merge($template_args, $price_args);
1703
-        $template = apply_filters(
1704
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1705
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1706
-            $ticket
1707
-        );
1708
-        return EEH_Template::display_template($template, $template_args, true);
1709
-    }
1710
-
1711
-
1712
-    /**
1713
-     * @throws DomainException
1714
-     */
1715
-    public function registration_options_meta_box()
1716
-    {
1717
-        $yes_no_values = array(
1718
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
1719
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
1720
-        );
1721
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1722
-            array(
1723
-                EEM_Registration::status_id_cancelled,
1724
-                EEM_Registration::status_id_declined,
1725
-                EEM_Registration::status_id_incomplete,
1726
-            ),
1727
-            true
1728
-        );
1729
-        // $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1730
-        $template_args['_event'] = $this->_cpt_model_obj;
1731
-        $template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1732
-        $template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1733
-        $template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1734
-            'default_reg_status',
1735
-            $default_reg_status_values,
1736
-            $this->_cpt_model_obj->default_registration_status()
1737
-        );
1738
-        $template_args['display_description'] = EEH_Form_Fields::select_input(
1739
-            'display_desc',
1740
-            $yes_no_values,
1741
-            $this->_cpt_model_obj->display_description()
1742
-        );
1743
-        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1744
-            'display_ticket_selector',
1745
-            $yes_no_values,
1746
-            $this->_cpt_model_obj->display_ticket_selector(),
1747
-            '',
1748
-            '',
1749
-            false
1750
-        );
1751
-        $template_args['additional_registration_options'] = apply_filters(
1752
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1753
-            '',
1754
-            $template_args,
1755
-            $yes_no_values,
1756
-            $default_reg_status_values
1757
-        );
1758
-        EEH_Template::display_template(
1759
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1760
-            $template_args
1761
-        );
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     * _get_events()
1767
-     * This method simply returns all the events (for the given _view and paging)
1768
-     *
1769
-     * @access public
1770
-     * @param int  $per_page     count of items per page (20 default);
1771
-     * @param int  $current_page what is the current page being viewed.
1772
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1773
-     *                           If FALSE then we return an array of event objects
1774
-     *                           that match the given _view and paging parameters.
1775
-     * @return array an array of event objects.
1776
-     */
1777
-    public function get_events($per_page = 10, $current_page = 1, $count = false)
1778
-    {
1779
-        $EEME = $this->_event_model();
1780
-        $offset = ($current_page - 1) * $per_page;
1781
-        $limit = $count ? null : $offset . ',' . $per_page;
1782
-        $orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'EVT_ID';
1783
-        $order = isset($this->_req_data['order']) ? $this->_req_data['order'] : "DESC";
1784
-        if (isset($this->_req_data['month_range'])) {
1785
-            $pieces = explode(' ', $this->_req_data['month_range'], 3);
1786
-            // simulate the FIRST day of the month, that fixes issues for months like February
1787
-            // where PHP doesn't know what to assume for date.
1788
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1789
-            $month_r = ! empty($pieces[0]) ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1790
-            $year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1791
-        }
1792
-        $where = array();
1793
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1794
-        // determine what post_status our condition will have for the query.
1795
-        switch ($status) {
1796
-            case 'month':
1797
-            case 'today':
1798
-            case null:
1799
-            case 'all':
1800
-                break;
1801
-            case 'draft':
1802
-                $where['status'] = array('IN', array('draft', 'auto-draft'));
1803
-                break;
1804
-            default:
1805
-                $where['status'] = $status;
1806
-        }
1807
-        // categories?
1808
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1809
-            ? $this->_req_data['EVT_CAT'] : null;
1810
-        if (! empty($category)) {
1811
-            $where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1812
-            $where['Term_Taxonomy.term_id'] = $category;
1813
-        }
1814
-        // date where conditions
1815
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1816
-        if (isset($this->_req_data['month_range']) && $this->_req_data['month_range'] != '') {
1817
-            $DateTime = new DateTime(
1818
-                $year_r . '-' . $month_r . '-01 00:00:00',
1819
-                new DateTimeZone('UTC')
1820
-            );
1821
-            $start = $DateTime->getTimestamp();
1822
-            // set the datetime to be the end of the month
1823
-            $DateTime->setDate(
1824
-                $year_r,
1825
-                $month_r,
1826
-                $DateTime->format('t')
1827
-            )->setTime(23, 59, 59);
1828
-            $end = $DateTime->getTimestamp();
1829
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1830
-        } elseif (isset($this->_req_data['status']) && $this->_req_data['status'] == 'today') {
1831
-            $DateTime = new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1832
-            $start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1833
-            $end = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1834
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1835
-        } elseif (isset($this->_req_data['status']) && $this->_req_data['status'] == 'month') {
1836
-            $now = date('Y-m-01');
1837
-            $DateTime = new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1838
-            $start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1839
-            $end = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1840
-                            ->setTime(23, 59, 59)
1841
-                            ->format(implode(' ', $start_formats));
1842
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1843
-        }
1844
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1845
-            $where['EVT_wp_user'] = get_current_user_id();
1846
-        } else {
1847
-            if (! isset($where['status'])) {
1848
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1849
-                    $where['OR'] = array(
1850
-                        'status*restrict_private' => array('!=', 'private'),
1851
-                        'AND'                     => array(
1852
-                            'status*inclusive' => array('=', 'private'),
1853
-                            'EVT_wp_user'      => get_current_user_id(),
1854
-                        ),
1855
-                    );
1856
-                }
1857
-            }
1858
-        }
1859
-        if (isset($this->_req_data['EVT_wp_user'])) {
1860
-            if ($this->_req_data['EVT_wp_user'] != get_current_user_id()
1861
-                && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1862
-            ) {
1863
-                $where['EVT_wp_user'] = $this->_req_data['EVT_wp_user'];
1864
-            }
1865
-        }
1866
-        // search query handling
1867
-        if (isset($this->_req_data['s'])) {
1868
-            $search_string = '%' . $this->_req_data['s'] . '%';
1869
-            $where['OR'] = array(
1870
-                'EVT_name'       => array('LIKE', $search_string),
1871
-                'EVT_desc'       => array('LIKE', $search_string),
1872
-                'EVT_short_desc' => array('LIKE', $search_string),
1873
-            );
1874
-        }
1875
-        // filter events by venue.
1876
-        if (isset($this->_req_data['venue']) && ! empty($this->_req_data['venue'])) {
1877
-            $where['Venue.VNU_ID'] = absint($this->_req_data['venue']);
1878
-        }
1879
-        $where = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $this->_req_data);
1880
-        $query_params = apply_filters(
1881
-            'FHEE__Events_Admin_Page__get_events__query_params',
1882
-            array(
1883
-                $where,
1884
-                'limit'    => $limit,
1885
-                'order_by' => $orderby,
1886
-                'order'    => $order,
1887
-                'group_by' => 'EVT_ID',
1888
-            ),
1889
-            $this->_req_data
1890
-        );
1891
-
1892
-        // let's first check if we have special requests coming in.
1893
-        if (isset($this->_req_data['active_status'])) {
1894
-            switch ($this->_req_data['active_status']) {
1895
-                case 'upcoming':
1896
-                    return $EEME->get_upcoming_events($query_params, $count);
1897
-                    break;
1898
-                case 'expired':
1899
-                    return $EEME->get_expired_events($query_params, $count);
1900
-                    break;
1901
-                case 'active':
1902
-                    return $EEME->get_active_events($query_params, $count);
1903
-                    break;
1904
-                case 'inactive':
1905
-                    return $EEME->get_inactive_events($query_params, $count);
1906
-                    break;
1907
-            }
1908
-        }
1909
-
1910
-        $events = $count ? $EEME->count(array($where), 'EVT_ID', true) : $EEME->get_all($query_params);
1911
-        return $events;
1912
-    }
1913
-
1914
-
1915
-    /**
1916
-     * handling for WordPress CPT actions (trash, restore, delete)
1917
-     *
1918
-     * @param string $post_id
1919
-     */
1920
-    public function trash_cpt_item($post_id)
1921
-    {
1922
-        $this->_req_data['EVT_ID'] = $post_id;
1923
-        $this->_trash_or_restore_event('trash', false);
1924
-    }
1925
-
1926
-
1927
-    /**
1928
-     * @param string $post_id
1929
-     */
1930
-    public function restore_cpt_item($post_id)
1931
-    {
1932
-        $this->_req_data['EVT_ID'] = $post_id;
1933
-        $this->_trash_or_restore_event('draft', false);
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * @param string $post_id
1939
-     */
1940
-    public function delete_cpt_item($post_id)
1941
-    {
1942
-        throw new EE_Error(esc_html__('Please contact Event Espresso support with the details of the steps taken to produce this error.', 'event_espresso'));
1943
-        $this->_req_data['EVT_ID'] = $post_id;
1944
-        $this->_delete_event();
1945
-    }
1946
-
1947
-
1948
-    /**
1949
-     * _trash_or_restore_event
1950
-     *
1951
-     * @access protected
1952
-     * @param  string $event_status
1953
-     * @param bool    $redirect_after
1954
-     */
1955
-    protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
1956
-    {
1957
-        // determine the event id and set to array.
1958
-        $EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : false;
1959
-        // loop thru events
1960
-        if ($EVT_ID) {
1961
-            // clean status
1962
-            $event_status = sanitize_key($event_status);
1963
-            // grab status
1964
-            if (! empty($event_status)) {
1965
-                $success = $this->_change_event_status($EVT_ID, $event_status);
1966
-            } else {
1967
-                $success = false;
1968
-                $msg = esc_html__(
1969
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
1970
-                    'event_espresso'
1971
-                );
1972
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1973
-            }
1974
-        } else {
1975
-            $success = false;
1976
-            $msg = esc_html__(
1977
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
1978
-                'event_espresso'
1979
-            );
1980
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1981
-        }
1982
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
1983
-        if ($redirect_after) {
1984
-            $this->_redirect_after_action($success, 'Event', $action, array('action' => 'default'));
1985
-        }
1986
-    }
1987
-
1988
-
1989
-    /**
1990
-     * _trash_or_restore_events
1991
-     *
1992
-     * @access protected
1993
-     * @param  string $event_status
1994
-     * @return void
1995
-     */
1996
-    protected function _trash_or_restore_events($event_status = 'trash')
1997
-    {
1998
-        // clean status
1999
-        $event_status = sanitize_key($event_status);
2000
-        // grab status
2001
-        if (! empty($event_status)) {
2002
-            $success = true;
2003
-            // determine the event id and set to array.
2004
-            $EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array) $this->_req_data['EVT_IDs'] : array();
2005
-            // loop thru events
2006
-            foreach ($EVT_IDs as $EVT_ID) {
2007
-                if ($EVT_ID = absint($EVT_ID)) {
2008
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
2009
-                    $success = $results !== false ? $success : false;
2010
-                } else {
2011
-                    $msg = sprintf(
2012
-                        esc_html__(
2013
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2014
-                            'event_espresso'
2015
-                        ),
2016
-                        $EVT_ID
2017
-                    );
2018
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2019
-                    $success = false;
2020
-                }
2021
-            }
2022
-        } else {
2023
-            $success = false;
2024
-            $msg = esc_html__(
2025
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2026
-                'event_espresso'
2027
-            );
2028
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2029
-        }
2030
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2031
-        $success = $success ? 2 : false;
2032
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2033
-        $this->_redirect_after_action($success, 'Events', $action, array('action' => 'default'));
2034
-    }
2035
-
2036
-
2037
-    /**
2038
-     * _trash_or_restore_events
2039
-     *
2040
-     * @access  private
2041
-     * @param  int    $EVT_ID
2042
-     * @param  string $event_status
2043
-     * @return bool
2044
-     */
2045
-    private function _change_event_status($EVT_ID = 0, $event_status = '')
2046
-    {
2047
-        // grab event id
2048
-        if (! $EVT_ID) {
2049
-            $msg = esc_html__(
2050
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2051
-                'event_espresso'
2052
-            );
2053
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2054
-            return false;
2055
-        }
2056
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2057
-        // clean status
2058
-        $event_status = sanitize_key($event_status);
2059
-        // grab status
2060
-        if (empty($event_status)) {
2061
-            $msg = esc_html__(
2062
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2063
-                'event_espresso'
2064
-            );
2065
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2066
-            return false;
2067
-        }
2068
-        // was event trashed or restored ?
2069
-        switch ($event_status) {
2070
-            case 'draft':
2071
-                $action = 'restored from the trash';
2072
-                $hook = 'AHEE_event_restored_from_trash';
2073
-                break;
2074
-            case 'trash':
2075
-                $action = 'moved to the trash';
2076
-                $hook = 'AHEE_event_moved_to_trash';
2077
-                break;
2078
-            default:
2079
-                $action = 'updated';
2080
-                $hook = false;
2081
-        }
2082
-        // use class to change status
2083
-        $this->_cpt_model_obj->set_status($event_status);
2084
-        $success = $this->_cpt_model_obj->save();
2085
-        if ($success === false) {
2086
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2087
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2088
-            return false;
2089
-        }
2090
-        if ($hook) {
2091
-            do_action($hook);
2092
-        }
2093
-        return true;
2094
-    }
2095
-
2096
-
2097
-    /**
2098
-     * _delete_event
2099
-     *
2100
-     * @access protected
2101
-     * @param bool $redirect_after
2102
-     */
2103
-    protected function _delete_event()
2104
-    {
2105
-        $this->generateDeletionPreview(isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : array());
2106
-    }
2107
-
2108
-    /**
2109
-     * Gets the tree traversal batch persister.
2110
-     * @since 4.10.12.p
2111
-     * @return NodeGroupDao
2112
-     * @throws InvalidArgumentException
2113
-     * @throws InvalidDataTypeException
2114
-     * @throws InvalidInterfaceException
2115
-     */
2116
-    protected function getModelObjNodeGroupPersister()
2117
-    {
2118
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2119
-            $this->model_obj_node_group_persister = $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2120
-        }
2121
-        return $this->model_obj_node_group_persister;
2122
-    }
2123
-
2124
-    /**
2125
-     * _delete_events
2126
-     *
2127
-     * @access protected
2128
-     * @return void
2129
-     */
2130
-    protected function _delete_events()
2131
-    {
2132
-        $this->generateDeletionPreview(isset($this->_req_data['EVT_IDs']) ? (array) $this->_req_data['EVT_IDs'] : array());
2133
-    }
2134
-
2135
-    protected function generateDeletionPreview($event_ids)
2136
-    {
2137
-        $event_ids = (array) $event_ids;
2138
-        // Set a code we can use to reference this deletion task in the batch jobs and preview page.
2139
-        $deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2140
-        $return_url = EE_Admin_Page::add_query_args_and_nonce(
2141
-            [
2142
-                'action' => 'preview_deletion',
2143
-                'deletion_job_code' => $deletion_job_code,
2144
-            ],
2145
-            $this->_admin_base_url
2146
-        );
2147
-        $event_ids = array_map(
2148
-            'intval',
2149
-            $event_ids
2150
-        );
2151
-
2152
-        EEH_URL::safeRedirectAndExit(
2153
-            EE_Admin_Page::add_query_args_and_nonce(
2154
-                array(
2155
-                    'page'        => 'espresso_batch',
2156
-                    'batch'       => EED_Batch::batch_job,
2157
-                    'EVT_IDs'      => $event_ids,
2158
-                    'deletion_job_code' => $deletion_job_code,
2159
-                    'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2160
-                    'return_url'  => urlencode($return_url),
2161
-                ),
2162
-                admin_url()
2163
-            )
2164
-        );
2165
-    }
2166
-
2167
-    /**
2168
-     * Checks for a POST submission
2169
-     * @since 4.10.12.p
2170
-     */
2171
-    protected function confirmDeletion()
2172
-    {
2173
-        $deletion_redirect_logic = $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2174
-        $deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2175
-    }
2176
-
2177
-    /**
2178
-     * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2179
-     * @since 4.10.12.p
2180
-     * @throws EE_Error
2181
-     */
2182
-    protected function previewDeletion()
2183
-    {
2184
-        $preview_deletion_logic = $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2185
-        $this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2186
-        $this->display_admin_page_with_no_sidebar();
2187
-    }
2188
-
2189
-    /**
2190
-     * get total number of events
2191
-     *
2192
-     * @access public
2193
-     * @return int
2194
-     */
2195
-    public function total_events()
2196
-    {
2197
-        $count = EEM_Event::instance()->count(array('caps' => 'read_admin'), 'EVT_ID', true);
2198
-        return $count;
2199
-    }
2200
-
2201
-
2202
-    /**
2203
-     * get total number of draft events
2204
-     *
2205
-     * @access public
2206
-     * @return int
2207
-     */
2208
-    public function total_events_draft()
2209
-    {
2210
-        $where = array(
2211
-            'status' => array('IN', array('draft', 'auto-draft')),
2212
-        );
2213
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2214
-        return $count;
2215
-    }
2216
-
2217
-
2218
-    /**
2219
-     * get total number of trashed events
2220
-     *
2221
-     * @access public
2222
-     * @return int
2223
-     */
2224
-    public function total_trashed_events()
2225
-    {
2226
-        $where = array(
2227
-            'status' => 'trash',
2228
-        );
2229
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2230
-        return $count;
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     *    _default_event_settings
2236
-     *    This generates the Default Settings Tab
2237
-     *
2238
-     * @return void
2239
-     * @throws EE_Error
2240
-     */
2241
-    protected function _default_event_settings()
2242
-    {
2243
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2244
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
2245
-        $this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2246
-        $this->display_admin_page_with_sidebar();
2247
-    }
2248
-
2249
-
2250
-    /**
2251
-     * Return the form for event settings.
2252
-     *
2253
-     * @return EE_Form_Section_Proper
2254
-     * @throws EE_Error
2255
-     */
2256
-    protected function _default_event_settings_form()
2257
-    {
2258
-        $registration_config = EE_Registry::instance()->CFG->registration;
2259
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2260
-            // exclude
2261
-            array(
2262
-                EEM_Registration::status_id_cancelled,
2263
-                EEM_Registration::status_id_declined,
2264
-                EEM_Registration::status_id_incomplete,
2265
-                EEM_Registration::status_id_wait_list,
2266
-            ),
2267
-            true
2268
-        );
2269
-        return new EE_Form_Section_Proper(
2270
-            array(
2271
-                'name'            => 'update_default_event_settings',
2272
-                'html_id'         => 'update_default_event_settings',
2273
-                'html_class'      => 'form-table',
2274
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2275
-                'subsections'     => apply_filters(
2276
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2277
-                    array(
2278
-                        'default_reg_status'  => new EE_Select_Input(
2279
-                            $registration_stati_for_selection,
2280
-                            array(
2281
-                                'default'         => isset($registration_config->default_STS_ID)
2282
-                                                     && array_key_exists(
2283
-                                                         $registration_config->default_STS_ID,
2284
-                                                         $registration_stati_for_selection
2285
-                                                     )
2286
-                                    ? sanitize_text_field($registration_config->default_STS_ID)
2287
-                                    : EEM_Registration::status_id_pending_payment,
2288
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2289
-                                                     . EEH_Template::get_help_tab_link(
2290
-                                                         'default_settings_status_help_tab'
2291
-                                                     ),
2292
-                                'html_help_text'  => esc_html__(
2293
-                                    'This setting allows you to preselect what the default registration status setting is when creating an event.  Note that changing this setting does NOT retroactively apply it to existing events.',
2294
-                                    'event_espresso'
2295
-                                ),
2296
-                            )
2297
-                        ),
2298
-                        'default_max_tickets' => new EE_Integer_Input(
2299
-                            array(
2300
-                                'default'         => isset($registration_config->default_maximum_number_of_tickets)
2301
-                                    ? $registration_config->default_maximum_number_of_tickets
2302
-                                    : EEM_Event::get_default_additional_limit(),
2303
-                                'html_label_text' => esc_html__(
2304
-                                    'Default Maximum Tickets Allowed Per Order:',
2305
-                                    'event_espresso'
2306
-                                )
2307
-                                                     . EEH_Template::get_help_tab_link(
2308
-                                                         'default_maximum_tickets_help_tab"'
2309
-                                                     ),
2310
-                                'html_help_text'  => esc_html__(
2311
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2312
-                                    'event_espresso'
2313
-                                ),
2314
-                            )
2315
-                        ),
2316
-                    )
2317
-                ),
2318
-            )
2319
-        );
2320
-    }
2321
-
2322
-
2323
-    /**
2324
-     * _update_default_event_settings
2325
-     *
2326
-     * @access protected
2327
-     * @return void
2328
-     * @throws EE_Error
2329
-     */
2330
-    protected function _update_default_event_settings()
2331
-    {
2332
-        $registration_config = EE_Registry::instance()->CFG->registration;
2333
-        $form = $this->_default_event_settings_form();
2334
-        if ($form->was_submitted()) {
2335
-            $form->receive_form_submission();
2336
-            if ($form->is_valid()) {
2337
-                $valid_data = $form->valid_data();
2338
-                if (isset($valid_data['default_reg_status'])) {
2339
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2340
-                }
2341
-                if (isset($valid_data['default_max_tickets'])) {
2342
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2343
-                }
2344
-                // update because data was valid!
2345
-                EE_Registry::instance()->CFG->update_espresso_config();
2346
-                EE_Error::overwrite_success();
2347
-                EE_Error::add_success(
2348
-                    __('Default Event Settings were updated', 'event_espresso')
2349
-                );
2350
-            }
2351
-        }
2352
-        $this->_redirect_after_action(0, '', '', array('action' => 'default_event_settings'), true);
2353
-    }
2354
-
2355
-
2356
-    /*************        Templates        *************/
2357
-    protected function _template_settings()
2358
-    {
2359
-        $this->_admin_page_title = esc_html__('Template Settings (Preview)', 'event_espresso');
2360
-        $this->_template_args['preview_img'] = '<img src="'
2361
-                                               . EVENTS_ASSETS_URL
2362
-                                               . '/images/'
2363
-                                               . 'caffeinated_template_features.jpg" alt="'
2364
-                                               . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2365
-                                               . '" />';
2366
-        $this->_template_args['preview_text'] = '<strong>'
2367
-                                                . esc_html__(
2368
-                                                    'Template Settings is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. Template Settings allow you to configure some of the appearance options for both the Event List and Event Details pages.',
2369
-                                                    'event_espresso'
2370
-                                                ) . '</strong>';
2371
-        $this->display_admin_caf_preview_page('template_settings_tab');
2372
-    }
2373
-
2374
-
2375
-    /** Event Category Stuff **/
2376
-    /**
2377
-     * set the _category property with the category object for the loaded page.
2378
-     *
2379
-     * @access private
2380
-     * @return void
2381
-     */
2382
-    private function _set_category_object()
2383
-    {
2384
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2385
-            return;
2386
-        } //already have the category object so get out.
2387
-        // set default category object
2388
-        $this->_set_empty_category_object();
2389
-        // only set if we've got an id
2390
-        if (! isset($this->_req_data['EVT_CAT_ID'])) {
2391
-            return;
2392
-        }
2393
-        $category_id = absint($this->_req_data['EVT_CAT_ID']);
2394
-        $term = get_term($category_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2395
-        if (! empty($term)) {
2396
-            $this->_category->category_name = $term->name;
2397
-            $this->_category->category_identifier = $term->slug;
2398
-            $this->_category->category_desc = $term->description;
2399
-            $this->_category->id = $term->term_id;
2400
-            $this->_category->parent = $term->parent;
2401
-        }
2402
-    }
2403
-
2404
-
2405
-    /**
2406
-     * Clears out category properties.
2407
-     */
2408
-    private function _set_empty_category_object()
2409
-    {
2410
-        $this->_category = new stdClass();
2411
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2412
-        $this->_category->id = $this->_category->parent = 0;
2413
-    }
2414
-
2415
-
2416
-    /**
2417
-     * @throws EE_Error
2418
-     */
2419
-    protected function _category_list_table()
2420
-    {
2421
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2422
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2424
-            'add_category',
2425
-            'add_category',
2426
-            array(),
2427
-            'add-new-h2'
2428
-        );
2429
-        $this->display_admin_list_table_page_with_sidebar();
2430
-    }
2431
-
2432
-
2433
-    /**
2434
-     * Output category details view.
2435
-     */
2436
-    protected function _category_details($view)
2437
-    {
2438
-        // load formatter helper
2439
-        // load field generator helper
2440
-        $route = $view == 'edit' ? 'update_category' : 'insert_category';
2441
-        $this->_set_add_edit_form_tags($route);
2442
-        $this->_set_category_object();
2443
-        $id = ! empty($this->_category->id) ? $this->_category->id : '';
2444
-        $delete_action = 'delete_category';
2445
-        // custom redirect
2446
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2447
-            array('action' => 'category_list'),
2448
-            $this->_admin_base_url
2449
-        );
2450
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2451
-        // take care of contents
2452
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2453
-        $this->display_admin_page_with_sidebar();
2454
-    }
2455
-
2456
-
2457
-    /**
2458
-     * Output category details content.
2459
-     */
2460
-    protected function _category_details_content()
2461
-    {
2462
-        $editor_args['category_desc'] = array(
2463
-            'type'          => 'wp_editor',
2464
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2465
-            'class'         => 'my_editor_custom',
2466
-            'wpeditor_args' => array('media_buttons' => false),
2467
-        );
2468
-        $_wp_editor = $this->_generate_admin_form_fields($editor_args, 'array');
2469
-        $all_terms = get_terms(
2470
-            array(EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY),
2471
-            array('hide_empty' => 0, 'exclude' => array($this->_category->id))
2472
-        );
2473
-        // setup category select for term parents.
2474
-        $category_select_values[] = array(
2475
-            'text' => esc_html__('No Parent', 'event_espresso'),
2476
-            'id'   => 0,
2477
-        );
2478
-        foreach ($all_terms as $term) {
2479
-            $category_select_values[] = array(
2480
-                'text' => $term->name,
2481
-                'id'   => $term->term_id,
2482
-            );
2483
-        }
2484
-        $category_select = EEH_Form_Fields::select_input(
2485
-            'category_parent',
2486
-            $category_select_values,
2487
-            $this->_category->parent
2488
-        );
2489
-        $template_args = array(
2490
-            'category'                 => $this->_category,
2491
-            'category_select'          => $category_select,
2492
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2493
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2494
-            'disable'                  => '',
2495
-            'disabled_message'         => false,
2496
-        );
2497
-        $template = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2498
-        return EEH_Template::display_template($template, $template_args, true);
2499
-    }
2500
-
2501
-
2502
-    /**
2503
-     * Handles deleting categories.
2504
-     */
2505
-    protected function _delete_categories()
2506
-    {
2507
-        $cat_ids = isset($this->_req_data['EVT_CAT_ID']) ? (array) $this->_req_data['EVT_CAT_ID']
2508
-            : (array) $this->_req_data['category_id'];
2509
-        foreach ($cat_ids as $cat_id) {
2510
-            $this->_delete_category($cat_id);
2511
-        }
2512
-        // doesn't matter what page we're coming from... we're going to the same place after delete.
2513
-        $query_args = array(
2514
-            'action' => 'category_list',
2515
-        );
2516
-        $this->_redirect_after_action(0, '', '', $query_args);
2517
-    }
2518
-
2519
-
2520
-    /**
2521
-     * Handles deleting specific category.
2522
-     *
2523
-     * @param int $cat_id
2524
-     */
2525
-    protected function _delete_category($cat_id)
2526
-    {
2527
-        $cat_id = absint($cat_id);
2528
-        wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2529
-    }
2530
-
2531
-
2532
-    /**
2533
-     * Handles triggering the update or insertion of a new category.
2534
-     *
2535
-     * @param bool $new_category true means we're triggering the insert of a new category.
2536
-     */
2537
-    protected function _insert_or_update_category($new_category)
2538
-    {
2539
-        $cat_id = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2540
-        $success = 0; // we already have a success message so lets not send another.
2541
-        if ($cat_id) {
2542
-            $query_args = array(
2543
-                'action'     => 'edit_category',
2544
-                'EVT_CAT_ID' => $cat_id,
2545
-            );
2546
-        } else {
2547
-            $query_args = array('action' => 'add_category');
2548
-        }
2549
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2550
-    }
2551
-
2552
-
2553
-    /**
2554
-     * Inserts or updates category
2555
-     *
2556
-     * @param bool $update (true indicates we're updating a category).
2557
-     * @return bool|mixed|string
2558
-     */
2559
-    private function _insert_category($update = false)
2560
-    {
2561
-        $cat_id = $update ? $this->_req_data['EVT_CAT_ID'] : '';
2562
-        $category_name = isset($this->_req_data['category_name']) ? $this->_req_data['category_name'] : '';
2563
-        $category_desc = isset($this->_req_data['category_desc']) ? $this->_req_data['category_desc'] : '';
2564
-        $category_parent = isset($this->_req_data['category_parent']) ? $this->_req_data['category_parent'] : 0;
2565
-        if (empty($category_name)) {
2566
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2567
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2568
-            return false;
2569
-        }
2570
-        $term_args = array(
2571
-            'name'        => $category_name,
2572
-            'description' => $category_desc,
2573
-            'parent'      => $category_parent,
2574
-        );
2575
-        // was the category_identifier input disabled?
2576
-        if (isset($this->_req_data['category_identifier'])) {
2577
-            $term_args['slug'] = $this->_req_data['category_identifier'];
2578
-        }
2579
-        $insert_ids = $update
2580
-            ? wp_update_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2581
-            : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2582
-        if (! is_array($insert_ids)) {
2583
-            $msg = esc_html__(
2584
-                'An error occurred and the category has not been saved to the database.',
2585
-                'event_espresso'
2586
-            );
2587
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2588
-        } else {
2589
-            $cat_id = $insert_ids['term_id'];
2590
-            $msg = sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2591
-            EE_Error::add_success($msg);
2592
-        }
2593
-        return $cat_id;
2594
-    }
2595
-
2596
-
2597
-    /**
2598
-     * Gets categories or count of categories matching the arguments in the request.
2599
-     *
2600
-     * @param int  $per_page
2601
-     * @param int  $current_page
2602
-     * @param bool $count
2603
-     * @return EE_Base_Class[]|EE_Term_Taxonomy[]|int
2604
-     */
2605
-    public function get_categories($per_page = 10, $current_page = 1, $count = false)
2606
-    {
2607
-        // testing term stuff
2608
-        $orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'Term.term_id';
2609
-        $order = isset($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2610
-        $limit = ($current_page - 1) * $per_page;
2611
-        $where = array('taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2612
-        if (isset($this->_req_data['s'])) {
2613
-            $sstr = '%' . $this->_req_data['s'] . '%';
2614
-            $where['OR'] = array(
2615
-                'Term.name'   => array('LIKE', $sstr),
2616
-                'description' => array('LIKE', $sstr),
2617
-            );
2618
-        }
2619
-        $query_params = array(
2620
-            $where,
2621
-            'order_by'   => array($orderby => $order),
2622
-            'limit'      => $limit . ',' . $per_page,
2623
-            'force_join' => array('Term'),
2624
-        );
2625
-        $categories = $count
2626
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2627
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2628
-        return $categories;
2629
-    }
2630
-
2631
-    /* end category stuff */
2632
-    /**************/
2633
-
2634
-
2635
-    /**
2636
-     * Callback for the `ee_save_timezone_setting` ajax action.
2637
-     *
2638
-     * @throws EE_Error
2639
-     */
2640
-    public function save_timezonestring_setting()
2641
-    {
2642
-        $timezone_string = isset($this->_req_data['timezone_selected'])
2643
-            ? $this->_req_data['timezone_selected']
2644
-            : '';
2645
-        if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2646
-            EE_Error::add_error(
2647
-                esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2648
-                __FILE__,
2649
-                __FUNCTION__,
2650
-                __LINE__
2651
-            );
2652
-            $this->_template_args['error'] = true;
2653
-            $this->_return_json();
2654
-        }
2655
-
2656
-        update_option('timezone_string', $timezone_string);
2657
-        EE_Error::add_success(
2658
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2659
-        );
2660
-        $this->_template_args['success'] = true;
2661
-        $this->_return_json(true, array('action' => 'create_new'));
2662
-    }
22
+	/**
23
+	 * This will hold the event object for event_details screen.
24
+	 *
25
+	 * @access protected
26
+	 * @var EE_Event $_event
27
+	 */
28
+	protected $_event;
29
+
30
+
31
+	/**
32
+	 * This will hold the category object for category_details screen.
33
+	 *
34
+	 * @var stdClass $_category
35
+	 */
36
+	protected $_category;
37
+
38
+
39
+	/**
40
+	 * This will hold the event model instance
41
+	 *
42
+	 * @var EEM_Event $_event_model
43
+	 */
44
+	protected $_event_model;
45
+
46
+
47
+	/**
48
+	 * @var EE_Event
49
+	 */
50
+	protected $_cpt_model_obj = false;
51
+
52
+
53
+	/**
54
+	 * @var NodeGroupDao
55
+	 */
56
+	protected $model_obj_node_group_persister;
57
+
58
+	/**
59
+	 * Initialize page props for this admin page group.
60
+	 */
61
+	protected function _init_page_props()
62
+	{
63
+		$this->page_slug = EVENTS_PG_SLUG;
64
+		$this->page_label = EVENTS_LABEL;
65
+		$this->_admin_base_url = EVENTS_ADMIN_URL;
66
+		$this->_admin_base_path = EVENTS_ADMIN;
67
+		$this->_cpt_model_names = array(
68
+			'create_new' => 'EEM_Event',
69
+			'edit'       => 'EEM_Event',
70
+		);
71
+		$this->_cpt_edit_routes = array(
72
+			'espresso_events' => 'edit',
73
+		);
74
+		add_action(
75
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
76
+			array($this, 'verify_event_edit'),
77
+			10,
78
+			2
79
+		);
80
+	}
81
+
82
+
83
+	/**
84
+	 * Sets the ajax hooks used for this admin page group.
85
+	 */
86
+	protected function _ajax_hooks()
87
+	{
88
+		add_action('wp_ajax_ee_save_timezone_setting', array($this, 'save_timezonestring_setting'));
89
+	}
90
+
91
+
92
+	/**
93
+	 * Sets the page properties for this admin page group.
94
+	 */
95
+	protected function _define_page_props()
96
+	{
97
+		$this->_admin_page_title = EVENTS_LABEL;
98
+		$this->_labels = array(
99
+			'buttons'      => array(
100
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
101
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
102
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
103
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
104
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
105
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
106
+			),
107
+			'editor_title' => array(
108
+				'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
109
+			),
110
+			'publishbox'   => array(
111
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
112
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
113
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
114
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
115
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
116
+			),
117
+		);
118
+	}
119
+
120
+
121
+	/**
122
+	 * Sets the page routes property for this admin page group.
123
+	 */
124
+	protected function _set_page_routes()
125
+	{
126
+		// load formatter helper
127
+		// load field generator helper
128
+		// is there a evt_id in the request?
129
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
130
+			? $this->_req_data['EVT_ID']
131
+			: 0;
132
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
133
+		$this->_page_routes = array(
134
+			'default'                       => array(
135
+				'func'       => '_events_overview_list_table',
136
+				'capability' => 'ee_read_events',
137
+			),
138
+			'create_new'                    => array(
139
+				'func'       => '_create_new_cpt_item',
140
+				'capability' => 'ee_edit_events',
141
+			),
142
+			'edit'                          => array(
143
+				'func'       => '_edit_cpt_item',
144
+				'capability' => 'ee_edit_event',
145
+				'obj_id'     => $evt_id,
146
+			),
147
+			'copy_event'                    => array(
148
+				'func'       => '_copy_events',
149
+				'capability' => 'ee_edit_event',
150
+				'obj_id'     => $evt_id,
151
+				'noheader'   => true,
152
+			),
153
+			'trash_event'                   => array(
154
+				'func'       => '_trash_or_restore_event',
155
+				'args'       => array('event_status' => 'trash'),
156
+				'capability' => 'ee_delete_event',
157
+				'obj_id'     => $evt_id,
158
+				'noheader'   => true,
159
+			),
160
+			'trash_events'                  => array(
161
+				'func'       => '_trash_or_restore_events',
162
+				'args'       => array('event_status' => 'trash'),
163
+				'capability' => 'ee_delete_events',
164
+				'noheader'   => true,
165
+			),
166
+			'restore_event'                 => array(
167
+				'func'       => '_trash_or_restore_event',
168
+				'args'       => array('event_status' => 'draft'),
169
+				'capability' => 'ee_delete_event',
170
+				'obj_id'     => $evt_id,
171
+				'noheader'   => true,
172
+			),
173
+			'restore_events'                => array(
174
+				'func'       => '_trash_or_restore_events',
175
+				'args'       => array('event_status' => 'draft'),
176
+				'capability' => 'ee_delete_events',
177
+				'noheader'   => true,
178
+			),
179
+			'delete_event'                  => array(
180
+				'func'       => '_delete_event',
181
+				'capability' => 'ee_delete_event',
182
+				'obj_id'     => $evt_id,
183
+				'noheader'   => true,
184
+			),
185
+			'delete_events'                 => array(
186
+				'func'       => '_delete_events',
187
+				'capability' => 'ee_delete_events',
188
+				'noheader'   => true,
189
+			),
190
+			'view_report'                   => array(
191
+				'func'      => '_view_report',
192
+				'capablity' => 'ee_edit_events',
193
+			),
194
+			'default_event_settings'        => array(
195
+				'func'       => '_default_event_settings',
196
+				'capability' => 'manage_options',
197
+			),
198
+			'update_default_event_settings' => array(
199
+				'func'       => '_update_default_event_settings',
200
+				'capability' => 'manage_options',
201
+				'noheader'   => true,
202
+			),
203
+			'template_settings'             => array(
204
+				'func'       => '_template_settings',
205
+				'capability' => 'manage_options',
206
+			),
207
+			// event category tab related
208
+			'add_category'                  => array(
209
+				'func'       => '_category_details',
210
+				'capability' => 'ee_edit_event_category',
211
+				'args'       => array('add'),
212
+			),
213
+			'edit_category'                 => array(
214
+				'func'       => '_category_details',
215
+				'capability' => 'ee_edit_event_category',
216
+				'args'       => array('edit'),
217
+			),
218
+			'delete_categories'             => array(
219
+				'func'       => '_delete_categories',
220
+				'capability' => 'ee_delete_event_category',
221
+				'noheader'   => true,
222
+			),
223
+			'delete_category'               => array(
224
+				'func'       => '_delete_categories',
225
+				'capability' => 'ee_delete_event_category',
226
+				'noheader'   => true,
227
+			),
228
+			'insert_category'               => array(
229
+				'func'       => '_insert_or_update_category',
230
+				'args'       => array('new_category' => true),
231
+				'capability' => 'ee_edit_event_category',
232
+				'noheader'   => true,
233
+			),
234
+			'update_category'               => array(
235
+				'func'       => '_insert_or_update_category',
236
+				'args'       => array('new_category' => false),
237
+				'capability' => 'ee_edit_event_category',
238
+				'noheader'   => true,
239
+			),
240
+			'category_list'                 => array(
241
+				'func'       => '_category_list_table',
242
+				'capability' => 'ee_manage_event_categories',
243
+			),
244
+			'preview_deletion' => [
245
+				'func' => 'previewDeletion',
246
+				'capability' => 'ee_delete_events',
247
+			],
248
+			'confirm_deletion' => [
249
+				'func' => 'confirmDeletion',
250
+				'capability' => 'ee_delete_events',
251
+				'noheader' => true,
252
+			]
253
+		);
254
+	}
255
+
256
+
257
+	/**
258
+	 * Set the _page_config property for this admin page group.
259
+	 */
260
+	protected function _set_page_config()
261
+	{
262
+		$this->_page_config = array(
263
+			'default'                => array(
264
+				'nav'           => array(
265
+					'label' => esc_html__('Overview', 'event_espresso'),
266
+					'order' => 10,
267
+				),
268
+				'list_table'    => 'Events_Admin_List_Table',
269
+				'help_tabs'     => array(
270
+					'events_overview_help_tab'                       => array(
271
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
272
+						'filename' => 'events_overview',
273
+					),
274
+					'events_overview_table_column_headings_help_tab' => array(
275
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
276
+						'filename' => 'events_overview_table_column_headings',
277
+					),
278
+					'events_overview_filters_help_tab'               => array(
279
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
280
+						'filename' => 'events_overview_filters',
281
+					),
282
+					'events_overview_view_help_tab'                  => array(
283
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
284
+						'filename' => 'events_overview_views',
285
+					),
286
+					'events_overview_other_help_tab'                 => array(
287
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
288
+						'filename' => 'events_overview_other',
289
+					),
290
+				),
291
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
292
+				// 'help_tour'     => array(
293
+				//     'Event_Overview_Help_Tour',
294
+				//     // 'New_Features_Test_Help_Tour' for testing multiple help tour
295
+				// ),
296
+				'qtips'         => array(
297
+					'EE_Event_List_Table_Tips',
298
+				),
299
+				'require_nonce' => false,
300
+			),
301
+			'create_new'             => array(
302
+				'nav'           => array(
303
+					'label'      => esc_html__('Add Event', 'event_espresso'),
304
+					'order'      => 5,
305
+					'persistent' => false,
306
+				),
307
+				'metaboxes'     => array('_register_event_editor_meta_boxes'),
308
+				'help_tabs'     => array(
309
+					'event_editor_help_tab'                            => array(
310
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
311
+						'filename' => 'event_editor',
312
+					),
313
+					'event_editor_title_richtexteditor_help_tab'       => array(
314
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
315
+						'filename' => 'event_editor_title_richtexteditor',
316
+					),
317
+					'event_editor_venue_details_help_tab'              => array(
318
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
319
+						'filename' => 'event_editor_venue_details',
320
+					),
321
+					'event_editor_event_datetimes_help_tab'            => array(
322
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
323
+						'filename' => 'event_editor_event_datetimes',
324
+					),
325
+					'event_editor_event_tickets_help_tab'              => array(
326
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
327
+						'filename' => 'event_editor_event_tickets',
328
+					),
329
+					'event_editor_event_registration_options_help_tab' => array(
330
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
331
+						'filename' => 'event_editor_event_registration_options',
332
+					),
333
+					'event_editor_tags_categories_help_tab'            => array(
334
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
335
+						'filename' => 'event_editor_tags_categories',
336
+					),
337
+					'event_editor_questions_registrants_help_tab'      => array(
338
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
339
+						'filename' => 'event_editor_questions_registrants',
340
+					),
341
+					'event_editor_save_new_event_help_tab'             => array(
342
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
343
+						'filename' => 'event_editor_save_new_event',
344
+					),
345
+					'event_editor_other_help_tab'                      => array(
346
+						'title'    => esc_html__('Event Other', 'event_espresso'),
347
+						'filename' => 'event_editor_other',
348
+					),
349
+				),
350
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
351
+				// 'help_tour'     => array(
352
+				//     'Event_Editor_Help_Tour',
353
+				// ),
354
+				'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
355
+				'require_nonce' => false,
356
+			),
357
+			'edit'                   => array(
358
+				'nav'           => array(
359
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
360
+					'order'      => 5,
361
+					'persistent' => false,
362
+					'url'        => isset($this->_req_data['post'])
363
+						? EE_Admin_Page::add_query_args_and_nonce(
364
+							array('post' => $this->_req_data['post'], 'action' => 'edit'),
365
+							$this->_current_page_view_url
366
+						)
367
+						: $this->_admin_base_url,
368
+				),
369
+				'metaboxes'     => array('_register_event_editor_meta_boxes'),
370
+				'help_tabs'     => array(
371
+					'event_editor_help_tab'                            => array(
372
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
373
+						'filename' => 'event_editor',
374
+					),
375
+					'event_editor_title_richtexteditor_help_tab'       => array(
376
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
377
+						'filename' => 'event_editor_title_richtexteditor',
378
+					),
379
+					'event_editor_venue_details_help_tab'              => array(
380
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
381
+						'filename' => 'event_editor_venue_details',
382
+					),
383
+					'event_editor_event_datetimes_help_tab'            => array(
384
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
385
+						'filename' => 'event_editor_event_datetimes',
386
+					),
387
+					'event_editor_event_tickets_help_tab'              => array(
388
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
389
+						'filename' => 'event_editor_event_tickets',
390
+					),
391
+					'event_editor_event_registration_options_help_tab' => array(
392
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
393
+						'filename' => 'event_editor_event_registration_options',
394
+					),
395
+					'event_editor_tags_categories_help_tab'            => array(
396
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
397
+						'filename' => 'event_editor_tags_categories',
398
+					),
399
+					'event_editor_questions_registrants_help_tab'      => array(
400
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
401
+						'filename' => 'event_editor_questions_registrants',
402
+					),
403
+					'event_editor_save_new_event_help_tab'             => array(
404
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
405
+						'filename' => 'event_editor_save_new_event',
406
+					),
407
+					'event_editor_other_help_tab'                      => array(
408
+						'title'    => esc_html__('Event Other', 'event_espresso'),
409
+						'filename' => 'event_editor_other',
410
+					),
411
+				),
412
+				'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
413
+				'require_nonce' => false,
414
+			),
415
+			'default_event_settings' => array(
416
+				'nav'           => array(
417
+					'label' => esc_html__('Default Settings', 'event_espresso'),
418
+					'order' => 40,
419
+				),
420
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
421
+				'labels'        => array(
422
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
423
+				),
424
+				'help_tabs'     => array(
425
+					'default_settings_help_tab'        => array(
426
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
427
+						'filename' => 'events_default_settings',
428
+					),
429
+					'default_settings_status_help_tab' => array(
430
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
431
+						'filename' => 'events_default_settings_status',
432
+					),
433
+					'default_maximum_tickets_help_tab' => array(
434
+						'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
435
+						'filename' => 'events_default_settings_max_tickets',
436
+					),
437
+				),
438
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
439
+				// 'help_tour'     => array('Event_Default_Settings_Help_Tour'),
440
+				'require_nonce' => false,
441
+			),
442
+			// template settings
443
+			'template_settings'      => array(
444
+				'nav'           => array(
445
+					'label' => esc_html__('Templates', 'event_espresso'),
446
+					'order' => 30,
447
+				),
448
+				'metaboxes'     => $this->_default_espresso_metaboxes,
449
+				'help_tabs'     => array(
450
+					'general_settings_templates_help_tab' => array(
451
+						'title'    => esc_html__('Templates', 'event_espresso'),
452
+						'filename' => 'general_settings_templates',
453
+					),
454
+				),
455
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
456
+				// 'help_tour'     => array('Templates_Help_Tour'),
457
+				'require_nonce' => false,
458
+			),
459
+			// event category stuff
460
+			'add_category'           => array(
461
+				'nav'           => array(
462
+					'label'      => esc_html__('Add Category', 'event_espresso'),
463
+					'order'      => 15,
464
+					'persistent' => false,
465
+				),
466
+				'help_tabs'     => array(
467
+					'add_category_help_tab' => array(
468
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
469
+						'filename' => 'events_add_category',
470
+					),
471
+				),
472
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
473
+				// 'help_tour'     => array('Event_Add_Category_Help_Tour'),
474
+				'metaboxes'     => array('_publish_post_box'),
475
+				'require_nonce' => false,
476
+			),
477
+			'edit_category'          => array(
478
+				'nav'           => array(
479
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
480
+					'order'      => 15,
481
+					'persistent' => false,
482
+					'url'        => isset($this->_req_data['EVT_CAT_ID'])
483
+						? add_query_arg(
484
+							array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID']),
485
+							$this->_current_page_view_url
486
+						)
487
+						: $this->_admin_base_url,
488
+				),
489
+				'help_tabs'     => array(
490
+					'edit_category_help_tab' => array(
491
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
492
+						'filename' => 'events_edit_category',
493
+					),
494
+				),
495
+				/*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
496
+				'metaboxes'     => array('_publish_post_box'),
497
+				'require_nonce' => false,
498
+			),
499
+			'category_list'          => array(
500
+				'nav'           => array(
501
+					'label' => esc_html__('Categories', 'event_espresso'),
502
+					'order' => 20,
503
+				),
504
+				'list_table'    => 'Event_Categories_Admin_List_Table',
505
+				'help_tabs'     => array(
506
+					'events_categories_help_tab'                       => array(
507
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
508
+						'filename' => 'events_categories',
509
+					),
510
+					'events_categories_table_column_headings_help_tab' => array(
511
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
512
+						'filename' => 'events_categories_table_column_headings',
513
+					),
514
+					'events_categories_view_help_tab'                  => array(
515
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
516
+						'filename' => 'events_categories_views',
517
+					),
518
+					'events_categories_other_help_tab'                 => array(
519
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
520
+						'filename' => 'events_categories_other',
521
+					),
522
+				),
523
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
524
+				// 'help_tour'     => array(
525
+				//     'Event_Categories_Help_Tour',
526
+				// ),
527
+				'metaboxes'     => $this->_default_espresso_metaboxes,
528
+				'require_nonce' => false,
529
+			),
530
+			'preview_deletion'           => array(
531
+				'nav'           => array(
532
+					'label'      => esc_html__('Preview Deletion', 'event_espresso'),
533
+					'order'      => 15,
534
+					'persistent' => false,
535
+					'url'        => '',
536
+				),
537
+				'require_nonce' => false
538
+			)
539
+		);
540
+	}
541
+
542
+
543
+	/**
544
+	 * Used to register any global screen options if necessary for every route in this admin page group.
545
+	 */
546
+	protected function _add_screen_options()
547
+	{
548
+	}
549
+
550
+
551
+	/**
552
+	 * Implementing the screen options for the 'default' route.
553
+	 */
554
+	protected function _add_screen_options_default()
555
+	{
556
+		$this->_per_page_screen_option();
557
+	}
558
+
559
+
560
+	/**
561
+	 * Implementing screen options for the category list route.
562
+	 */
563
+	protected function _add_screen_options_category_list()
564
+	{
565
+		$page_title = $this->_admin_page_title;
566
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
567
+		$this->_per_page_screen_option();
568
+		$this->_admin_page_title = $page_title;
569
+	}
570
+
571
+
572
+	/**
573
+	 * Used to register any global feature pointers for the admin page group.
574
+	 */
575
+	protected function _add_feature_pointers()
576
+	{
577
+	}
578
+
579
+
580
+	/**
581
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
582
+	 */
583
+	public function load_scripts_styles()
584
+	{
585
+		wp_register_style(
586
+			'events-admin-css',
587
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
588
+			array(),
589
+			EVENT_ESPRESSO_VERSION
590
+		);
591
+		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION);
592
+		wp_enqueue_style('events-admin-css');
593
+		wp_enqueue_style('ee-cat-admin');
594
+		// todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
595
+		// registers for all views
596
+		// scripts
597
+		wp_register_script(
598
+			'event_editor_js',
599
+			EVENTS_ASSETS_URL . 'event_editor.js',
600
+			array('ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'),
601
+			EVENT_ESPRESSO_VERSION,
602
+			true
603
+		);
604
+	}
605
+
606
+
607
+	/**
608
+	 * Enqueuing scripts and styles specific to this view
609
+	 */
610
+	public function load_scripts_styles_create_new()
611
+	{
612
+		$this->load_scripts_styles_edit();
613
+	}
614
+
615
+
616
+	/**
617
+	 * Enqueuing scripts and styles specific to this view
618
+	 */
619
+	public function load_scripts_styles_edit()
620
+	{
621
+		// styles
622
+		wp_enqueue_style('espresso-ui-theme');
623
+		wp_register_style(
624
+			'event-editor-css',
625
+			EVENTS_ASSETS_URL . 'event-editor.css',
626
+			array('ee-admin-css'),
627
+			EVENT_ESPRESSO_VERSION
628
+		);
629
+		wp_enqueue_style('event-editor-css');
630
+		// scripts
631
+		wp_register_script(
632
+			'event-datetime-metabox',
633
+			EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
634
+			array('event_editor_js', 'ee-datepicker'),
635
+			EVENT_ESPRESSO_VERSION
636
+		);
637
+		wp_enqueue_script('event-datetime-metabox');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Populating the _views property for the category list table view.
643
+	 */
644
+	protected function _set_list_table_views_category_list()
645
+	{
646
+		$this->_views = array(
647
+			'all' => array(
648
+				'slug'        => 'all',
649
+				'label'       => esc_html__('All', 'event_espresso'),
650
+				'count'       => 0,
651
+				'bulk_action' => array(
652
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
653
+				),
654
+			),
655
+		);
656
+	}
657
+
658
+
659
+	/**
660
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
661
+	 */
662
+	public function admin_init()
663
+	{
664
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
665
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
666
+			'event_espresso'
667
+		);
668
+	}
669
+
670
+
671
+	/**
672
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
673
+	 * group.
674
+	 */
675
+	public function admin_notices()
676
+	{
677
+	}
678
+
679
+
680
+	/**
681
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
682
+	 * this admin page group.
683
+	 */
684
+	public function admin_footer_scripts()
685
+	{
686
+	}
687
+
688
+
689
+	/**
690
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
691
+	 * warning (via EE_Error::add_error());
692
+	 *
693
+	 * @param  EE_Event $event Event object
694
+	 * @param string    $req_type
695
+	 * @return void
696
+	 * @throws EE_Error
697
+	 * @access public
698
+	 */
699
+	public function verify_event_edit($event = null, $req_type = '')
700
+	{
701
+		// don't need to do this when processing
702
+		if (! empty($req_type)) {
703
+			return;
704
+		}
705
+		// no event?
706
+		if (empty($event)) {
707
+			// set event
708
+			$event = $this->_cpt_model_obj;
709
+		}
710
+		// STILL no event?
711
+		if (! $event instanceof EE_Event) {
712
+			return;
713
+		}
714
+		$orig_status = $event->status();
715
+		// first check if event is active.
716
+		if ($orig_status === EEM_Event::cancelled
717
+			|| $orig_status === EEM_Event::postponed
718
+			|| $event->is_expired()
719
+			|| $event->is_inactive()
720
+		) {
721
+			return;
722
+		}
723
+		// made it here so it IS active... next check that any of the tickets are sold.
724
+		if ($event->is_sold_out(true)) {
725
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
726
+				EE_Error::add_attention(
727
+					sprintf(
728
+						esc_html__(
729
+							'Please note that the Event Status has automatically been changed to %s because there are no more spaces available for this event.  However, this change is not permanent until you update the event.  You can change the status back to something else before updating if you wish.',
730
+							'event_espresso'
731
+						),
732
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
733
+					)
734
+				);
735
+			}
736
+			return;
737
+		} elseif ($orig_status === EEM_Event::sold_out) {
738
+			EE_Error::add_attention(
739
+				sprintf(
740
+					esc_html__(
741
+						'Please note that the Event Status has automatically been changed to %s because more spaces have become available for this event, most likely due to abandoned transactions freeing up reserved tickets.  However, this change is not permanent until you update the event. If you wish, you can change the status back to something else before updating.',
742
+						'event_espresso'
743
+					),
744
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
745
+				)
746
+			);
747
+		}
748
+		// now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
749
+		if (! $event->tickets_on_sale()) {
750
+			return;
751
+		}
752
+		// made it here so show warning
753
+		$this->_edit_event_warning();
754
+	}
755
+
756
+
757
+	/**
758
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
759
+	 * When needed, hook this into a EE_Error::add_error() notice.
760
+	 *
761
+	 * @access protected
762
+	 * @return void
763
+	 */
764
+	protected function _edit_event_warning()
765
+	{
766
+		// we don't want to add warnings during these requests
767
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'editpost') {
768
+			return;
769
+		}
770
+		EE_Error::add_attention(
771
+			sprintf(
772
+				esc_html__(
773
+					'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
774
+					'event_espresso'
775
+				),
776
+				'<a class="espresso-help-tab-lnk">',
777
+				'</a>'
778
+			)
779
+		);
780
+	}
781
+
782
+
783
+	/**
784
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
785
+	 * Otherwise, do the normal logic
786
+	 *
787
+	 * @return string
788
+	 * @throws \EE_Error
789
+	 */
790
+	protected function _create_new_cpt_item()
791
+	{
792
+		$has_timezone_string = get_option('timezone_string');
793
+		// only nag them about setting their timezone if it's their first event, and they haven't already done it
794
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists(array())) {
795
+			EE_Error::add_attention(
796
+				sprintf(
797
+					__(
798
+						'Your website\'s timezone is currently set to a UTC offset. We recommend updating your timezone to a city or region near you before you create an event. Change your timezone now:%1$s%2$s%3$sChange Timezone%4$s',
799
+						'event_espresso'
800
+					),
801
+					'<br>',
802
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
803
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
804
+					. '</select>',
805
+					'<button class="button button-secondary timezone-submit">',
806
+					'</button><span class="spinner"></span>'
807
+				),
808
+				__FILE__,
809
+				__FUNCTION__,
810
+				__LINE__
811
+			);
812
+		}
813
+		return parent::_create_new_cpt_item();
814
+	}
815
+
816
+
817
+	/**
818
+	 * Sets the _views property for the default route in this admin page group.
819
+	 */
820
+	protected function _set_list_table_views_default()
821
+	{
822
+		$this->_views = array(
823
+			'all'   => array(
824
+				'slug'        => 'all',
825
+				'label'       => esc_html__('View All Events', 'event_espresso'),
826
+				'count'       => 0,
827
+				'bulk_action' => array(
828
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
829
+				),
830
+			),
831
+			'draft' => array(
832
+				'slug'        => 'draft',
833
+				'label'       => esc_html__('Draft', 'event_espresso'),
834
+				'count'       => 0,
835
+				'bulk_action' => array(
836
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
837
+				),
838
+			),
839
+		);
840
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
841
+			$this->_views['trash'] = array(
842
+				'slug'        => 'trash',
843
+				'label'       => esc_html__('Trash', 'event_espresso'),
844
+				'count'       => 0,
845
+				'bulk_action' => array(
846
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
847
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
848
+				),
849
+			);
850
+		}
851
+	}
852
+
853
+
854
+	/**
855
+	 * Provides the legend item array for the default list table view.
856
+	 *
857
+	 * @return array
858
+	 */
859
+	protected function _event_legend_items()
860
+	{
861
+		$items = array(
862
+			'view_details'   => array(
863
+				'class' => 'dashicons dashicons-search',
864
+				'desc'  => esc_html__('View Event', 'event_espresso'),
865
+			),
866
+			'edit_event'     => array(
867
+				'class' => 'ee-icon ee-icon-calendar-edit',
868
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
869
+			),
870
+			'view_attendees' => array(
871
+				'class' => 'dashicons dashicons-groups',
872
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
873
+			),
874
+		);
875
+		$items = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
876
+		$statuses = array(
877
+			'sold_out_status'  => array(
878
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
879
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
880
+			),
881
+			'active_status'    => array(
882
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
883
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
884
+			),
885
+			'upcoming_status'  => array(
886
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
887
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
888
+			),
889
+			'postponed_status' => array(
890
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
891
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
892
+			),
893
+			'cancelled_status' => array(
894
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
895
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
896
+			),
897
+			'expired_status'   => array(
898
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
899
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
900
+			),
901
+			'inactive_status'  => array(
902
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
903
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
904
+			),
905
+		);
906
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
907
+		return array_merge($items, $statuses);
908
+	}
909
+
910
+
911
+	/**
912
+	 * @return EEM_Event
913
+	 */
914
+	private function _event_model()
915
+	{
916
+		if (! $this->_event_model instanceof EEM_Event) {
917
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
918
+		}
919
+		return $this->_event_model;
920
+	}
921
+
922
+
923
+	/**
924
+	 * Adds extra buttons to the WP CPT permalink field row.
925
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
926
+	 *
927
+	 * @param  string $return    the current html
928
+	 * @param  int    $id        the post id for the page
929
+	 * @param  string $new_title What the title is
930
+	 * @param  string $new_slug  what the slug is
931
+	 * @return string            The new html string for the permalink area
932
+	 */
933
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
934
+	{
935
+		// make sure this is only when editing
936
+		if (! empty($id)) {
937
+			$post = get_post($id);
938
+			$return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
939
+					   . esc_html__('Shortcode', 'event_espresso')
940
+					   . '</a> ';
941
+			$return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
942
+					   . $post->ID
943
+					   . ']">';
944
+		}
945
+		return $return;
946
+	}
947
+
948
+
949
+	/**
950
+	 * _events_overview_list_table
951
+	 * This contains the logic for showing the events_overview list
952
+	 *
953
+	 * @access protected
954
+	 * @return void
955
+	 * @throws \EE_Error
956
+	 */
957
+	protected function _events_overview_list_table()
958
+	{
959
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
960
+		$this->_template_args['after_list_table'] = ! empty($this->_template_args['after_list_table'])
961
+			? (array) $this->_template_args['after_list_table']
962
+			: array();
963
+		$this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
964
+				. EEH_Template::get_button_or_link(
965
+					get_post_type_archive_link('espresso_events'),
966
+					esc_html__("View Event Archive Page", "event_espresso"),
967
+					'button'
968
+				);
969
+		$this->_template_args['after_list_table']['legend'] = $this->_display_legend($this->_event_legend_items());
970
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
971
+			'create_new',
972
+			'add',
973
+			array(),
974
+			'add-new-h2'
975
+		);
976
+		$this->display_admin_list_table_page_with_no_sidebar();
977
+	}
978
+
979
+
980
+	/**
981
+	 * this allows for extra misc actions in the default WP publish box
982
+	 *
983
+	 * @return void
984
+	 */
985
+	public function extra_misc_actions_publish_box()
986
+	{
987
+		$this->_generate_publish_box_extra_content();
988
+	}
989
+
990
+
991
+	/**
992
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
993
+	 * saved.
994
+	 * Typically you would use this to save any additional data.
995
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
996
+	 * ALSO very important.  When a post transitions from scheduled to published,
997
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
998
+	 * other meta saves. So MAKE sure that you handle this accordingly.
999
+	 *
1000
+	 * @access protected
1001
+	 * @abstract
1002
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
1003
+	 * @param  object $post    The post object of the cpt that was saved.
1004
+	 * @return void
1005
+	 * @throws \EE_Error
1006
+	 */
1007
+	protected function _insert_update_cpt_item($post_id, $post)
1008
+	{
1009
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1010
+			// get out we're not processing an event save.
1011
+			return;
1012
+		}
1013
+		$event_values = array(
1014
+			'EVT_display_desc'                => ! empty($this->_req_data['display_desc']) ? 1 : 0,
1015
+			'EVT_display_ticket_selector'     => ! empty($this->_req_data['display_ticket_selector']) ? 1 : 0,
1016
+			'EVT_additional_limit'            => min(
1017
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1018
+				! empty($this->_req_data['additional_limit']) ? $this->_req_data['additional_limit'] : null
1019
+			),
1020
+			'EVT_default_registration_status' => ! empty($this->_req_data['EVT_default_registration_status'])
1021
+				? $this->_req_data['EVT_default_registration_status']
1022
+				: EE_Registry::instance()->CFG->registration->default_STS_ID,
1023
+			'EVT_member_only'                 => ! empty($this->_req_data['member_only']) ? 1 : 0,
1024
+			'EVT_allow_overflow'              => ! empty($this->_req_data['EVT_allow_overflow']) ? 1 : 0,
1025
+			'EVT_timezone_string'             => ! empty($this->_req_data['timezone_string'])
1026
+				? $this->_req_data['timezone_string'] : null,
1027
+			'EVT_external_URL'                => ! empty($this->_req_data['externalURL'])
1028
+				? $this->_req_data['externalURL'] : null,
1029
+			'EVT_phone'                       => ! empty($this->_req_data['event_phone'])
1030
+				? $this->_req_data['event_phone'] : null,
1031
+		);
1032
+		// update event
1033
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1034
+		// get event_object for other metaboxes... though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id ).. i have to setup where conditions to override the filters in the model that filter out autodraft and inherit statuses so we GET the inherit id!
1035
+		$get_one_where = array(
1036
+			$this->_event_model()->primary_key_name() => $post_id,
1037
+			'OR'                                      => array(
1038
+				'status'   => $post->post_status,
1039
+				// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1040
+				// but the returned object here has a status of "publish", so use the original post status as well
1041
+				'status*1' => $this->_req_data['original_post_status'],
1042
+			),
1043
+		);
1044
+		$event = $this->_event_model()->get_one(array($get_one_where));
1045
+		// the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1046
+		$event_update_callbacks = apply_filters(
1047
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1048
+			array(
1049
+				array($this, '_default_venue_update'),
1050
+				array($this, '_default_tickets_update'),
1051
+			)
1052
+		);
1053
+		$att_success = true;
1054
+		foreach ($event_update_callbacks as $e_callback) {
1055
+			$_success = is_callable($e_callback)
1056
+				? call_user_func($e_callback, $event, $this->_req_data)
1057
+				: false;
1058
+			// if ANY of these updates fail then we want the appropriate global error message
1059
+			$att_success = ! $att_success ? $att_success : $_success;
1060
+		}
1061
+		// any errors?
1062
+		if ($success && false === $att_success) {
1063
+			EE_Error::add_error(
1064
+				esc_html__(
1065
+					'Event Details saved successfully but something went wrong with saving attachments.',
1066
+					'event_espresso'
1067
+				),
1068
+				__FILE__,
1069
+				__FUNCTION__,
1070
+				__LINE__
1071
+			);
1072
+		} elseif ($success === false) {
1073
+			EE_Error::add_error(
1074
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1075
+				__FILE__,
1076
+				__FUNCTION__,
1077
+				__LINE__
1078
+			);
1079
+		}
1080
+	}
1081
+
1082
+
1083
+	/**
1084
+	 * @see parent::restore_item()
1085
+	 * @param int $post_id
1086
+	 * @param int $revision_id
1087
+	 */
1088
+	protected function _restore_cpt_item($post_id, $revision_id)
1089
+	{
1090
+		// copy existing event meta to new post
1091
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1092
+		if ($post_evt instanceof EE_Event) {
1093
+			// meta revision restore
1094
+			$post_evt->restore_revision($revision_id);
1095
+			// related objs restore
1096
+			$post_evt->restore_revision($revision_id, array('Venue', 'Datetime', 'Price'));
1097
+		}
1098
+	}
1099
+
1100
+
1101
+	/**
1102
+	 * Attach the venue to the Event
1103
+	 *
1104
+	 * @param  \EE_Event $evtobj Event Object to add the venue to
1105
+	 * @param  array     $data   The request data from the form
1106
+	 * @return bool           Success or fail.
1107
+	 */
1108
+	protected function _default_venue_update(\EE_Event $evtobj, $data)
1109
+	{
1110
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1111
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1112
+		$rows_affected = null;
1113
+		$venue_id = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1114
+		// very important.  If we don't have a venue name...
1115
+		// then we'll get out because not necessary to create empty venue
1116
+		if (empty($data['venue_title'])) {
1117
+			return false;
1118
+		}
1119
+		$venue_array = array(
1120
+			'VNU_wp_user'         => $evtobj->get('EVT_wp_user'),
1121
+			'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1122
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1123
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1124
+			'VNU_short_desc'      => ! empty($data['venue_short_description']) ? $data['venue_short_description']
1125
+				: null,
1126
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1127
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1128
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1129
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1130
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1131
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1132
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1133
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1134
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1135
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1136
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1137
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1138
+			'status'              => 'publish',
1139
+		);
1140
+		// if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1141
+		if (! empty($venue_id)) {
1142
+			$update_where = array($venue_model->primary_key_name() => $venue_id);
1143
+			$rows_affected = $venue_model->update($venue_array, array($update_where));
1144
+			// we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1145
+			$evtobj->_add_relation_to($venue_id, 'Venue');
1146
+			return $rows_affected > 0 ? true : false;
1147
+		} else {
1148
+			// we insert the venue
1149
+			$venue_id = $venue_model->insert($venue_array);
1150
+			$evtobj->_add_relation_to($venue_id, 'Venue');
1151
+			return ! empty($venue_id) ? true : false;
1152
+		}
1153
+		// when we have the ancestor come in it's already been handled by the revision save.
1154
+	}
1155
+
1156
+
1157
+	/**
1158
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1159
+	 *
1160
+	 * @param  EE_Event $evtobj The Event object we're attaching data to
1161
+	 * @param  array    $data   The request data from the form
1162
+	 * @return array
1163
+	 */
1164
+	protected function _default_tickets_update(EE_Event $evtobj, $data)
1165
+	{
1166
+		$success = true;
1167
+		$saved_dtt = null;
1168
+		$saved_tickets = array();
1169
+		$incoming_date_formats = array('Y-m-d', 'h:i a');
1170
+		foreach ($data['edit_event_datetimes'] as $row => $dtt) {
1171
+			// trim all values to ensure any excess whitespace is removed.
1172
+			$dtt = array_map('trim', $dtt);
1173
+			$dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end']
1174
+				: $dtt['DTT_EVT_start'];
1175
+			$datetime_values = array(
1176
+				'DTT_ID'        => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
1177
+				'DTT_EVT_start' => $dtt['DTT_EVT_start'],
1178
+				'DTT_EVT_end'   => $dtt['DTT_EVT_end'],
1179
+				'DTT_reg_limit' => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
1180
+				'DTT_order'     => $row,
1181
+			);
1182
+			// if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
1183
+			if (! empty($dtt['DTT_ID'])) {
1184
+				$DTM = EE_Registry::instance()
1185
+								  ->load_model('Datetime', array($evtobj->get_timezone()))
1186
+								  ->get_one_by_ID($dtt['DTT_ID']);
1187
+				$DTM->set_date_format($incoming_date_formats[0]);
1188
+				$DTM->set_time_format($incoming_date_formats[1]);
1189
+				foreach ($datetime_values as $field => $value) {
1190
+					$DTM->set($field, $value);
1191
+				}
1192
+				// make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.  We need to do this so we dont' TRASH the parent DTT.
1193
+				$saved_dtts[ $DTM->ID() ] = $DTM;
1194
+			} else {
1195
+				$DTM = EE_Registry::instance()->load_class(
1196
+					'Datetime',
1197
+					array($datetime_values, $evtobj->get_timezone(), $incoming_date_formats),
1198
+					false,
1199
+					false
1200
+				);
1201
+				foreach ($datetime_values as $field => $value) {
1202
+					$DTM->set($field, $value);
1203
+				}
1204
+			}
1205
+			$DTM->save();
1206
+			$DTT = $evtobj->_add_relation_to($DTM, 'Datetime');
1207
+			// load DTT helper
1208
+			// before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1209
+			if ($DTT->get_raw('DTT_EVT_start') > $DTT->get_raw('DTT_EVT_end')) {
1210
+				$DTT->set('DTT_EVT_end', $DTT->get('DTT_EVT_start'));
1211
+				$DTT = EEH_DTT_Helper::date_time_add($DTT, 'DTT_EVT_end', 'days');
1212
+				$DTT->save();
1213
+			}
1214
+			// now we got to make sure we add the new DTT_ID to the $saved_dtts array  because it is possible there was a new one created for the autosave.
1215
+			$saved_dtt = $DTT;
1216
+			$success = ! $success ? $success : $DTT;
1217
+			// if ANY of these updates fail then we want the appropriate global error message.
1218
+			// //todo this is actually sucky we need a better error message but this is what it is for now.
1219
+		}
1220
+		// no dtts get deleted so we don't do any of that logic here.
1221
+		// update tickets next
1222
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
1223
+		foreach ($data['edit_tickets'] as $row => $tkt) {
1224
+			$incoming_date_formats = array('Y-m-d', 'h:i a');
1225
+			$update_prices = false;
1226
+			$ticket_price = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1227
+				? $data['edit_prices'][ $row ][1]['PRC_amount'] : 0;
1228
+			// trim inputs to ensure any excess whitespace is removed.
1229
+			$tkt = array_map('trim', $tkt);
1230
+			if (empty($tkt['TKT_start_date'])) {
1231
+				// let's use now in the set timezone.
1232
+				$now = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
1233
+				$tkt['TKT_start_date'] = $now->format($incoming_date_formats[0] . ' ' . $incoming_date_formats[1]);
1234
+			}
1235
+			if (empty($tkt['TKT_end_date'])) {
1236
+				// use the start date of the first datetime
1237
+				$dtt = $evtobj->first_datetime();
1238
+				$tkt['TKT_end_date'] = $dtt->start_date_and_time(
1239
+					$incoming_date_formats[0],
1240
+					$incoming_date_formats[1]
1241
+				);
1242
+			}
1243
+			$TKT_values = array(
1244
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
1245
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
1246
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
1247
+				'TKT_description' => ! empty($tkt['TKT_description']) ? $tkt['TKT_description'] : '',
1248
+				'TKT_start_date'  => $tkt['TKT_start_date'],
1249
+				'TKT_end_date'    => $tkt['TKT_end_date'],
1250
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
1251
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
1252
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
1253
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
1254
+				'TKT_row'         => $row,
1255
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : $row,
1256
+				'TKT_price'       => $ticket_price,
1257
+			);
1258
+			// if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
1259
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
1260
+				$TKT_values['TKT_ID'] = 0;
1261
+				$TKT_values['TKT_is_default'] = 0;
1262
+				$TKT_values['TKT_price'] = $ticket_price;
1263
+				$update_prices = true;
1264
+			}
1265
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
1266
+			// we actually do our saves a head of doing any add_relations to because its entirely possible that this ticket didn't removed or added to any datetime in the session but DID have it's items modified.
1267
+			// keep in mind that if the TKT has been sold (and we have changed pricing information), then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1268
+			if (! empty($tkt['TKT_ID'])) {
1269
+				$TKT = EE_Registry::instance()
1270
+								  ->load_model('Ticket', array($evtobj->get_timezone()))
1271
+								  ->get_one_by_ID($tkt['TKT_ID']);
1272
+				if ($TKT instanceof EE_Ticket) {
1273
+					$ticket_sold = $TKT->count_related(
1274
+						'Registration',
1275
+						array(
1276
+							array(
1277
+								'STS_ID' => array(
1278
+									'NOT IN',
1279
+									array(EEM_Registration::status_id_incomplete),
1280
+								),
1281
+							),
1282
+						)
1283
+					) > 0 ? true : false;
1284
+					// let's just check the total price for the existing ticket and determine if it matches the new total price.  if they are different then we create a new ticket (if tkts sold) if they aren't different then we go ahead and modify existing ticket.
1285
+					$create_new_TKT = $ticket_sold && $ticket_price != $TKT->get('TKT_price')
1286
+									  && ! $TKT->get('TKT_deleted');
1287
+					$TKT->set_date_format($incoming_date_formats[0]);
1288
+					$TKT->set_time_format($incoming_date_formats[1]);
1289
+					// set new values
1290
+					foreach ($TKT_values as $field => $value) {
1291
+						if ($field == 'TKT_qty') {
1292
+							$TKT->set_qty($value);
1293
+						} else {
1294
+							$TKT->set($field, $value);
1295
+						}
1296
+					}
1297
+					// if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
1298
+					if ($create_new_TKT) {
1299
+						// archive the old ticket first
1300
+						$TKT->set('TKT_deleted', 1);
1301
+						$TKT->save();
1302
+						// make sure this ticket is still recorded in our saved_tkts so we don't run it through the regular trash routine.
1303
+						$saved_tickets[ $TKT->ID() ] = $TKT;
1304
+						// create new ticket that's a copy of the existing except a new id of course (and not archived) AND has the new TKT_price associated with it.
1305
+						$TKT = clone $TKT;
1306
+						$TKT->set('TKT_ID', 0);
1307
+						$TKT->set('TKT_deleted', 0);
1308
+						$TKT->set('TKT_price', $ticket_price);
1309
+						$TKT->set('TKT_sold', 0);
1310
+						// now we need to make sure that $new prices are created as well and attached to new ticket.
1311
+						$update_prices = true;
1312
+					}
1313
+					// make sure price is set if it hasn't been already
1314
+					$TKT->set('TKT_price', $ticket_price);
1315
+				}
1316
+			} else {
1317
+				// no TKT_id so a new TKT
1318
+				$TKT_values['TKT_price'] = $ticket_price;
1319
+				$TKT = EE_Registry::instance()->load_class('Ticket', array($TKT_values), false, false);
1320
+				if ($TKT instanceof EE_Ticket) {
1321
+					// need to reset values to properly account for the date formats
1322
+					$TKT->set_date_format($incoming_date_formats[0]);
1323
+					$TKT->set_time_format($incoming_date_formats[1]);
1324
+					$TKT->set_timezone($evtobj->get_timezone());
1325
+					// set new values
1326
+					foreach ($TKT_values as $field => $value) {
1327
+						if ($field == 'TKT_qty') {
1328
+							$TKT->set_qty($value);
1329
+						} else {
1330
+							$TKT->set($field, $value);
1331
+						}
1332
+					}
1333
+					$update_prices = true;
1334
+				}
1335
+			}
1336
+			// cap ticket qty by datetime reg limits
1337
+			$TKT->set_qty(min($TKT->qty(), $TKT->qty('reg_limit')));
1338
+			// update ticket.
1339
+			$TKT->save();
1340
+			// before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1341
+			if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
1342
+				$TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
1343
+				$TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
1344
+				$TKT->save();
1345
+			}
1346
+			// initially let's add the ticket to the dtt
1347
+			$saved_dtt->_add_relation_to($TKT, 'Ticket');
1348
+			$saved_tickets[ $TKT->ID() ] = $TKT;
1349
+			// add prices to ticket
1350
+			$this->_add_prices_to_ticket($data['edit_prices'][ $row ], $TKT, $update_prices);
1351
+		}
1352
+		// however now we need to handle permanently deleting tickets via the ui.  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.  However, it does allow for deleting tickets that have no tickets sold, in which case we want to get rid of permanently because there is no need to save in db.
1353
+		$old_tickets = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
1354
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1355
+		foreach ($tickets_removed as $id) {
1356
+			$id = absint($id);
1357
+			// get the ticket for this id
1358
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
1359
+			// need to get all the related datetimes on this ticket and remove from every single one of them (remember this process can ONLY kick off if there are NO tkts_sold)
1360
+			$dtts = $tkt_to_remove->get_many_related('Datetime');
1361
+			foreach ($dtts as $dtt) {
1362
+				$tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
1363
+			}
1364
+			// need to do the same for prices (except these prices can also be deleted because again, tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1365
+			$tkt_to_remove->delete_related_permanently('Price');
1366
+			// finally let's delete this ticket (which should not be blocked at this point b/c we've removed all our relationships)
1367
+			$tkt_to_remove->delete_permanently();
1368
+		}
1369
+		return array($saved_dtt, $saved_tickets);
1370
+	}
1371
+
1372
+
1373
+	/**
1374
+	 * This attaches a list of given prices to a ticket.
1375
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1376
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1377
+	 * price info and prices are automatically "archived" via the ticket.
1378
+	 *
1379
+	 * @access  private
1380
+	 * @param array     $prices     Array of prices from the form.
1381
+	 * @param EE_Ticket $ticket     EE_Ticket object that prices are being attached to.
1382
+	 * @param bool      $new_prices Whether attach existing incoming prices or create new ones.
1383
+	 * @return  void
1384
+	 */
1385
+	private function _add_prices_to_ticket($prices, EE_Ticket $ticket, $new_prices = false)
1386
+	{
1387
+		foreach ($prices as $row => $prc) {
1388
+			$PRC_values = array(
1389
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
1390
+				'PRT_ID'         => ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null,
1391
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
1392
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
1393
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
1394
+				'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1395
+				'PRC_order'      => $row,
1396
+			);
1397
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
1398
+				$PRC_values['PRC_ID'] = 0;
1399
+				$PRC = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
1400
+			} else {
1401
+				$PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
1402
+				// update this price with new values
1403
+				foreach ($PRC_values as $field => $newprc) {
1404
+					$PRC->set($field, $newprc);
1405
+				}
1406
+				$PRC->save();
1407
+			}
1408
+			$ticket->_add_relation_to($PRC, 'Price');
1409
+		}
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * Add in our autosave ajax handlers
1415
+	 *
1416
+	 */
1417
+	protected function _ee_autosave_create_new()
1418
+	{
1419
+	}
1420
+
1421
+
1422
+	/**
1423
+	 * More autosave handlers.
1424
+	 */
1425
+	protected function _ee_autosave_edit()
1426
+	{
1427
+		return; // TEMPORARILY EXITING CAUSE THIS IS A TODO
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 *    _generate_publish_box_extra_content
1433
+	 */
1434
+	private function _generate_publish_box_extra_content()
1435
+	{
1436
+		// load formatter helper
1437
+		// args for getting related registrations
1438
+		$approved_query_args = array(
1439
+			array(
1440
+				'REG_deleted' => 0,
1441
+				'STS_ID'      => EEM_Registration::status_id_approved,
1442
+			),
1443
+		);
1444
+		$not_approved_query_args = array(
1445
+			array(
1446
+				'REG_deleted' => 0,
1447
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1448
+			),
1449
+		);
1450
+		$pending_payment_query_args = array(
1451
+			array(
1452
+				'REG_deleted' => 0,
1453
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1454
+			),
1455
+		);
1456
+		// publish box
1457
+		$publish_box_extra_args = array(
1458
+			'view_approved_reg_url'        => add_query_arg(
1459
+				array(
1460
+					'action'      => 'default',
1461
+					'event_id'    => $this->_cpt_model_obj->ID(),
1462
+					'_reg_status' => EEM_Registration::status_id_approved,
1463
+				),
1464
+				REG_ADMIN_URL
1465
+			),
1466
+			'view_not_approved_reg_url'    => add_query_arg(
1467
+				array(
1468
+					'action'      => 'default',
1469
+					'event_id'    => $this->_cpt_model_obj->ID(),
1470
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1471
+				),
1472
+				REG_ADMIN_URL
1473
+			),
1474
+			'view_pending_payment_reg_url' => add_query_arg(
1475
+				array(
1476
+					'action'      => 'default',
1477
+					'event_id'    => $this->_cpt_model_obj->ID(),
1478
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1479
+				),
1480
+				REG_ADMIN_URL
1481
+			),
1482
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1483
+				'Registration',
1484
+				$approved_query_args
1485
+			),
1486
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1487
+				'Registration',
1488
+				$not_approved_query_args
1489
+			),
1490
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1491
+				'Registration',
1492
+				$pending_payment_query_args
1493
+			),
1494
+			'misc_pub_section_class'       => apply_filters(
1495
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1496
+				'misc-pub-section'
1497
+			),
1498
+		);
1499
+		ob_start();
1500
+		do_action(
1501
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1502
+			$this->_cpt_model_obj
1503
+		);
1504
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1505
+		// load template
1506
+		EEH_Template::display_template(
1507
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1508
+			$publish_box_extra_args
1509
+		);
1510
+	}
1511
+
1512
+
1513
+	/**
1514
+	 * @return EE_Event
1515
+	 */
1516
+	public function get_event_object()
1517
+	{
1518
+		return $this->_cpt_model_obj;
1519
+	}
1520
+
1521
+
1522
+
1523
+
1524
+	/** METABOXES * */
1525
+	/**
1526
+	 * _register_event_editor_meta_boxes
1527
+	 * add all metaboxes related to the event_editor
1528
+	 *
1529
+	 * @return void
1530
+	 */
1531
+	protected function _register_event_editor_meta_boxes()
1532
+	{
1533
+		$this->verify_cpt_object();
1534
+		add_meta_box(
1535
+			'espresso_event_editor_tickets',
1536
+			esc_html__('Event Datetime & Ticket', 'event_espresso'),
1537
+			array($this, 'ticket_metabox'),
1538
+			$this->page_slug,
1539
+			'normal',
1540
+			'high'
1541
+		);
1542
+		add_meta_box(
1543
+			'espresso_event_editor_event_options',
1544
+			esc_html__('Event Registration Options', 'event_espresso'),
1545
+			array($this, 'registration_options_meta_box'),
1546
+			$this->page_slug,
1547
+			'side',
1548
+			'default'
1549
+		);
1550
+		// NOTE: if you're looking for other metaboxes in here,
1551
+		// where a metabox has a related management page in the admin
1552
+		// you will find it setup in the related management page's "_Hooks" file.
1553
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1554
+	}
1555
+
1556
+
1557
+	/**
1558
+	 * @throws DomainException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	public function ticket_metabox()
1562
+	{
1563
+		$existing_datetime_ids = $existing_ticket_ids = array();
1564
+		// defaults for template args
1565
+		$template_args = array(
1566
+			'existing_datetime_ids'    => '',
1567
+			'event_datetime_help_link' => '',
1568
+			'ticket_options_help_link' => '',
1569
+			'time'                     => null,
1570
+			'ticket_rows'              => '',
1571
+			'existing_ticket_ids'      => '',
1572
+			'total_ticket_rows'        => 1,
1573
+			'ticket_js_structure'      => '',
1574
+			'trash_icon'               => 'ee-lock-icon',
1575
+			'disabled'                 => '',
1576
+		);
1577
+		$event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1578
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1579
+		/**
1580
+		 * 1. Start with retrieving Datetimes
1581
+		 * 2. Fore each datetime get related tickets
1582
+		 * 3. For each ticket get related prices
1583
+		 */
1584
+		$times = EE_Registry::instance()->load_model('Datetime')->get_all_event_dates($event_id);
1585
+		/** @type EE_Datetime $first_datetime */
1586
+		$first_datetime = reset($times);
1587
+		// do we get related tickets?
1588
+		if ($first_datetime instanceof EE_Datetime
1589
+			&& $first_datetime->ID() !== 0
1590
+		) {
1591
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1592
+			$template_args['time'] = $first_datetime;
1593
+			$related_tickets = $first_datetime->tickets(
1594
+				array(
1595
+					array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
1596
+					'default_where_conditions' => 'none',
1597
+				)
1598
+			);
1599
+			if (! empty($related_tickets)) {
1600
+				$template_args['total_ticket_rows'] = count($related_tickets);
1601
+				$row = 0;
1602
+				foreach ($related_tickets as $ticket) {
1603
+					$existing_ticket_ids[] = $ticket->get('TKT_ID');
1604
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1605
+					$row++;
1606
+				}
1607
+			} else {
1608
+				$template_args['total_ticket_rows'] = 1;
1609
+				/** @type EE_Ticket $ticket */
1610
+				$ticket = EE_Registry::instance()->load_model('Ticket')->create_default_object();
1611
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1612
+			}
1613
+		} else {
1614
+			$template_args['time'] = $times[0];
1615
+			/** @type EE_Ticket $ticket */
1616
+			$ticket = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
1617
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket[1]);
1618
+			// NOTE: we're just sending the first default row
1619
+			// (decaf can't manage default tickets so this should be sufficient);
1620
+		}
1621
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1622
+			'event_editor_event_datetimes_help_tab'
1623
+		);
1624
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1625
+		$template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1626
+		$template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1627
+		$template_args['ticket_js_structure'] = $this->_get_ticket_row(
1628
+			EE_Registry::instance()->load_model('Ticket')->create_default_object(),
1629
+			true
1630
+		);
1631
+		$template = apply_filters(
1632
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1633
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1634
+		);
1635
+		EEH_Template::display_template($template, $template_args);
1636
+	}
1637
+
1638
+
1639
+	/**
1640
+	 * Setup an individual ticket form for the decaf event editor page
1641
+	 *
1642
+	 * @access private
1643
+	 * @param  EE_Ticket $ticket   the ticket object
1644
+	 * @param  boolean   $skeleton whether we're generating a skeleton for js manipulation
1645
+	 * @param int        $row
1646
+	 * @return string generated html for the ticket row.
1647
+	 */
1648
+	private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1649
+	{
1650
+		$template_args = array(
1651
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1652
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1653
+				: '',
1654
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1655
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1656
+			'TKT_name'            => $ticket->get('TKT_name'),
1657
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1658
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1659
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1660
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1661
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1662
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1663
+			'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1664
+									 && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1665
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1666
+			'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1667
+				: ' disabled=disabled',
1668
+		);
1669
+		$price = $ticket->ID() !== 0
1670
+			? $ticket->get_first_related('Price', array('default_where_conditions' => 'none'))
1671
+			: EE_Registry::instance()->load_model('Price')->create_default_object();
1672
+		$price_args = array(
1673
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1674
+			'PRC_amount'            => $price->get('PRC_amount'),
1675
+			'PRT_ID'                => $price->get('PRT_ID'),
1676
+			'PRC_ID'                => $price->get('PRC_ID'),
1677
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1678
+		);
1679
+		// make sure we have default start and end dates if skeleton
1680
+		// handle rows that should NOT be empty
1681
+		if (empty($template_args['TKT_start_date'])) {
1682
+			// if empty then the start date will be now.
1683
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1684
+		}
1685
+		if (empty($template_args['TKT_end_date'])) {
1686
+			// get the earliest datetime (if present);
1687
+			$earliest_dtt = $this->_cpt_model_obj->ID() > 0
1688
+				? $this->_cpt_model_obj->get_first_related(
1689
+					'Datetime',
1690
+					array('order_by' => array('DTT_EVT_start' => 'ASC'))
1691
+				)
1692
+				: null;
1693
+			if (! empty($earliest_dtt)) {
1694
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a');
1695
+			} else {
1696
+				$template_args['TKT_end_date'] = date(
1697
+					'Y-m-d h:i a',
1698
+					mktime(0, 0, 0, date("m"), date("d") + 7, date("Y"))
1699
+				);
1700
+			}
1701
+		}
1702
+		$template_args = array_merge($template_args, $price_args);
1703
+		$template = apply_filters(
1704
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1705
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1706
+			$ticket
1707
+		);
1708
+		return EEH_Template::display_template($template, $template_args, true);
1709
+	}
1710
+
1711
+
1712
+	/**
1713
+	 * @throws DomainException
1714
+	 */
1715
+	public function registration_options_meta_box()
1716
+	{
1717
+		$yes_no_values = array(
1718
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
1719
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
1720
+		);
1721
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1722
+			array(
1723
+				EEM_Registration::status_id_cancelled,
1724
+				EEM_Registration::status_id_declined,
1725
+				EEM_Registration::status_id_incomplete,
1726
+			),
1727
+			true
1728
+		);
1729
+		// $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1730
+		$template_args['_event'] = $this->_cpt_model_obj;
1731
+		$template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1732
+		$template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1733
+		$template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1734
+			'default_reg_status',
1735
+			$default_reg_status_values,
1736
+			$this->_cpt_model_obj->default_registration_status()
1737
+		);
1738
+		$template_args['display_description'] = EEH_Form_Fields::select_input(
1739
+			'display_desc',
1740
+			$yes_no_values,
1741
+			$this->_cpt_model_obj->display_description()
1742
+		);
1743
+		$template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1744
+			'display_ticket_selector',
1745
+			$yes_no_values,
1746
+			$this->_cpt_model_obj->display_ticket_selector(),
1747
+			'',
1748
+			'',
1749
+			false
1750
+		);
1751
+		$template_args['additional_registration_options'] = apply_filters(
1752
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1753
+			'',
1754
+			$template_args,
1755
+			$yes_no_values,
1756
+			$default_reg_status_values
1757
+		);
1758
+		EEH_Template::display_template(
1759
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1760
+			$template_args
1761
+		);
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 * _get_events()
1767
+	 * This method simply returns all the events (for the given _view and paging)
1768
+	 *
1769
+	 * @access public
1770
+	 * @param int  $per_page     count of items per page (20 default);
1771
+	 * @param int  $current_page what is the current page being viewed.
1772
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1773
+	 *                           If FALSE then we return an array of event objects
1774
+	 *                           that match the given _view and paging parameters.
1775
+	 * @return array an array of event objects.
1776
+	 */
1777
+	public function get_events($per_page = 10, $current_page = 1, $count = false)
1778
+	{
1779
+		$EEME = $this->_event_model();
1780
+		$offset = ($current_page - 1) * $per_page;
1781
+		$limit = $count ? null : $offset . ',' . $per_page;
1782
+		$orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'EVT_ID';
1783
+		$order = isset($this->_req_data['order']) ? $this->_req_data['order'] : "DESC";
1784
+		if (isset($this->_req_data['month_range'])) {
1785
+			$pieces = explode(' ', $this->_req_data['month_range'], 3);
1786
+			// simulate the FIRST day of the month, that fixes issues for months like February
1787
+			// where PHP doesn't know what to assume for date.
1788
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1789
+			$month_r = ! empty($pieces[0]) ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1790
+			$year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1791
+		}
1792
+		$where = array();
1793
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1794
+		// determine what post_status our condition will have for the query.
1795
+		switch ($status) {
1796
+			case 'month':
1797
+			case 'today':
1798
+			case null:
1799
+			case 'all':
1800
+				break;
1801
+			case 'draft':
1802
+				$where['status'] = array('IN', array('draft', 'auto-draft'));
1803
+				break;
1804
+			default:
1805
+				$where['status'] = $status;
1806
+		}
1807
+		// categories?
1808
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1809
+			? $this->_req_data['EVT_CAT'] : null;
1810
+		if (! empty($category)) {
1811
+			$where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1812
+			$where['Term_Taxonomy.term_id'] = $category;
1813
+		}
1814
+		// date where conditions
1815
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1816
+		if (isset($this->_req_data['month_range']) && $this->_req_data['month_range'] != '') {
1817
+			$DateTime = new DateTime(
1818
+				$year_r . '-' . $month_r . '-01 00:00:00',
1819
+				new DateTimeZone('UTC')
1820
+			);
1821
+			$start = $DateTime->getTimestamp();
1822
+			// set the datetime to be the end of the month
1823
+			$DateTime->setDate(
1824
+				$year_r,
1825
+				$month_r,
1826
+				$DateTime->format('t')
1827
+			)->setTime(23, 59, 59);
1828
+			$end = $DateTime->getTimestamp();
1829
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1830
+		} elseif (isset($this->_req_data['status']) && $this->_req_data['status'] == 'today') {
1831
+			$DateTime = new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1832
+			$start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1833
+			$end = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1834
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1835
+		} elseif (isset($this->_req_data['status']) && $this->_req_data['status'] == 'month') {
1836
+			$now = date('Y-m-01');
1837
+			$DateTime = new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1838
+			$start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1839
+			$end = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1840
+							->setTime(23, 59, 59)
1841
+							->format(implode(' ', $start_formats));
1842
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1843
+		}
1844
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1845
+			$where['EVT_wp_user'] = get_current_user_id();
1846
+		} else {
1847
+			if (! isset($where['status'])) {
1848
+				if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1849
+					$where['OR'] = array(
1850
+						'status*restrict_private' => array('!=', 'private'),
1851
+						'AND'                     => array(
1852
+							'status*inclusive' => array('=', 'private'),
1853
+							'EVT_wp_user'      => get_current_user_id(),
1854
+						),
1855
+					);
1856
+				}
1857
+			}
1858
+		}
1859
+		if (isset($this->_req_data['EVT_wp_user'])) {
1860
+			if ($this->_req_data['EVT_wp_user'] != get_current_user_id()
1861
+				&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1862
+			) {
1863
+				$where['EVT_wp_user'] = $this->_req_data['EVT_wp_user'];
1864
+			}
1865
+		}
1866
+		// search query handling
1867
+		if (isset($this->_req_data['s'])) {
1868
+			$search_string = '%' . $this->_req_data['s'] . '%';
1869
+			$where['OR'] = array(
1870
+				'EVT_name'       => array('LIKE', $search_string),
1871
+				'EVT_desc'       => array('LIKE', $search_string),
1872
+				'EVT_short_desc' => array('LIKE', $search_string),
1873
+			);
1874
+		}
1875
+		// filter events by venue.
1876
+		if (isset($this->_req_data['venue']) && ! empty($this->_req_data['venue'])) {
1877
+			$where['Venue.VNU_ID'] = absint($this->_req_data['venue']);
1878
+		}
1879
+		$where = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $this->_req_data);
1880
+		$query_params = apply_filters(
1881
+			'FHEE__Events_Admin_Page__get_events__query_params',
1882
+			array(
1883
+				$where,
1884
+				'limit'    => $limit,
1885
+				'order_by' => $orderby,
1886
+				'order'    => $order,
1887
+				'group_by' => 'EVT_ID',
1888
+			),
1889
+			$this->_req_data
1890
+		);
1891
+
1892
+		// let's first check if we have special requests coming in.
1893
+		if (isset($this->_req_data['active_status'])) {
1894
+			switch ($this->_req_data['active_status']) {
1895
+				case 'upcoming':
1896
+					return $EEME->get_upcoming_events($query_params, $count);
1897
+					break;
1898
+				case 'expired':
1899
+					return $EEME->get_expired_events($query_params, $count);
1900
+					break;
1901
+				case 'active':
1902
+					return $EEME->get_active_events($query_params, $count);
1903
+					break;
1904
+				case 'inactive':
1905
+					return $EEME->get_inactive_events($query_params, $count);
1906
+					break;
1907
+			}
1908
+		}
1909
+
1910
+		$events = $count ? $EEME->count(array($where), 'EVT_ID', true) : $EEME->get_all($query_params);
1911
+		return $events;
1912
+	}
1913
+
1914
+
1915
+	/**
1916
+	 * handling for WordPress CPT actions (trash, restore, delete)
1917
+	 *
1918
+	 * @param string $post_id
1919
+	 */
1920
+	public function trash_cpt_item($post_id)
1921
+	{
1922
+		$this->_req_data['EVT_ID'] = $post_id;
1923
+		$this->_trash_or_restore_event('trash', false);
1924
+	}
1925
+
1926
+
1927
+	/**
1928
+	 * @param string $post_id
1929
+	 */
1930
+	public function restore_cpt_item($post_id)
1931
+	{
1932
+		$this->_req_data['EVT_ID'] = $post_id;
1933
+		$this->_trash_or_restore_event('draft', false);
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * @param string $post_id
1939
+	 */
1940
+	public function delete_cpt_item($post_id)
1941
+	{
1942
+		throw new EE_Error(esc_html__('Please contact Event Espresso support with the details of the steps taken to produce this error.', 'event_espresso'));
1943
+		$this->_req_data['EVT_ID'] = $post_id;
1944
+		$this->_delete_event();
1945
+	}
1946
+
1947
+
1948
+	/**
1949
+	 * _trash_or_restore_event
1950
+	 *
1951
+	 * @access protected
1952
+	 * @param  string $event_status
1953
+	 * @param bool    $redirect_after
1954
+	 */
1955
+	protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
1956
+	{
1957
+		// determine the event id and set to array.
1958
+		$EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : false;
1959
+		// loop thru events
1960
+		if ($EVT_ID) {
1961
+			// clean status
1962
+			$event_status = sanitize_key($event_status);
1963
+			// grab status
1964
+			if (! empty($event_status)) {
1965
+				$success = $this->_change_event_status($EVT_ID, $event_status);
1966
+			} else {
1967
+				$success = false;
1968
+				$msg = esc_html__(
1969
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
1970
+					'event_espresso'
1971
+				);
1972
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1973
+			}
1974
+		} else {
1975
+			$success = false;
1976
+			$msg = esc_html__(
1977
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
1978
+				'event_espresso'
1979
+			);
1980
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1981
+		}
1982
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
1983
+		if ($redirect_after) {
1984
+			$this->_redirect_after_action($success, 'Event', $action, array('action' => 'default'));
1985
+		}
1986
+	}
1987
+
1988
+
1989
+	/**
1990
+	 * _trash_or_restore_events
1991
+	 *
1992
+	 * @access protected
1993
+	 * @param  string $event_status
1994
+	 * @return void
1995
+	 */
1996
+	protected function _trash_or_restore_events($event_status = 'trash')
1997
+	{
1998
+		// clean status
1999
+		$event_status = sanitize_key($event_status);
2000
+		// grab status
2001
+		if (! empty($event_status)) {
2002
+			$success = true;
2003
+			// determine the event id and set to array.
2004
+			$EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array) $this->_req_data['EVT_IDs'] : array();
2005
+			// loop thru events
2006
+			foreach ($EVT_IDs as $EVT_ID) {
2007
+				if ($EVT_ID = absint($EVT_ID)) {
2008
+					$results = $this->_change_event_status($EVT_ID, $event_status);
2009
+					$success = $results !== false ? $success : false;
2010
+				} else {
2011
+					$msg = sprintf(
2012
+						esc_html__(
2013
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2014
+							'event_espresso'
2015
+						),
2016
+						$EVT_ID
2017
+					);
2018
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2019
+					$success = false;
2020
+				}
2021
+			}
2022
+		} else {
2023
+			$success = false;
2024
+			$msg = esc_html__(
2025
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2026
+				'event_espresso'
2027
+			);
2028
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2029
+		}
2030
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2031
+		$success = $success ? 2 : false;
2032
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2033
+		$this->_redirect_after_action($success, 'Events', $action, array('action' => 'default'));
2034
+	}
2035
+
2036
+
2037
+	/**
2038
+	 * _trash_or_restore_events
2039
+	 *
2040
+	 * @access  private
2041
+	 * @param  int    $EVT_ID
2042
+	 * @param  string $event_status
2043
+	 * @return bool
2044
+	 */
2045
+	private function _change_event_status($EVT_ID = 0, $event_status = '')
2046
+	{
2047
+		// grab event id
2048
+		if (! $EVT_ID) {
2049
+			$msg = esc_html__(
2050
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2051
+				'event_espresso'
2052
+			);
2053
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2054
+			return false;
2055
+		}
2056
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2057
+		// clean status
2058
+		$event_status = sanitize_key($event_status);
2059
+		// grab status
2060
+		if (empty($event_status)) {
2061
+			$msg = esc_html__(
2062
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2063
+				'event_espresso'
2064
+			);
2065
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2066
+			return false;
2067
+		}
2068
+		// was event trashed or restored ?
2069
+		switch ($event_status) {
2070
+			case 'draft':
2071
+				$action = 'restored from the trash';
2072
+				$hook = 'AHEE_event_restored_from_trash';
2073
+				break;
2074
+			case 'trash':
2075
+				$action = 'moved to the trash';
2076
+				$hook = 'AHEE_event_moved_to_trash';
2077
+				break;
2078
+			default:
2079
+				$action = 'updated';
2080
+				$hook = false;
2081
+		}
2082
+		// use class to change status
2083
+		$this->_cpt_model_obj->set_status($event_status);
2084
+		$success = $this->_cpt_model_obj->save();
2085
+		if ($success === false) {
2086
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2087
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2088
+			return false;
2089
+		}
2090
+		if ($hook) {
2091
+			do_action($hook);
2092
+		}
2093
+		return true;
2094
+	}
2095
+
2096
+
2097
+	/**
2098
+	 * _delete_event
2099
+	 *
2100
+	 * @access protected
2101
+	 * @param bool $redirect_after
2102
+	 */
2103
+	protected function _delete_event()
2104
+	{
2105
+		$this->generateDeletionPreview(isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : array());
2106
+	}
2107
+
2108
+	/**
2109
+	 * Gets the tree traversal batch persister.
2110
+	 * @since 4.10.12.p
2111
+	 * @return NodeGroupDao
2112
+	 * @throws InvalidArgumentException
2113
+	 * @throws InvalidDataTypeException
2114
+	 * @throws InvalidInterfaceException
2115
+	 */
2116
+	protected function getModelObjNodeGroupPersister()
2117
+	{
2118
+		if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2119
+			$this->model_obj_node_group_persister = $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2120
+		}
2121
+		return $this->model_obj_node_group_persister;
2122
+	}
2123
+
2124
+	/**
2125
+	 * _delete_events
2126
+	 *
2127
+	 * @access protected
2128
+	 * @return void
2129
+	 */
2130
+	protected function _delete_events()
2131
+	{
2132
+		$this->generateDeletionPreview(isset($this->_req_data['EVT_IDs']) ? (array) $this->_req_data['EVT_IDs'] : array());
2133
+	}
2134
+
2135
+	protected function generateDeletionPreview($event_ids)
2136
+	{
2137
+		$event_ids = (array) $event_ids;
2138
+		// Set a code we can use to reference this deletion task in the batch jobs and preview page.
2139
+		$deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2140
+		$return_url = EE_Admin_Page::add_query_args_and_nonce(
2141
+			[
2142
+				'action' => 'preview_deletion',
2143
+				'deletion_job_code' => $deletion_job_code,
2144
+			],
2145
+			$this->_admin_base_url
2146
+		);
2147
+		$event_ids = array_map(
2148
+			'intval',
2149
+			$event_ids
2150
+		);
2151
+
2152
+		EEH_URL::safeRedirectAndExit(
2153
+			EE_Admin_Page::add_query_args_and_nonce(
2154
+				array(
2155
+					'page'        => 'espresso_batch',
2156
+					'batch'       => EED_Batch::batch_job,
2157
+					'EVT_IDs'      => $event_ids,
2158
+					'deletion_job_code' => $deletion_job_code,
2159
+					'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2160
+					'return_url'  => urlencode($return_url),
2161
+				),
2162
+				admin_url()
2163
+			)
2164
+		);
2165
+	}
2166
+
2167
+	/**
2168
+	 * Checks for a POST submission
2169
+	 * @since 4.10.12.p
2170
+	 */
2171
+	protected function confirmDeletion()
2172
+	{
2173
+		$deletion_redirect_logic = $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2174
+		$deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2175
+	}
2176
+
2177
+	/**
2178
+	 * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2179
+	 * @since 4.10.12.p
2180
+	 * @throws EE_Error
2181
+	 */
2182
+	protected function previewDeletion()
2183
+	{
2184
+		$preview_deletion_logic = $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2185
+		$this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2186
+		$this->display_admin_page_with_no_sidebar();
2187
+	}
2188
+
2189
+	/**
2190
+	 * get total number of events
2191
+	 *
2192
+	 * @access public
2193
+	 * @return int
2194
+	 */
2195
+	public function total_events()
2196
+	{
2197
+		$count = EEM_Event::instance()->count(array('caps' => 'read_admin'), 'EVT_ID', true);
2198
+		return $count;
2199
+	}
2200
+
2201
+
2202
+	/**
2203
+	 * get total number of draft events
2204
+	 *
2205
+	 * @access public
2206
+	 * @return int
2207
+	 */
2208
+	public function total_events_draft()
2209
+	{
2210
+		$where = array(
2211
+			'status' => array('IN', array('draft', 'auto-draft')),
2212
+		);
2213
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2214
+		return $count;
2215
+	}
2216
+
2217
+
2218
+	/**
2219
+	 * get total number of trashed events
2220
+	 *
2221
+	 * @access public
2222
+	 * @return int
2223
+	 */
2224
+	public function total_trashed_events()
2225
+	{
2226
+		$where = array(
2227
+			'status' => 'trash',
2228
+		);
2229
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2230
+		return $count;
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 *    _default_event_settings
2236
+	 *    This generates the Default Settings Tab
2237
+	 *
2238
+	 * @return void
2239
+	 * @throws EE_Error
2240
+	 */
2241
+	protected function _default_event_settings()
2242
+	{
2243
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2244
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
2245
+		$this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2246
+		$this->display_admin_page_with_sidebar();
2247
+	}
2248
+
2249
+
2250
+	/**
2251
+	 * Return the form for event settings.
2252
+	 *
2253
+	 * @return EE_Form_Section_Proper
2254
+	 * @throws EE_Error
2255
+	 */
2256
+	protected function _default_event_settings_form()
2257
+	{
2258
+		$registration_config = EE_Registry::instance()->CFG->registration;
2259
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2260
+			// exclude
2261
+			array(
2262
+				EEM_Registration::status_id_cancelled,
2263
+				EEM_Registration::status_id_declined,
2264
+				EEM_Registration::status_id_incomplete,
2265
+				EEM_Registration::status_id_wait_list,
2266
+			),
2267
+			true
2268
+		);
2269
+		return new EE_Form_Section_Proper(
2270
+			array(
2271
+				'name'            => 'update_default_event_settings',
2272
+				'html_id'         => 'update_default_event_settings',
2273
+				'html_class'      => 'form-table',
2274
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2275
+				'subsections'     => apply_filters(
2276
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2277
+					array(
2278
+						'default_reg_status'  => new EE_Select_Input(
2279
+							$registration_stati_for_selection,
2280
+							array(
2281
+								'default'         => isset($registration_config->default_STS_ID)
2282
+													 && array_key_exists(
2283
+														 $registration_config->default_STS_ID,
2284
+														 $registration_stati_for_selection
2285
+													 )
2286
+									? sanitize_text_field($registration_config->default_STS_ID)
2287
+									: EEM_Registration::status_id_pending_payment,
2288
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2289
+													 . EEH_Template::get_help_tab_link(
2290
+														 'default_settings_status_help_tab'
2291
+													 ),
2292
+								'html_help_text'  => esc_html__(
2293
+									'This setting allows you to preselect what the default registration status setting is when creating an event.  Note that changing this setting does NOT retroactively apply it to existing events.',
2294
+									'event_espresso'
2295
+								),
2296
+							)
2297
+						),
2298
+						'default_max_tickets' => new EE_Integer_Input(
2299
+							array(
2300
+								'default'         => isset($registration_config->default_maximum_number_of_tickets)
2301
+									? $registration_config->default_maximum_number_of_tickets
2302
+									: EEM_Event::get_default_additional_limit(),
2303
+								'html_label_text' => esc_html__(
2304
+									'Default Maximum Tickets Allowed Per Order:',
2305
+									'event_espresso'
2306
+								)
2307
+													 . EEH_Template::get_help_tab_link(
2308
+														 'default_maximum_tickets_help_tab"'
2309
+													 ),
2310
+								'html_help_text'  => esc_html__(
2311
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2312
+									'event_espresso'
2313
+								),
2314
+							)
2315
+						),
2316
+					)
2317
+				),
2318
+			)
2319
+		);
2320
+	}
2321
+
2322
+
2323
+	/**
2324
+	 * _update_default_event_settings
2325
+	 *
2326
+	 * @access protected
2327
+	 * @return void
2328
+	 * @throws EE_Error
2329
+	 */
2330
+	protected function _update_default_event_settings()
2331
+	{
2332
+		$registration_config = EE_Registry::instance()->CFG->registration;
2333
+		$form = $this->_default_event_settings_form();
2334
+		if ($form->was_submitted()) {
2335
+			$form->receive_form_submission();
2336
+			if ($form->is_valid()) {
2337
+				$valid_data = $form->valid_data();
2338
+				if (isset($valid_data['default_reg_status'])) {
2339
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2340
+				}
2341
+				if (isset($valid_data['default_max_tickets'])) {
2342
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2343
+				}
2344
+				// update because data was valid!
2345
+				EE_Registry::instance()->CFG->update_espresso_config();
2346
+				EE_Error::overwrite_success();
2347
+				EE_Error::add_success(
2348
+					__('Default Event Settings were updated', 'event_espresso')
2349
+				);
2350
+			}
2351
+		}
2352
+		$this->_redirect_after_action(0, '', '', array('action' => 'default_event_settings'), true);
2353
+	}
2354
+
2355
+
2356
+	/*************        Templates        *************/
2357
+	protected function _template_settings()
2358
+	{
2359
+		$this->_admin_page_title = esc_html__('Template Settings (Preview)', 'event_espresso');
2360
+		$this->_template_args['preview_img'] = '<img src="'
2361
+											   . EVENTS_ASSETS_URL
2362
+											   . '/images/'
2363
+											   . 'caffeinated_template_features.jpg" alt="'
2364
+											   . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2365
+											   . '" />';
2366
+		$this->_template_args['preview_text'] = '<strong>'
2367
+												. esc_html__(
2368
+													'Template Settings is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. Template Settings allow you to configure some of the appearance options for both the Event List and Event Details pages.',
2369
+													'event_espresso'
2370
+												) . '</strong>';
2371
+		$this->display_admin_caf_preview_page('template_settings_tab');
2372
+	}
2373
+
2374
+
2375
+	/** Event Category Stuff **/
2376
+	/**
2377
+	 * set the _category property with the category object for the loaded page.
2378
+	 *
2379
+	 * @access private
2380
+	 * @return void
2381
+	 */
2382
+	private function _set_category_object()
2383
+	{
2384
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2385
+			return;
2386
+		} //already have the category object so get out.
2387
+		// set default category object
2388
+		$this->_set_empty_category_object();
2389
+		// only set if we've got an id
2390
+		if (! isset($this->_req_data['EVT_CAT_ID'])) {
2391
+			return;
2392
+		}
2393
+		$category_id = absint($this->_req_data['EVT_CAT_ID']);
2394
+		$term = get_term($category_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2395
+		if (! empty($term)) {
2396
+			$this->_category->category_name = $term->name;
2397
+			$this->_category->category_identifier = $term->slug;
2398
+			$this->_category->category_desc = $term->description;
2399
+			$this->_category->id = $term->term_id;
2400
+			$this->_category->parent = $term->parent;
2401
+		}
2402
+	}
2403
+
2404
+
2405
+	/**
2406
+	 * Clears out category properties.
2407
+	 */
2408
+	private function _set_empty_category_object()
2409
+	{
2410
+		$this->_category = new stdClass();
2411
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2412
+		$this->_category->id = $this->_category->parent = 0;
2413
+	}
2414
+
2415
+
2416
+	/**
2417
+	 * @throws EE_Error
2418
+	 */
2419
+	protected function _category_list_table()
2420
+	{
2421
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2422
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2423
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2424
+			'add_category',
2425
+			'add_category',
2426
+			array(),
2427
+			'add-new-h2'
2428
+		);
2429
+		$this->display_admin_list_table_page_with_sidebar();
2430
+	}
2431
+
2432
+
2433
+	/**
2434
+	 * Output category details view.
2435
+	 */
2436
+	protected function _category_details($view)
2437
+	{
2438
+		// load formatter helper
2439
+		// load field generator helper
2440
+		$route = $view == 'edit' ? 'update_category' : 'insert_category';
2441
+		$this->_set_add_edit_form_tags($route);
2442
+		$this->_set_category_object();
2443
+		$id = ! empty($this->_category->id) ? $this->_category->id : '';
2444
+		$delete_action = 'delete_category';
2445
+		// custom redirect
2446
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2447
+			array('action' => 'category_list'),
2448
+			$this->_admin_base_url
2449
+		);
2450
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2451
+		// take care of contents
2452
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2453
+		$this->display_admin_page_with_sidebar();
2454
+	}
2455
+
2456
+
2457
+	/**
2458
+	 * Output category details content.
2459
+	 */
2460
+	protected function _category_details_content()
2461
+	{
2462
+		$editor_args['category_desc'] = array(
2463
+			'type'          => 'wp_editor',
2464
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2465
+			'class'         => 'my_editor_custom',
2466
+			'wpeditor_args' => array('media_buttons' => false),
2467
+		);
2468
+		$_wp_editor = $this->_generate_admin_form_fields($editor_args, 'array');
2469
+		$all_terms = get_terms(
2470
+			array(EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY),
2471
+			array('hide_empty' => 0, 'exclude' => array($this->_category->id))
2472
+		);
2473
+		// setup category select for term parents.
2474
+		$category_select_values[] = array(
2475
+			'text' => esc_html__('No Parent', 'event_espresso'),
2476
+			'id'   => 0,
2477
+		);
2478
+		foreach ($all_terms as $term) {
2479
+			$category_select_values[] = array(
2480
+				'text' => $term->name,
2481
+				'id'   => $term->term_id,
2482
+			);
2483
+		}
2484
+		$category_select = EEH_Form_Fields::select_input(
2485
+			'category_parent',
2486
+			$category_select_values,
2487
+			$this->_category->parent
2488
+		);
2489
+		$template_args = array(
2490
+			'category'                 => $this->_category,
2491
+			'category_select'          => $category_select,
2492
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2493
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2494
+			'disable'                  => '',
2495
+			'disabled_message'         => false,
2496
+		);
2497
+		$template = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2498
+		return EEH_Template::display_template($template, $template_args, true);
2499
+	}
2500
+
2501
+
2502
+	/**
2503
+	 * Handles deleting categories.
2504
+	 */
2505
+	protected function _delete_categories()
2506
+	{
2507
+		$cat_ids = isset($this->_req_data['EVT_CAT_ID']) ? (array) $this->_req_data['EVT_CAT_ID']
2508
+			: (array) $this->_req_data['category_id'];
2509
+		foreach ($cat_ids as $cat_id) {
2510
+			$this->_delete_category($cat_id);
2511
+		}
2512
+		// doesn't matter what page we're coming from... we're going to the same place after delete.
2513
+		$query_args = array(
2514
+			'action' => 'category_list',
2515
+		);
2516
+		$this->_redirect_after_action(0, '', '', $query_args);
2517
+	}
2518
+
2519
+
2520
+	/**
2521
+	 * Handles deleting specific category.
2522
+	 *
2523
+	 * @param int $cat_id
2524
+	 */
2525
+	protected function _delete_category($cat_id)
2526
+	{
2527
+		$cat_id = absint($cat_id);
2528
+		wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2529
+	}
2530
+
2531
+
2532
+	/**
2533
+	 * Handles triggering the update or insertion of a new category.
2534
+	 *
2535
+	 * @param bool $new_category true means we're triggering the insert of a new category.
2536
+	 */
2537
+	protected function _insert_or_update_category($new_category)
2538
+	{
2539
+		$cat_id = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2540
+		$success = 0; // we already have a success message so lets not send another.
2541
+		if ($cat_id) {
2542
+			$query_args = array(
2543
+				'action'     => 'edit_category',
2544
+				'EVT_CAT_ID' => $cat_id,
2545
+			);
2546
+		} else {
2547
+			$query_args = array('action' => 'add_category');
2548
+		}
2549
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2550
+	}
2551
+
2552
+
2553
+	/**
2554
+	 * Inserts or updates category
2555
+	 *
2556
+	 * @param bool $update (true indicates we're updating a category).
2557
+	 * @return bool|mixed|string
2558
+	 */
2559
+	private function _insert_category($update = false)
2560
+	{
2561
+		$cat_id = $update ? $this->_req_data['EVT_CAT_ID'] : '';
2562
+		$category_name = isset($this->_req_data['category_name']) ? $this->_req_data['category_name'] : '';
2563
+		$category_desc = isset($this->_req_data['category_desc']) ? $this->_req_data['category_desc'] : '';
2564
+		$category_parent = isset($this->_req_data['category_parent']) ? $this->_req_data['category_parent'] : 0;
2565
+		if (empty($category_name)) {
2566
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2567
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2568
+			return false;
2569
+		}
2570
+		$term_args = array(
2571
+			'name'        => $category_name,
2572
+			'description' => $category_desc,
2573
+			'parent'      => $category_parent,
2574
+		);
2575
+		// was the category_identifier input disabled?
2576
+		if (isset($this->_req_data['category_identifier'])) {
2577
+			$term_args['slug'] = $this->_req_data['category_identifier'];
2578
+		}
2579
+		$insert_ids = $update
2580
+			? wp_update_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2581
+			: wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2582
+		if (! is_array($insert_ids)) {
2583
+			$msg = esc_html__(
2584
+				'An error occurred and the category has not been saved to the database.',
2585
+				'event_espresso'
2586
+			);
2587
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2588
+		} else {
2589
+			$cat_id = $insert_ids['term_id'];
2590
+			$msg = sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2591
+			EE_Error::add_success($msg);
2592
+		}
2593
+		return $cat_id;
2594
+	}
2595
+
2596
+
2597
+	/**
2598
+	 * Gets categories or count of categories matching the arguments in the request.
2599
+	 *
2600
+	 * @param int  $per_page
2601
+	 * @param int  $current_page
2602
+	 * @param bool $count
2603
+	 * @return EE_Base_Class[]|EE_Term_Taxonomy[]|int
2604
+	 */
2605
+	public function get_categories($per_page = 10, $current_page = 1, $count = false)
2606
+	{
2607
+		// testing term stuff
2608
+		$orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'Term.term_id';
2609
+		$order = isset($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2610
+		$limit = ($current_page - 1) * $per_page;
2611
+		$where = array('taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2612
+		if (isset($this->_req_data['s'])) {
2613
+			$sstr = '%' . $this->_req_data['s'] . '%';
2614
+			$where['OR'] = array(
2615
+				'Term.name'   => array('LIKE', $sstr),
2616
+				'description' => array('LIKE', $sstr),
2617
+			);
2618
+		}
2619
+		$query_params = array(
2620
+			$where,
2621
+			'order_by'   => array($orderby => $order),
2622
+			'limit'      => $limit . ',' . $per_page,
2623
+			'force_join' => array('Term'),
2624
+		);
2625
+		$categories = $count
2626
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2627
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2628
+		return $categories;
2629
+	}
2630
+
2631
+	/* end category stuff */
2632
+	/**************/
2633
+
2634
+
2635
+	/**
2636
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2637
+	 *
2638
+	 * @throws EE_Error
2639
+	 */
2640
+	public function save_timezonestring_setting()
2641
+	{
2642
+		$timezone_string = isset($this->_req_data['timezone_selected'])
2643
+			? $this->_req_data['timezone_selected']
2644
+			: '';
2645
+		if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2646
+			EE_Error::add_error(
2647
+				esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2648
+				__FILE__,
2649
+				__FUNCTION__,
2650
+				__LINE__
2651
+			);
2652
+			$this->_template_args['error'] = true;
2653
+			$this->_return_json();
2654
+		}
2655
+
2656
+		update_option('timezone_string', $timezone_string);
2657
+		EE_Error::add_success(
2658
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2659
+		);
2660
+		$this->_template_args['success'] = true;
2661
+		$this->_return_json(true, array('action' => 'create_new'));
2662
+	}
2663 2663
 }
Please login to merge, or discard this patch.