Completed
Branch master (3457d3)
by
unknown
25:39 queued 23:21
created
core/db_models/EEM_Ticket.model.php 2 patches
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -12,318 +12,318 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_Ticket extends EEM_Soft_Delete_Base
14 14
 {
15
-    /**
16
-     * private instance of the EEM_Ticket object
17
-     *
18
-     * @var EEM_Ticket $_instance
19
-     */
20
-    protected static $_instance;
15
+	/**
16
+	 * private instance of the EEM_Ticket object
17
+	 *
18
+	 * @var EEM_Ticket $_instance
19
+	 */
20
+	protected static $_instance;
21 21
 
22 22
 
23
-    /**
24
-     * private constructor to prevent direct creation
25
-     *
26
-     * @Constructor
27
-     * @access private
28
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
29
-     *                         (and any incoming timezone data that gets saved).
30
-     *                         Note this just sends the timezone info to the date time model field objects.
31
-     *                         Default is NULL
32
-     *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct($timezone)
36
-    {
37
-        $this->singular_item    = esc_html__('Ticket', 'event_espresso');
38
-        $this->plural_item      = esc_html__('Tickets', 'event_espresso');
39
-        $this->_tables          = [
40
-            'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
41
-        ];
42
-        $this->_fields          = [
43
-            'Ticket' => [
44
-                'TKT_ID'          => new EE_Primary_Key_Int_Field(
45
-                    'TKT_ID',
46
-                    esc_html__('Ticket ID', 'event_espresso')
47
-                ),
48
-                'TTM_ID'          => new EE_Foreign_Key_Int_Field(
49
-                    'TTM_ID',
50
-                    esc_html__('Ticket Template ID', 'event_espresso'),
51
-                    false,
52
-                    0,
53
-                    'Ticket_Template'
54
-                ),
55
-                'TKT_name'        => new EE_Plain_Text_Field(
56
-                    'TKT_name',
57
-                    esc_html__('Ticket Name', 'event_espresso'),
58
-                    false,
59
-                    ''
60
-                ),
61
-                'TKT_description' => new EE_Post_Content_Field(
62
-                    'TKT_description',
63
-                    esc_html__('Description of Ticket', 'event_espresso'),
64
-                    false,
65
-                    ''
66
-                ),
67
-                'TKT_start_date'  => new EE_Datetime_Field(
68
-                    'TKT_start_date',
69
-                    esc_html__('Start time/date of Ticket', 'event_espresso'),
70
-                    false,
71
-                    EE_Datetime_Field::now,
72
-                    $timezone
73
-                ),
74
-                'TKT_end_date'    => new EE_Datetime_Field(
75
-                    'TKT_end_date',
76
-                    esc_html__('End time/date of Ticket', 'event_espresso'),
77
-                    false,
78
-                    EE_Datetime_Field::now,
79
-                    $timezone
80
-                ),
81
-                'TKT_min'         => new EE_Integer_Field(
82
-                    'TKT_min',
83
-                    esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
84
-                    false,
85
-                    0
86
-                ),
87
-                'TKT_max'         => new EE_Infinite_Integer_Field(
88
-                    'TKT_max',
89
-                    esc_html__(
90
-                        'Maximum quantity of this ticket that can be purchased in one transaction',
91
-                        'event_espresso'
92
-                    ),
93
-                    false,
94
-                    EE_INF
95
-                ),
96
-                'TKT_price'       => new EE_Money_Field(
97
-                    'TKT_price',
98
-                    esc_html__('Final calculated price for ticket', 'event_espresso'),
99
-                    false,
100
-                    0
101
-                ),
102
-                'TKT_sold'        => new EE_Integer_Field(
103
-                    'TKT_sold',
104
-                    esc_html__('Number of this ticket sold', 'event_espresso'),
105
-                    false,
106
-                    0
107
-                ),
108
-                'TKT_qty'         => new EE_Infinite_Integer_Field(
109
-                    'TKT_qty',
110
-                    esc_html__('Quantity of this ticket that is available', 'event_espresso'),
111
-                    false,
112
-                    EE_INF
113
-                ),
114
-                'TKT_reserved'    => new EE_Integer_Field(
115
-                    'TKT_reserved',
116
-                    esc_html__(
117
-                        'Quantity of this ticket that is reserved, but not yet fully purchased',
118
-                        'event_espresso'
119
-                    ),
120
-                    false,
121
-                    0
122
-                ),
123
-                'TKT_uses'        => new EE_Infinite_Integer_Field(
124
-                    'TKT_uses',
125
-                    esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
126
-                    false,
127
-                    EE_INF
128
-                ),
129
-                'TKT_required'    => new EE_Boolean_Field(
130
-                    'TKT_required',
131
-                    esc_html__(
132
-                        'Flag indicating whether this ticket must be purchased with a transaction',
133
-                        'event_espresso'
134
-                    ),
135
-                    false,
136
-                    false
137
-                ),
138
-                'TKT_taxable'     => new EE_Boolean_Field(
139
-                    'TKT_taxable',
140
-                    esc_html__(
141
-                        'Flag indicating whether there is tax applied on this ticket',
142
-                        'event_espresso'
143
-                    ),
144
-                    false,
145
-                    false
146
-                ),
147
-                'TKT_is_default'  => new EE_Boolean_Field(
148
-                    'TKT_is_default',
149
-                    esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
150
-                    false,
151
-                    false
152
-                ),
153
-                'TKT_order'       => new EE_Integer_Field(
154
-                    'TKT_order',
155
-                    esc_html__(
156
-                        'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
157
-                        'event_espresso'
158
-                    ),
159
-                    false,
160
-                    0
161
-                ),
162
-                'TKT_row'         => new EE_Integer_Field(
163
-                    'TKT_row',
164
-                    esc_html__('How tickets are displayed in the ui', 'event_espresso'),
165
-                    false,
166
-                    0
167
-                ),
168
-                'TKT_deleted'     => new EE_Trashed_Flag_Field(
169
-                    'TKT_deleted',
170
-                    esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
171
-                    false,
172
-                    false
173
-                ),
174
-                'TKT_wp_user'     => new EE_WP_User_Field(
175
-                    'TKT_wp_user',
176
-                    esc_html__('Ticket Creator ID', 'event_espresso'),
177
-                    false
178
-                ),
179
-                'TKT_parent'      => new EE_Integer_Field(
180
-                    'TKT_parent',
181
-                    esc_html__(
182
-                        'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
183
-                        'event_espresso'
184
-                    ),
185
-                    true,
186
-                    0
187
-                ),
188
-            ],
189
-        ];
190
-        $this->_model_relations = [
191
-            'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
192
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
193
-            'Price'           => new EE_HABTM_Relation('Ticket_Price'),
194
-            'Ticket_Template' => new EE_Belongs_To_Relation(),
195
-            'Registration'    => new EE_Has_Many_Relation(),
196
-            'WP_User'         => new EE_Belongs_To_Relation(),
197
-        ];
198
-        // this model is generally available for reading
199
-        $path_to_event                                            = 'Datetime.Event';
200
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
201
-            'TKT_is_default',
202
-            $path_to_event
203
-        );
23
+	/**
24
+	 * private constructor to prevent direct creation
25
+	 *
26
+	 * @Constructor
27
+	 * @access private
28
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
29
+	 *                         (and any incoming timezone data that gets saved).
30
+	 *                         Note this just sends the timezone info to the date time model field objects.
31
+	 *                         Default is NULL
32
+	 *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct($timezone)
36
+	{
37
+		$this->singular_item    = esc_html__('Ticket', 'event_espresso');
38
+		$this->plural_item      = esc_html__('Tickets', 'event_espresso');
39
+		$this->_tables          = [
40
+			'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
41
+		];
42
+		$this->_fields          = [
43
+			'Ticket' => [
44
+				'TKT_ID'          => new EE_Primary_Key_Int_Field(
45
+					'TKT_ID',
46
+					esc_html__('Ticket ID', 'event_espresso')
47
+				),
48
+				'TTM_ID'          => new EE_Foreign_Key_Int_Field(
49
+					'TTM_ID',
50
+					esc_html__('Ticket Template ID', 'event_espresso'),
51
+					false,
52
+					0,
53
+					'Ticket_Template'
54
+				),
55
+				'TKT_name'        => new EE_Plain_Text_Field(
56
+					'TKT_name',
57
+					esc_html__('Ticket Name', 'event_espresso'),
58
+					false,
59
+					''
60
+				),
61
+				'TKT_description' => new EE_Post_Content_Field(
62
+					'TKT_description',
63
+					esc_html__('Description of Ticket', 'event_espresso'),
64
+					false,
65
+					''
66
+				),
67
+				'TKT_start_date'  => new EE_Datetime_Field(
68
+					'TKT_start_date',
69
+					esc_html__('Start time/date of Ticket', 'event_espresso'),
70
+					false,
71
+					EE_Datetime_Field::now,
72
+					$timezone
73
+				),
74
+				'TKT_end_date'    => new EE_Datetime_Field(
75
+					'TKT_end_date',
76
+					esc_html__('End time/date of Ticket', 'event_espresso'),
77
+					false,
78
+					EE_Datetime_Field::now,
79
+					$timezone
80
+				),
81
+				'TKT_min'         => new EE_Integer_Field(
82
+					'TKT_min',
83
+					esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
84
+					false,
85
+					0
86
+				),
87
+				'TKT_max'         => new EE_Infinite_Integer_Field(
88
+					'TKT_max',
89
+					esc_html__(
90
+						'Maximum quantity of this ticket that can be purchased in one transaction',
91
+						'event_espresso'
92
+					),
93
+					false,
94
+					EE_INF
95
+				),
96
+				'TKT_price'       => new EE_Money_Field(
97
+					'TKT_price',
98
+					esc_html__('Final calculated price for ticket', 'event_espresso'),
99
+					false,
100
+					0
101
+				),
102
+				'TKT_sold'        => new EE_Integer_Field(
103
+					'TKT_sold',
104
+					esc_html__('Number of this ticket sold', 'event_espresso'),
105
+					false,
106
+					0
107
+				),
108
+				'TKT_qty'         => new EE_Infinite_Integer_Field(
109
+					'TKT_qty',
110
+					esc_html__('Quantity of this ticket that is available', 'event_espresso'),
111
+					false,
112
+					EE_INF
113
+				),
114
+				'TKT_reserved'    => new EE_Integer_Field(
115
+					'TKT_reserved',
116
+					esc_html__(
117
+						'Quantity of this ticket that is reserved, but not yet fully purchased',
118
+						'event_espresso'
119
+					),
120
+					false,
121
+					0
122
+				),
123
+				'TKT_uses'        => new EE_Infinite_Integer_Field(
124
+					'TKT_uses',
125
+					esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
126
+					false,
127
+					EE_INF
128
+				),
129
+				'TKT_required'    => new EE_Boolean_Field(
130
+					'TKT_required',
131
+					esc_html__(
132
+						'Flag indicating whether this ticket must be purchased with a transaction',
133
+						'event_espresso'
134
+					),
135
+					false,
136
+					false
137
+				),
138
+				'TKT_taxable'     => new EE_Boolean_Field(
139
+					'TKT_taxable',
140
+					esc_html__(
141
+						'Flag indicating whether there is tax applied on this ticket',
142
+						'event_espresso'
143
+					),
144
+					false,
145
+					false
146
+				),
147
+				'TKT_is_default'  => new EE_Boolean_Field(
148
+					'TKT_is_default',
149
+					esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
150
+					false,
151
+					false
152
+				),
153
+				'TKT_order'       => new EE_Integer_Field(
154
+					'TKT_order',
155
+					esc_html__(
156
+						'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
157
+						'event_espresso'
158
+					),
159
+					false,
160
+					0
161
+				),
162
+				'TKT_row'         => new EE_Integer_Field(
163
+					'TKT_row',
164
+					esc_html__('How tickets are displayed in the ui', 'event_espresso'),
165
+					false,
166
+					0
167
+				),
168
+				'TKT_deleted'     => new EE_Trashed_Flag_Field(
169
+					'TKT_deleted',
170
+					esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
171
+					false,
172
+					false
173
+				),
174
+				'TKT_wp_user'     => new EE_WP_User_Field(
175
+					'TKT_wp_user',
176
+					esc_html__('Ticket Creator ID', 'event_espresso'),
177
+					false
178
+				),
179
+				'TKT_parent'      => new EE_Integer_Field(
180
+					'TKT_parent',
181
+					esc_html__(
182
+						'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
183
+						'event_espresso'
184
+					),
185
+					true,
186
+					0
187
+				),
188
+			],
189
+		];
190
+		$this->_model_relations = [
191
+			'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
192
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
193
+			'Price'           => new EE_HABTM_Relation('Ticket_Price'),
194
+			'Ticket_Template' => new EE_Belongs_To_Relation(),
195
+			'Registration'    => new EE_Has_Many_Relation(),
196
+			'WP_User'         => new EE_Belongs_To_Relation(),
197
+		];
198
+		// this model is generally available for reading
199
+		$path_to_event                                            = 'Datetime.Event';
200
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
201
+			'TKT_is_default',
202
+			$path_to_event
203
+		);
204 204
 
205
-        // account for default tickets in the caps
206
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
207
-            new EE_Restriction_Generator_Default_Protected(
208
-                'TKT_is_default',
209
-                $path_to_event
210
-            );
211
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
212
-            new EE_Restriction_Generator_Default_Protected(
213
-                'TKT_is_default',
214
-                $path_to_event
215
-            );
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
217
-            new EE_Restriction_Generator_Default_Protected(
218
-                'TKT_is_default',
219
-                $path_to_event
220
-            );
205
+		// account for default tickets in the caps
206
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
207
+			new EE_Restriction_Generator_Default_Protected(
208
+				'TKT_is_default',
209
+				$path_to_event
210
+			);
211
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
212
+			new EE_Restriction_Generator_Default_Protected(
213
+				'TKT_is_default',
214
+				$path_to_event
215
+			);
216
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
217
+			new EE_Restriction_Generator_Default_Protected(
218
+				'TKT_is_default',
219
+				$path_to_event
220
+			);
221 221
 
222
-        $this->model_chain_to_password = $path_to_event;
223
-        parent::__construct($timezone);
224
-    }
222
+		$this->model_chain_to_password = $path_to_event;
223
+		parent::__construct($timezone);
224
+	}
225 225
 
226 226
 
227
-    /**
228
-     * This returns all tickets that are defaults from the db
229
-     *
230
-     * @return EE_Ticket[]
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function get_all_default_tickets()
235
-    {
236
-        $tickets = $this->get_all([['TKT_is_default' => 1], 'order_by' => ['TKT_ID' => 'ASC']]);
237
-        // we need to set the start date and end date to today's date and the start of the default dtt
238
-        return $this->_set_default_dates($tickets);
239
-    }
227
+	/**
228
+	 * This returns all tickets that are defaults from the db
229
+	 *
230
+	 * @return EE_Ticket[]
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function get_all_default_tickets()
235
+	{
236
+		$tickets = $this->get_all([['TKT_is_default' => 1], 'order_by' => ['TKT_ID' => 'ASC']]);
237
+		// we need to set the start date and end date to today's date and the start of the default dtt
238
+		return $this->_set_default_dates($tickets);
239
+	}
240 240
 
241 241
 
242
-    /**
243
-     * sets up relevant start and end date for EE_Ticket (s)
244
-     *
245
-     * @param EE_Ticket[] $tickets
246
-     * @return EE_Ticket[]
247
-     * @throws EE_Error
248
-     * @throws ReflectionException
249
-     */
250
-    private function _set_default_dates($tickets)
251
-    {
252
-        foreach ($tickets as $ticket) {
253
-            $ticket->set(
254
-                'TKT_start_date',
255
-                (int) $this->current_time_for_query('TKT_start_date', true)
256
-            );
257
-            $ticket->set(
258
-                'TKT_end_date',
259
-                (int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
260
-            );
261
-            $ticket->set_end_time(
262
-                $this->convert_datetime_for_query(
263
-                    'TKT_end_date',
264
-                    '11:59 pm',
265
-                    'g:i a',
266
-                    $this->_timezone
267
-                )
268
-            );
269
-        }
270
-        return $tickets;
271
-    }
242
+	/**
243
+	 * sets up relevant start and end date for EE_Ticket (s)
244
+	 *
245
+	 * @param EE_Ticket[] $tickets
246
+	 * @return EE_Ticket[]
247
+	 * @throws EE_Error
248
+	 * @throws ReflectionException
249
+	 */
250
+	private function _set_default_dates($tickets)
251
+	{
252
+		foreach ($tickets as $ticket) {
253
+			$ticket->set(
254
+				'TKT_start_date',
255
+				(int) $this->current_time_for_query('TKT_start_date', true)
256
+			);
257
+			$ticket->set(
258
+				'TKT_end_date',
259
+				(int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
260
+			);
261
+			$ticket->set_end_time(
262
+				$this->convert_datetime_for_query(
263
+					'TKT_end_date',
264
+					'11:59 pm',
265
+					'g:i a',
266
+					$this->_timezone
267
+				)
268
+			);
269
+		}
270
+		return $tickets;
271
+	}
272 272
 
273 273
 
274
-    /**
275
-     * Gets the total number of tickets available at a particular datetime (does
276
-     * NOT take int account the datetime's spaces available)
277
-     *
278
-     * @param int   $DTT_ID
279
-     * @param array $query_params
280
-     * @return int
281
-     * @throws EE_Error
282
-     * @throws EE_Error
283
-     */
284
-    public function sum_tickets_currently_available_at_datetime($DTT_ID, $query_params = [])
285
-    {
286
-        return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
287
-    }
274
+	/**
275
+	 * Gets the total number of tickets available at a particular datetime (does
276
+	 * NOT take int account the datetime's spaces available)
277
+	 *
278
+	 * @param int   $DTT_ID
279
+	 * @param array $query_params
280
+	 * @return int
281
+	 * @throws EE_Error
282
+	 * @throws EE_Error
283
+	 */
284
+	public function sum_tickets_currently_available_at_datetime($DTT_ID, $query_params = [])
285
+	{
286
+		return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
287
+	}
288 288
 
289 289
 
290
-    /**
291
-     * Updates the TKT_sold quantity on all the tickets matching $query_params
292
-     *
293
-     * @param EE_Ticket[] $tickets
294
-     * @return void
295
-     * @throws EE_Error
296
-     * @throws ReflectionException
297
-     */
298
-    public function update_tickets_sold($tickets)
299
-    {
300
-        foreach ($tickets as $ticket) {
301
-            $ticket->update_tickets_sold();
302
-        }
303
-    }
290
+	/**
291
+	 * Updates the TKT_sold quantity on all the tickets matching $query_params
292
+	 *
293
+	 * @param EE_Ticket[] $tickets
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 * @throws ReflectionException
297
+	 */
298
+	public function update_tickets_sold($tickets)
299
+	{
300
+		foreach ($tickets as $ticket) {
301
+			$ticket->update_tickets_sold();
302
+		}
303
+	}
304 304
 
305 305
 
306
-    /**
307
-     * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
308
-     *
309
-     * @return EE_Base_Class[]|EE_Ticket[]
310
-     * @throws EE_Error
311
-     */
312
-    public function get_tickets_with_reservations()
313
-    {
314
-        return $this->get_all([['TKT_reserved' => ['>', 0]]]);
315
-    }
306
+	/**
307
+	 * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
308
+	 *
309
+	 * @return EE_Base_Class[]|EE_Ticket[]
310
+	 * @throws EE_Error
311
+	 */
312
+	public function get_tickets_with_reservations()
313
+	{
314
+		return $this->get_all([['TKT_reserved' => ['>', 0]]]);
315
+	}
316 316
 
317 317
 
318
-    /**
319
-     * returns an array of EE_Ticket objects matching the supplied list of IDs
320
-     *
321
-     * @param array $ticket_IDs
322
-     * @return EE_Base_Class[]|EE_Ticket[]
323
-     * @throws EE_Error
324
-     */
325
-    public function get_tickets_with_IDs(array $ticket_IDs)
326
-    {
327
-        return $this->get_all([['TKT_ID' => ['IN', $ticket_IDs]]]);
328
-    }
318
+	/**
319
+	 * returns an array of EE_Ticket objects matching the supplied list of IDs
320
+	 *
321
+	 * @param array $ticket_IDs
322
+	 * @return EE_Base_Class[]|EE_Ticket[]
323
+	 * @throws EE_Error
324
+	 */
325
+	public function get_tickets_with_IDs(array $ticket_IDs)
326
+	{
327
+		return $this->get_all([['TKT_ID' => ['IN', $ticket_IDs]]]);
328
+	}
329 329
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -197,23 +197,23 @@
 block discarded – undo
197 197
         ];
198 198
         // this model is generally available for reading
199 199
         $path_to_event                                            = 'Datetime.Event';
200
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
200
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Default_Public(
201 201
             'TKT_is_default',
202 202
             $path_to_event
203 203
         );
204 204
 
205 205
         // account for default tickets in the caps
206
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
206
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
207 207
             new EE_Restriction_Generator_Default_Protected(
208 208
                 'TKT_is_default',
209 209
                 $path_to_event
210 210
             );
211
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
211
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] =
212 212
             new EE_Restriction_Generator_Default_Protected(
213 213
                 'TKT_is_default',
214 214
                 $path_to_event
215 215
             );
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
216
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] =
217 217
             new EE_Restriction_Generator_Default_Protected(
218 218
                 'TKT_is_default',
219 219
                 $path_to_event
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6481 added lines, -6481 removed lines patch added patch discarded remove patch
@@ -35,6487 +35,6487 @@
 block discarded – undo
35 35
  */
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
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
-    protected 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
-                    esc_html__(
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(esc_html__(
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
-                            esc_html__(
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
-                EEM_Base::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
-                EEM_Base::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
848
-     *                             different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            esc_html__(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(esc_html__(
1375
-                        '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).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(esc_html__(
1478
-                '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.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // 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
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // 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)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // 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
1679
-            // 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
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            $field_settings = $this->field_settings();
1790
-            // no primary key, just grab the first column
1791
-            $field = reset($field_settings);
1792
-            // don't need this array now
1793
-            unset($field_settings);
1794
-        }
1795
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
-        $select_expressions = $field->get_qualified_column();
1797
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1798
-        return $this->_do_wpdb_query('get_col', array($SQL));
1799
-    }
1800
-
1801
-
1802
-
1803
-    /**
1804
-     * Returns a single column value for a single row from the database
1805
-     *
1806
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1807
-     * @param string $field_to_select @see EEM_Base::get_col()
1808
-     * @return string
1809
-     * @throws EE_Error
1810
-     */
1811
-    public function get_var($query_params = array(), $field_to_select = null)
1812
-    {
1813
-        $query_params['limit'] = 1;
1814
-        $col = $this->get_col($query_params, $field_to_select);
1815
-        if (! empty($col)) {
1816
-            return reset($col);
1817
-        }
1818
-        return null;
1819
-    }
1820
-
1821
-
1822
-
1823
-    /**
1824
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1825
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1826
-     * injection, but currently no further filtering is done
1827
-     *
1828
-     * @global      $wpdb
1829
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1830
-     *                               be updated to in the DB
1831
-     * @return string of SQL
1832
-     * @throws EE_Error
1833
-     */
1834
-    public function _construct_update_sql($fields_n_values)
1835
-    {
1836
-        /** @type WPDB $wpdb */
1837
-        global $wpdb;
1838
-        $cols_n_values = array();
1839
-        foreach ($fields_n_values as $field_name => $value) {
1840
-            $field_obj = $this->field_settings_for($field_name);
1841
-            // if the value is NULL, we want to assign the value to that.
1842
-            // wpdb->prepare doesn't really handle that properly
1843
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844
-            $value_sql = $prepared_value === null ? 'NULL'
1845
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1847
-        }
1848
-        return implode(",", $cols_n_values);
1849
-    }
1850
-
1851
-
1852
-
1853
-    /**
1854
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1855
-     * Performs a HARD delete, meaning the database row should always be removed,
1856
-     * not just have a flag field on it switched
1857
-     * Wrapper for EEM_Base::delete_permanently()
1858
-     *
1859
-     * @param mixed $id
1860
-     * @param boolean $allow_blocking
1861
-     * @return int the number of rows deleted
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1865
-    {
1866
-        return $this->delete_permanently(
1867
-            array(
1868
-                array($this->get_primary_key_field()->get_name() => $id),
1869
-                'limit' => 1,
1870
-            ),
1871
-            $allow_blocking
1872
-        );
1873
-    }
1874
-
1875
-
1876
-
1877
-    /**
1878
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1879
-     * Wrapper for EEM_Base::delete()
1880
-     *
1881
-     * @param mixed $id
1882
-     * @param boolean $allow_blocking
1883
-     * @return int the number of rows deleted
1884
-     * @throws EE_Error
1885
-     */
1886
-    public function delete_by_ID($id, $allow_blocking = true)
1887
-    {
1888
-        return $this->delete(
1889
-            array(
1890
-                array($this->get_primary_key_field()->get_name() => $id),
1891
-                'limit' => 1,
1892
-            ),
1893
-            $allow_blocking
1894
-        );
1895
-    }
1896
-
1897
-
1898
-
1899
-    /**
1900
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1901
-     * meaning if the model has a field that indicates its been "trashed" or
1902
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1903
-     *
1904
-     * @see EEM_Base::delete_permanently
1905
-     * @param array   $query_params
1906
-     * @param boolean $allow_blocking
1907
-     * @return int how many rows got deleted
1908
-     * @throws EE_Error
1909
-     */
1910
-    public function delete($query_params, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete_permanently($query_params, $allow_blocking);
1913
-    }
1914
-
1915
-
1916
-
1917
-    /**
1918
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1919
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1920
-     * as archived, not actually deleted
1921
-     *
1922
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1923
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1924
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1925
-     *                                deletes regardless of other objects which may depend on it. Its generally
1926
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1927
-     *                                DB
1928
-     * @return int how many rows got deleted
1929
-     * @throws EE_Error
1930
-     */
1931
-    public function delete_permanently($query_params, $allow_blocking = true)
1932
-    {
1933
-        /**
1934
-         * Action called just before performing a real deletion query. You can use the
1935
-         * model and its $query_params to find exactly which items will be deleted
1936
-         *
1937
-         * @param EEM_Base $model
1938
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1939
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1940
-         *                                 to block (prevent) this deletion
1941
-         */
1942
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1943
-        // some MySQL databases may be running safe mode, which may restrict
1944
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1945
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1946
-        // to delete them
1947
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1948
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1949
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1950
-            $columns_and_ids_for_deleting
1951
-        );
1952
-        /**
1953
-         * Allows client code to act on the items being deleted before the query is actually executed.
1954
-         *
1955
-         * @param EEM_Base $this  The model instance being acted on.
1956
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1957
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1958
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1959
-         *                                                  derived from the incoming query parameters.
1960
-         *                                                  @see details on the structure of this array in the phpdocs
1961
-         *                                                  for the `_get_ids_for_delete_method`
1962
-         *
1963
-         */
1964
-        do_action(
1965
-            'AHEE__EEM_Base__delete__before_query',
1966
-            $this,
1967
-            $query_params,
1968
-            $allow_blocking,
1969
-            $columns_and_ids_for_deleting
1970
-        );
1971
-        if ($deletion_where_query_part) {
1972
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
-            $table_aliases = array_keys($this->_tables);
1974
-            $SQL = "DELETE "
1975
-                   . implode(", ", $table_aliases)
1976
-                   . " FROM "
1977
-                   . $model_query_info->get_full_join_sql()
1978
-                   . " WHERE "
1979
-                   . $deletion_where_query_part;
1980
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
-        } else {
1982
-            $rows_deleted = 0;
1983
-        }
1984
-
1985
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
-        // there was no error with the delete query.
1987
-        if (
1988
-            $this->has_primary_key_field()
1989
-            && $rows_deleted !== false
1990
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1991
-        ) {
1992
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1993
-            foreach ($ids_for_removal as $id) {
1994
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1996
-                }
1997
-            }
1998
-
1999
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2000
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2001
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2002
-            // (although it is possible).
2003
-            // Note this can be skipped by using the provided filter and returning false.
2004
-            if (
2005
-                apply_filters(
2006
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2007
-                    ! $this instanceof EEM_Extra_Meta,
2008
-                    $this
2009
-                )
2010
-            ) {
2011
-                EEM_Extra_Meta::instance()->delete_permanently(
2012
-                    [
2013
-                        0 => [
2014
-                            'OBJ_ID'   => ['IN', $ids_for_removal],
2015
-                            'EXM_type' => $this->get_this_model_name(),
2016
-                        ]
2017
-                    ]
2018
-                );
2019
-            }
2020
-        }
2021
-
2022
-        /**
2023
-         * Action called just after performing a real deletion query. Although at this point the
2024
-         * items should have been deleted
2025
-         *
2026
-         * @param EEM_Base $model
2027
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2028
-         * @param int      $rows_deleted
2029
-         */
2030
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
-        return $rows_deleted;// how many supposedly got deleted
2032
-    }
2033
-
2034
-
2035
-
2036
-    /**
2037
-     * Checks all the relations that throw error messages when there are blocking related objects
2038
-     * for related model objects. If there are any related model objects on those relations,
2039
-     * adds an EE_Error, and return true
2040
-     *
2041
-     * @param EE_Base_Class|int $this_model_obj_or_id
2042
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2043
-     *                                                 should be ignored when determining whether there are related
2044
-     *                                                 model objects which block this model object's deletion. Useful
2045
-     *                                                 if you know A is related to B and are considering deleting A,
2046
-     *                                                 but want to see if A has any other objects blocking its deletion
2047
-     *                                                 before removing the relation between A and B
2048
-     * @return boolean
2049
-     * @throws EE_Error
2050
-     */
2051
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2052
-    {
2053
-        // first, if $ignore_this_model_obj was supplied, get its model
2054
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2055
-            $ignored_model = $ignore_this_model_obj->get_model();
2056
-        } else {
2057
-            $ignored_model = null;
2058
-        }
2059
-        // now check all the relations of $this_model_obj_or_id and see if there
2060
-        // are any related model objects blocking it?
2061
-        $is_blocked = false;
2062
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2063
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2064
-                // if $ignore_this_model_obj was supplied, then for the query
2065
-                // on that model needs to be told to ignore $ignore_this_model_obj
2066
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2067
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2068
-                        array(
2069
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2070
-                                '!=',
2071
-                                $ignore_this_model_obj->ID(),
2072
-                            ),
2073
-                        ),
2074
-                    ));
2075
-                } else {
2076
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2077
-                }
2078
-                if ($related_model_objects) {
2079
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2080
-                    $is_blocked = true;
2081
-                }
2082
-            }
2083
-        }
2084
-        return $is_blocked;
2085
-    }
2086
-
2087
-
2088
-    /**
2089
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2090
-     * @param array $row_results_for_deleting
2091
-     * @param bool  $allow_blocking
2092
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2093
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2094
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2095
-     *                 deleted. Example:
2096
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2097
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2098
-     *                 where each element is a group of columns and values that get deleted. Example:
2099
-     *                      array(
2100
-     *                          0 => array(
2101
-     *                              'Term_Relationship.object_id' => 1
2102
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2103
-     *                          ),
2104
-     *                          1 => array(
2105
-     *                              'Term_Relationship.object_id' => 1
2106
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2107
-     *                          )
2108
-     *                      )
2109
-     * @throws EE_Error
2110
-     */
2111
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2112
-    {
2113
-        $ids_to_delete_indexed_by_column = array();
2114
-        if ($this->has_primary_key_field()) {
2115
-            $primary_table = $this->_get_main_table();
2116
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2117
-            $other_tables = $this->_get_other_tables();
2118
-            $ids_to_delete_indexed_by_column = $query = array();
2119
-            foreach ($row_results_for_deleting as $item_to_delete) {
2120
-                // before we mark this item for deletion,
2121
-                // make sure there's no related entities blocking its deletion (if we're checking)
2122
-                if (
2123
-                    $allow_blocking
2124
-                    && $this->delete_is_blocked_by_related_models(
2125
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2126
-                    )
2127
-                ) {
2128
-                    continue;
2129
-                }
2130
-                // primary table deletes
2131
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2134
-                }
2135
-            }
2136
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2137
-            $fields = $this->get_combined_primary_key_fields();
2138
-            foreach ($row_results_for_deleting as $item_to_delete) {
2139
-                $ids_to_delete_indexed_by_column_for_row = array();
2140
-                foreach ($fields as $cpk_field) {
2141
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2142
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2144
-                    }
2145
-                }
2146
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2147
-            }
2148
-        } else {
2149
-            // so there's no primary key and no combined key...
2150
-            // sorry, can't help you
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2155
-                        "event_espresso"
2156
-                    ),
2157
-                    get_class($this)
2158
-                )
2159
-            );
2160
-        }
2161
-        return $ids_to_delete_indexed_by_column;
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2167
-     * the corresponding query_part for the query performing the delete.
2168
-     *
2169
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2170
-     * @return string
2171
-     * @throws EE_Error
2172
-     */
2173
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2174
-    {
2175
-        $query_part = '';
2176
-        if (empty($ids_to_delete_indexed_by_column)) {
2177
-            return $query_part;
2178
-        } elseif ($this->has_primary_key_field()) {
2179
-            $query = array();
2180
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2182
-            }
2183
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
-            $ways_to_identify_a_row = array();
2186
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
-                $values_for_each_combined_primary_key_for_a_row = array();
2188
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
-                }
2191
-                $ways_to_identify_a_row[] = '('
2192
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
-                                            . ')';
2194
-            }
2195
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2196
-        }
2197
-        return $query_part;
2198
-    }
2199
-
2200
-
2201
-
2202
-    /**
2203
-     * Gets the model field by the fully qualified name
2204
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
-     * @return EE_Model_Field_Base
2206
-     */
2207
-    public function get_field_by_column($qualified_column_name)
2208
-    {
2209
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
-                return $field_obj;
2212
-            }
2213
-        }
2214
-        throw new EE_Error(
2215
-            sprintf(
2216
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
-                $this->get_this_model_name(),
2218
-                $qualified_column_name
2219
-            )
2220
-        );
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Count all the rows that match criteria the model query params.
2227
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
-     * column
2229
-     *
2230
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
-     * @param string $field_to_count field on model to count by (not column name)
2232
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
-     *                               that by the setting $distinct to TRUE;
2234
-     * @return int
2235
-     * @throws EE_Error
2236
-     */
2237
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
-    {
2239
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
-        if ($field_to_count) {
2241
-            $field_obj = $this->field_settings_for($field_to_count);
2242
-            $column_to_count = $field_obj->get_qualified_column();
2243
-        } elseif ($this->has_primary_key_field()) {
2244
-            $pk_field_obj = $this->get_primary_key_field();
2245
-            $column_to_count = $pk_field_obj->get_qualified_column();
2246
-        } else {
2247
-            // there's no primary key
2248
-            // if we're counting distinct items, and there's no primary key,
2249
-            // we need to list out the columns for distinction;
2250
-            // otherwise we can just use star
2251
-            if ($distinct) {
2252
-                $columns_to_use = array();
2253
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2255
-                }
2256
-                $column_to_count = implode(',', $columns_to_use);
2257
-            } else {
2258
-                $column_to_count = '*';
2259
-            }
2260
-        }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
-    }
2265
-
2266
-
2267
-
2268
-    /**
2269
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
-     *
2271
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
-     * @param string $field_to_sum name of field (array key in $_fields array)
2273
-     * @return float
2274
-     * @throws EE_Error
2275
-     */
2276
-    public function sum($query_params, $field_to_sum = null)
2277
-    {
2278
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
-        if ($field_to_sum) {
2280
-            $field_obj = $this->field_settings_for($field_to_sum);
2281
-        } else {
2282
-            $field_obj = $this->get_primary_key_field();
2283
-        }
2284
-        $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
-        $data_type = $field_obj->get_wpdb_data_type();
2288
-        if ($data_type === '%d' || $data_type === '%s') {
2289
-            return (float) $return_value;
2290
-        }
2291
-        // must be %f
2292
-        return (float) $return_value;
2293
-    }
2294
-
2295
-
2296
-
2297
-    /**
2298
-     * Just calls the specified method on $wpdb with the given arguments
2299
-     * Consolidates a little extra error handling code
2300
-     *
2301
-     * @param string $wpdb_method
2302
-     * @param array  $arguments_to_provide
2303
-     * @throws EE_Error
2304
-     * @global wpdb  $wpdb
2305
-     * @return mixed
2306
-     */
2307
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        // if we're in maintenance mode level 2, DON'T run any queries
2310
-        // because level 2 indicates the database needs updating and
2311
-        // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
-            throw new EE_Error(sprintf(esc_html__(
2314
-                "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.",
2315
-                "event_espresso"
2316
-            )));
2317
-        }
2318
-        /** @type WPDB $wpdb */
2319
-        global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2321
-            throw new EE_Error(sprintf(esc_html__(
2322
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2323
-                'event_espresso'
2324
-            ), $wpdb_method));
2325
-        }
2326
-        if (WP_DEBUG) {
2327
-            $old_show_errors_value = $wpdb->show_errors;
2328
-            $wpdb->show_errors(false);
2329
-        }
2330
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2332
-        if (WP_DEBUG) {
2333
-            $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2335
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
-            }
2337
-            if ($result === false) {
2338
-                throw new EE_Error(sprintf(esc_html__(
2339
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
-                    'event_espresso'
2341
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2342
-            }
2343
-        } elseif ($result === false) {
2344
-            EE_Error::add_error(
2345
-                sprintf(
2346
-                    esc_html__(
2347
-                        '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"',
2348
-                        'event_espresso'
2349
-                    ),
2350
-                    $wpdb_method,
2351
-                    var_export($arguments_to_provide, true),
2352
-                    $wpdb->last_error
2353
-                ),
2354
-                __FILE__,
2355
-                __FUNCTION__,
2356
-                __LINE__
2357
-            );
2358
-        }
2359
-        return $result;
2360
-    }
2361
-
2362
-
2363
-
2364
-    /**
2365
-     * Attempts to run the indicated WPDB method with the provided arguments,
2366
-     * and if there's an error tries to verify the DB is correct. Uses
2367
-     * the static property EEM_Base::$_db_verification_level to determine whether
2368
-     * we should try to fix the EE core db, the addons, or just give up
2369
-     *
2370
-     * @param string $wpdb_method
2371
-     * @param array  $arguments_to_provide
2372
-     * @return mixed
2373
-     */
2374
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
-    {
2376
-        /** @type WPDB $wpdb */
2377
-        global $wpdb;
2378
-        $wpdb->last_error = null;
2379
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
-        // was there an error running the query? but we don't care on new activations
2381
-        // (we're going to setup the DB anyway on new activations)
2382
-        if (
2383
-            ($result === false || ! empty($wpdb->last_error))
2384
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
-        ) {
2386
-            switch (EEM_Base::$_db_verification_level) {
2387
-                case EEM_Base::db_verified_none:
2388
-                    // let's double-check core's DB
2389
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
-                    break;
2391
-                case EEM_Base::db_verified_core:
2392
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
-                    break;
2395
-                case EEM_Base::db_verified_addons:
2396
-                    // ummmm... you in trouble
2397
-                    return $result;
2398
-                    break;
2399
-            }
2400
-            if (! empty($error_message)) {
2401
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
-                trigger_error($error_message);
2403
-            }
2404
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-
2411
-    /**
2412
-     * Verifies the EE core database is up-to-date and records that we've done it on
2413
-     * EEM_Base::$_db_verification_level
2414
-     *
2415
-     * @param string $wpdb_method
2416
-     * @param array  $arguments_to_provide
2417
-     * @return string
2418
-     */
2419
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
-    {
2421
-        /** @type WPDB $wpdb */
2422
-        global $wpdb;
2423
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2424
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
-        $error_message = sprintf(
2426
-            esc_html__(
2427
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
-                'event_espresso'
2429
-            ),
2430
-            $wpdb->last_error,
2431
-            $wpdb_method,
2432
-            wp_json_encode($arguments_to_provide)
2433
-        );
2434
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
-        return $error_message;
2436
-    }
2437
-
2438
-
2439
-
2440
-    /**
2441
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
-     * EEM_Base::$_db_verification_level
2443
-     *
2444
-     * @param $wpdb_method
2445
-     * @param $arguments_to_provide
2446
-     * @return string
2447
-     */
2448
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
-    {
2450
-        /** @type WPDB $wpdb */
2451
-        global $wpdb;
2452
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
-        $error_message = sprintf(
2455
-            esc_html__(
2456
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
-                'event_espresso'
2458
-            ),
2459
-            $wpdb->last_error,
2460
-            $wpdb_method,
2461
-            wp_json_encode($arguments_to_provide)
2462
-        );
2463
-        EE_System::instance()->initialize_addons();
2464
-        return $error_message;
2465
-    }
2466
-
2467
-
2468
-
2469
-    /**
2470
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
-     * ..."
2474
-     *
2475
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2476
-     * @return string
2477
-     */
2478
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
-    {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2485
-               $model_query_info->get_limit_sql();
2486
-    }
2487
-
2488
-
2489
-
2490
-    /**
2491
-     * Set to easily debug the next X queries ran from this model.
2492
-     *
2493
-     * @param int $count
2494
-     */
2495
-    public function show_next_x_db_queries($count = 1)
2496
-    {
2497
-        $this->_show_next_x_db_queries = $count;
2498
-    }
2499
-
2500
-
2501
-
2502
-    /**
2503
-     * @param $sql_query
2504
-     */
2505
-    public function show_db_query_if_previously_requested($sql_query)
2506
-    {
2507
-        if ($this->_show_next_x_db_queries > 0) {
2508
-            echo esc_html($sql_query);
2509
-            $this->_show_next_x_db_queries--;
2510
-        }
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
-     * There are the 3 cases:
2518
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
-     * $otherModelObject has no ID, it is first saved.
2520
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
-     * has no ID, it is first saved.
2522
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
-     * join table
2525
-     *
2526
-     * @param        EE_Base_Class                     /int $thisModelObject
2527
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
-     * @param string $relationName                     , key in EEM_Base::_relations
2529
-     *                                                 an attendee to a group, you also want to specify which role they
2530
-     *                                                 will have in that group. So you would use this parameter to
2531
-     *                                                 specify array('role-column-name'=>'role-id')
2532
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
-     *                                                 to for relation to methods that allow you to further specify
2534
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
-     *                                                 because these will be inserted in any new rows created as well.
2537
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
-     * @throws EE_Error
2539
-     */
2540
-    public function add_relationship_to(
2541
-        $id_or_obj,
2542
-        $other_model_id_or_obj,
2543
-        $relationName,
2544
-        $extra_join_model_fields_n_values = array()
2545
-    ) {
2546
-        $relation_obj = $this->related_settings_for($relationName);
2547
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
-    }
2549
-
2550
-
2551
-
2552
-    /**
2553
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
-     * There are the 3 cases:
2555
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
-     * error
2557
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
-     * an error
2559
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
-     *
2561
-     * @param        EE_Base_Class /int $id_or_obj
2562
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
-     * @param string $relationName key in EEM_Base::_relations
2564
-     * @return boolean of success
2565
-     * @throws EE_Error
2566
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
-     *                             because these will be inserted in any new rows created as well.
2570
-     */
2571
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
-    {
2573
-        $relation_obj = $this->related_settings_for($relationName);
2574
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * @param mixed           $id_or_obj
2581
-     * @param string          $relationName
2582
-     * @param array           $where_query_params
2583
-     * @param EE_Base_Class[] objects to which relations were removed
2584
-     * @return \EE_Base_Class[]
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
-    {
2589
-        $relation_obj = $this->related_settings_for($relationName);
2590
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
-    }
2592
-
2593
-
2594
-
2595
-    /**
2596
-     * Gets all the related items of the specified $model_name, using $query_params.
2597
-     * Note: by default, we remove the "default query params"
2598
-     * because we want to get even deleted items etc.
2599
-     *
2600
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
-     * @return EE_Base_Class[]
2604
-     * @throws EE_Error
2605
-     */
2606
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
-    {
2608
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2609
-        $relation_settings = $this->related_settings_for($model_name);
2610
-        return $relation_settings->get_all_related($model_obj, $query_params);
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Deletes all the model objects across the relation indicated by $model_name
2617
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2619
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
-     *
2621
-     * @param EE_Base_Class|int|string $id_or_obj
2622
-     * @param string                   $model_name
2623
-     * @param array                    $query_params
2624
-     * @return int how many deleted
2625
-     * @throws EE_Error
2626
-     */
2627
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
-    {
2629
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2630
-        $relation_settings = $this->related_settings_for($model_name);
2631
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2632
-    }
2633
-
2634
-
2635
-
2636
-    /**
2637
-     * Hard deletes all the model objects across the relation indicated by $model_name
2638
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
-     * the model objects can't be hard deleted because of blocking related model objects,
2640
-     * just does a soft-delete on them instead.
2641
-     *
2642
-     * @param EE_Base_Class|int|string $id_or_obj
2643
-     * @param string                   $model_name
2644
-     * @param array                    $query_params
2645
-     * @return int how many deleted
2646
-     * @throws EE_Error
2647
-     */
2648
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
-    {
2650
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2651
-        $relation_settings = $this->related_settings_for($model_name);
2652
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
-    }
2654
-
2655
-
2656
-
2657
-    /**
2658
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
-     * unless otherwise specified in the $query_params
2660
-     *
2661
-     * @param        int             /EE_Base_Class $id_or_obj
2662
-     * @param string $model_name     like 'Event', or 'Registration'
2663
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2665
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
-     *                               that by the setting $distinct to TRUE;
2667
-     * @return int
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function count_related(
2671
-        $id_or_obj,
2672
-        $model_name,
2673
-        $query_params = array(),
2674
-        $field_to_count = null,
2675
-        $distinct = false
2676
-    ) {
2677
-        $related_model = $this->get_related_model_obj($model_name);
2678
-        // we're just going to use the query params on the related model's normal get_all query,
2679
-        // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2681
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
-        }
2683
-        $this_model_name = $this->get_this_model_name();
2684
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
-        return $related_model->count($query_params, $field_to_count, $distinct);
2687
-    }
2688
-
2689
-
2690
-
2691
-    /**
2692
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
-     *
2695
-     * @param        int           /EE_Base_Class $id_or_obj
2696
-     * @param string $model_name   like 'Event', or 'Registration'
2697
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
-     * @return float
2700
-     * @throws EE_Error
2701
-     */
2702
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
-    {
2704
-        $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2706
-            EE_Error::doing_it_wrong(
2707
-                'EEM_Base::sum_related',
2708
-                sprintf(
2709
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
-                    gettype($query_params)
2711
-                ),
2712
-                '4.6.0'
2713
-            );
2714
-            $query_params = array();
2715
-        }
2716
-        // we're just going to use the query params on the related model's normal get_all query,
2717
-        // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2719
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
-        }
2721
-        $this_model_name = $this->get_this_model_name();
2722
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
-        return $related_model->sum($query_params, $field_to_sum);
2725
-    }
2726
-
2727
-
2728
-
2729
-    /**
2730
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
-     * $modelObject
2732
-     *
2733
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
-     * @return EE_Base_Class
2737
-     * @throws EE_Error
2738
-     */
2739
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
-    {
2741
-        $query_params['limit'] = 1;
2742
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
-        if ($results) {
2744
-            return array_shift($results);
2745
-        }
2746
-        return null;
2747
-    }
2748
-
2749
-
2750
-
2751
-    /**
2752
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
-     *
2754
-     * @return string
2755
-     */
2756
-    public function get_this_model_name()
2757
-    {
2758
-        return str_replace("EEM_", "", get_class($this));
2759
-    }
2760
-
2761
-
2762
-
2763
-    /**
2764
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
-     *
2766
-     * @return EE_Any_Foreign_Model_Name_Field
2767
-     * @throws EE_Error
2768
-     */
2769
-    public function get_field_containing_related_model_name()
2770
-    {
2771
-        foreach ($this->field_settings(true) as $field) {
2772
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
-                $field_with_model_name = $field;
2774
-            }
2775
-        }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
-            throw new EE_Error(sprintf(
2778
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
-                $this->get_this_model_name()
2780
-            ));
2781
-        }
2782
-        return $field_with_model_name;
2783
-    }
2784
-
2785
-
2786
-
2787
-    /**
2788
-     * Inserts a new entry into the database, for each table.
2789
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
-     *
2796
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
-     *                              of EEM_Base)
2800
-     * @return int|string new primary key on main table that got inserted
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function insert($field_n_values)
2804
-    {
2805
-        /**
2806
-         * Filters the fields and their values before inserting an item using the models
2807
-         *
2808
-         * @param array    $fields_n_values keys are the fields and values are their new values
2809
-         * @param EEM_Base $model           the model used
2810
-         */
2811
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
-            $main_table = $this->_get_main_table();
2814
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
-            if ($new_id !== false) {
2816
-                foreach ($this->_get_other_tables() as $other_table) {
2817
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
-                }
2819
-            }
2820
-            /**
2821
-             * Done just after attempting to insert a new model object
2822
-             *
2823
-             * @param EEM_Base   $model           used
2824
-             * @param array      $fields_n_values fields and their values
2825
-             * @param int|string the              ID of the newly-inserted model object
2826
-             */
2827
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
-            return $new_id;
2829
-        }
2830
-        return false;
2831
-    }
2832
-
2833
-
2834
-
2835
-    /**
2836
-     * Checks that the result would satisfy the unique indexes on this model
2837
-     *
2838
-     * @param array  $field_n_values
2839
-     * @param string $action
2840
-     * @return boolean
2841
-     * @throws EE_Error
2842
-     */
2843
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
-    {
2845
-        foreach ($this->unique_indexes() as $index_name => $index) {
2846
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
-            if ($this->exists(array($uniqueness_where_params))) {
2848
-                EE_Error::add_error(
2849
-                    sprintf(
2850
-                        esc_html__(
2851
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
-                            "event_espresso"
2853
-                        ),
2854
-                        $action,
2855
-                        $this->_get_class_name(),
2856
-                        $index_name,
2857
-                        implode(",", $index->field_names()),
2858
-                        http_build_query($uniqueness_where_params)
2859
-                    ),
2860
-                    __FILE__,
2861
-                    __FUNCTION__,
2862
-                    __LINE__
2863
-                );
2864
-                return false;
2865
-            }
2866
-        }
2867
-        return true;
2868
-    }
2869
-
2870
-
2871
-
2872
-    /**
2873
-     * Checks the database for an item that conflicts (ie, if this item were
2874
-     * saved to the DB would break some uniqueness requirement, like a primary key
2875
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
-     * can be either an EE_Base_Class or an array of fields n values
2877
-     *
2878
-     * @param EE_Base_Class|array $obj_or_fields_array
2879
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2880
-     *                                                 when looking for conflicts
2881
-     *                                                 (ie, if false, we ignore the model object's primary key
2882
-     *                                                 when finding "conflicts". If true, it's also considered).
2883
-     *                                                 Only works for INT primary key,
2884
-     *                                                 STRING primary keys cannot be ignored
2885
-     * @throws EE_Error
2886
-     * @return EE_Base_Class|array
2887
-     */
2888
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
-    {
2890
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2892
-        } elseif (is_array($obj_or_fields_array)) {
2893
-            $fields_n_values = $obj_or_fields_array;
2894
-        } else {
2895
-            throw new EE_Error(
2896
-                sprintf(
2897
-                    esc_html__(
2898
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
-                        "event_espresso"
2900
-                    ),
2901
-                    get_class($this),
2902
-                    $obj_or_fields_array
2903
-                )
2904
-            );
2905
-        }
2906
-        $query_params = array();
2907
-        if (
2908
-            $this->has_primary_key_field()
2909
-            && ($include_primary_key
2910
-                || $this->get_primary_key_field()
2911
-                   instanceof
2912
-                   EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2914
-        ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
-        }
2917
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
-        }
2921
-        // if there is nothing to base this search on, then we shouldn't find anything
2922
-        if (empty($query_params)) {
2923
-            return array();
2924
-        }
2925
-        return $this->get_one($query_params);
2926
-    }
2927
-
2928
-
2929
-
2930
-    /**
2931
-     * Like count, but is optimized and returns a boolean instead of an int
2932
-     *
2933
-     * @param array $query_params
2934
-     * @return boolean
2935
-     * @throws EE_Error
2936
-     */
2937
-    public function exists($query_params)
2938
-    {
2939
-        $query_params['limit'] = 1;
2940
-        return $this->count($query_params) > 0;
2941
-    }
2942
-
2943
-
2944
-
2945
-    /**
2946
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
-     *
2948
-     * @param int|string $id
2949
-     * @return boolean
2950
-     * @throws EE_Error
2951
-     */
2952
-    public function exists_by_ID($id)
2953
-    {
2954
-        return $this->exists(
2955
-            array(
2956
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
-                array(
2958
-                    $this->primary_key_name() => $id,
2959
-                ),
2960
-            )
2961
-        );
2962
-    }
2963
-
2964
-
2965
-
2966
-    /**
2967
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
-     * on the main table)
2971
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
-     * cases where we want to call it directly rather than via insert().
2973
-     *
2974
-     * @access   protected
2975
-     * @param EE_Table_Base $table
2976
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
-     *                                       float
2978
-     * @param int           $new_id          for now we assume only int keys
2979
-     * @throws EE_Error
2980
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
-     * @return int ID of new row inserted, or FALSE on failure
2982
-     */
2983
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
-    {
2985
-        global $wpdb;
2986
-        $insertion_col_n_values = array();
2987
-        $format_for_insertion = array();
2988
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
-        foreach ($fields_on_table as $field_name => $field_obj) {
2990
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
-            if ($field_obj->is_auto_increment()) {
2992
-                continue;
2993
-            }
2994
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
-            if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
-            }
3000
-        }
3001
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3002
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3003
-            // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
-        }
3007
-        // insert the new entry
3008
-        $result = $this->_do_wpdb_query(
3009
-            'insert',
3010
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
-        );
3012
-        if ($result === false) {
3013
-            return false;
3014
-        }
3015
-        // ok, now what do we return for the ID of the newly-inserted thing?
3016
-        if ($this->has_primary_key_field()) {
3017
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3018
-                return $wpdb->insert_id;
3019
-            }
3020
-            // it's not an auto-increment primary key, so
3021
-            // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
-        }
3024
-        // we can't return a  primary key because there is none. instead return
3025
-        // a unique string indicating this model
3026
-        return $this->get_index_primary_key_string($fields_n_values);
3027
-    }
3028
-
3029
-
3030
-
3031
-    /**
3032
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
-     * and there is no default, we pass it along. WPDB will take care of it)
3035
-     *
3036
-     * @param EE_Model_Field_Base $field_obj
3037
-     * @param array               $fields_n_values
3038
-     * @return mixed string|int|float depending on what the table column will be expecting
3039
-     * @throws EE_Error
3040
-     */
3041
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
-    {
3043
-        // if this field doesn't allow nullable, don't allow it
3044
-        if (
3045
-            ! $field_obj->is_nullable()
3046
-            && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3049
-            )
3050
-        ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
-        }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3055
-            : null;
3056
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
-    }
3058
-
3059
-
3060
-
3061
-    /**
3062
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
-     * the field's prepare_for_set() method.
3065
-     *
3066
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
-     *                                   top of file)
3069
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
-     *                                   $value is a custom selection
3071
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
-     */
3073
-    private function _prepare_value_for_use_in_db($value, $field)
3074
-    {
3075
-        if ($field && $field instanceof EE_Model_Field_Base) {
3076
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
-            switch ($this->_values_already_prepared_by_model_object) {
3078
-                /** @noinspection PhpMissingBreakStatementInspection */
3079
-                case self::not_prepared_by_model_object:
3080
-                    $value = $field->prepare_for_set($value);
3081
-                // purposefully left out "return"
3082
-                case self::prepared_by_model_object:
3083
-                    /** @noinspection SuspiciousAssignmentsInspection */
3084
-                    $value = $field->prepare_for_use_in_db($value);
3085
-                case self::prepared_for_use_in_db:
3086
-                    // leave the value alone
3087
-            }
3088
-            return $value;
3089
-            // phpcs:enable
3090
-        }
3091
-        return $value;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Returns the main table on this model
3098
-     *
3099
-     * @return EE_Primary_Table
3100
-     * @throws EE_Error
3101
-     */
3102
-    protected function _get_main_table()
3103
-    {
3104
-        foreach ($this->_tables as $table) {
3105
-            if ($table instanceof EE_Primary_Table) {
3106
-                return $table;
3107
-            }
3108
-        }
3109
-        throw new EE_Error(sprintf(esc_html__(
3110
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
-            'event_espresso'
3112
-        ), get_class($this)));
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * table
3119
-     * returns EE_Primary_Table table name
3120
-     *
3121
-     * @return string
3122
-     * @throws EE_Error
3123
-     */
3124
-    public function table()
3125
-    {
3126
-        return $this->_get_main_table()->get_table_name();
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * table
3133
-     * returns first EE_Secondary_Table table name
3134
-     *
3135
-     * @return string
3136
-     */
3137
-    public function second_table()
3138
-    {
3139
-        // grab second table from tables array
3140
-        $second_table = end($this->_tables);
3141
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * get_table_obj_by_alias
3148
-     * returns table name given it's alias
3149
-     *
3150
-     * @param string $table_alias
3151
-     * @return EE_Primary_Table | EE_Secondary_Table
3152
-     */
3153
-    public function get_table_obj_by_alias($table_alias = '')
3154
-    {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
-     *
3163
-     * @return EE_Secondary_Table[]
3164
-     */
3165
-    protected function _get_other_tables()
3166
-    {
3167
-        $other_tables = array();
3168
-        foreach ($this->_tables as $table_alias => $table) {
3169
-            if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3171
-            }
3172
-        }
3173
-        return $other_tables;
3174
-    }
3175
-
3176
-
3177
-
3178
-    /**
3179
-     * Finds all the fields that correspond to the given table
3180
-     *
3181
-     * @param string $table_alias , array key in EEM_Base::_tables
3182
-     * @return EE_Model_Field_Base[]
3183
-     */
3184
-    public function _get_fields_for_table($table_alias)
3185
-    {
3186
-        return $this->_fields[ $table_alias ];
3187
-    }
3188
-
3189
-
3190
-
3191
-    /**
3192
-     * Recurses through all the where parameters, and finds all the related models we'll need
3193
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
-     * related Registration, Transaction, and Payment models.
3197
-     *
3198
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     * @throws EE_Error
3201
-     */
3202
-    public function _extract_related_models_from_query($query_params)
3203
-    {
3204
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
-        if (array_key_exists(0, $query_params)) {
3206
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
-        }
3208
-        if (array_key_exists('group_by', $query_params)) {
3209
-            if (is_array($query_params['group_by'])) {
3210
-                $this->_extract_related_models_from_sub_params_array_values(
3211
-                    $query_params['group_by'],
3212
-                    $query_info_carrier,
3213
-                    'group_by'
3214
-                );
3215
-            } elseif (! empty($query_params['group_by'])) {
3216
-                $this->_extract_related_model_info_from_query_param(
3217
-                    $query_params['group_by'],
3218
-                    $query_info_carrier,
3219
-                    'group_by'
3220
-                );
3221
-            }
3222
-        }
3223
-        if (array_key_exists('having', $query_params)) {
3224
-            $this->_extract_related_models_from_sub_params_array_keys(
3225
-                $query_params[0],
3226
-                $query_info_carrier,
3227
-                'having'
3228
-            );
3229
-        }
3230
-        if (array_key_exists('order_by', $query_params)) {
3231
-            if (is_array($query_params['order_by'])) {
3232
-                $this->_extract_related_models_from_sub_params_array_keys(
3233
-                    $query_params['order_by'],
3234
-                    $query_info_carrier,
3235
-                    'order_by'
3236
-                );
3237
-            } elseif (! empty($query_params['order_by'])) {
3238
-                $this->_extract_related_model_info_from_query_param(
3239
-                    $query_params['order_by'],
3240
-                    $query_info_carrier,
3241
-                    'order_by'
3242
-                );
3243
-            }
3244
-        }
3245
-        if (array_key_exists('force_join', $query_params)) {
3246
-            $this->_extract_related_models_from_sub_params_array_values(
3247
-                $query_params['force_join'],
3248
-                $query_info_carrier,
3249
-                'force_join'
3250
-            );
3251
-        }
3252
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
-        return $query_info_carrier;
3254
-    }
3255
-
3256
-
3257
-
3258
-    /**
3259
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
-     *
3261
-     * @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
3262
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3264
-     * @throws EE_Error
3265
-     * @return \EE_Model_Query_Info_Carrier
3266
-     */
3267
-    private function _extract_related_models_from_sub_params_array_keys(
3268
-        $sub_query_params,
3269
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
-        $query_param_type
3271
-    ) {
3272
-        if (! empty($sub_query_params)) {
3273
-            $sub_query_params = (array) $sub_query_params;
3274
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
-                $this->_extract_related_model_info_from_query_param(
3277
-                    $param,
3278
-                    $model_query_info_carrier,
3279
-                    $query_param_type
3280
-                );
3281
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
-                // of array('Registration.TXN_ID'=>23)
3285
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3288
-                        throw new EE_Error(sprintf(
3289
-                            esc_html__(
3290
-                                "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'))",
3291
-                                "event_espresso"
3292
-                            ),
3293
-                            $param,
3294
-                            $possibly_array_of_params
3295
-                        ));
3296
-                    }
3297
-                    $this->_extract_related_models_from_sub_params_array_keys(
3298
-                        $possibly_array_of_params,
3299
-                        $model_query_info_carrier,
3300
-                        $query_param_type
3301
-                    );
3302
-                } elseif (
3303
-                    $query_param_type === 0 // ie WHERE
3304
-                          && is_array($possibly_array_of_params)
3305
-                          && isset($possibly_array_of_params[2])
3306
-                          && $possibly_array_of_params[2] == true
3307
-                ) {
3308
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3310
-                    // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
-                        throw new EE_Error(sprintf(esc_html__(
3313
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
-                            "event_espresso"
3315
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3316
-                    }
3317
-                    $this->_extract_related_model_info_from_query_param(
3318
-                        $possibly_array_of_params[1],
3319
-                        $model_query_info_carrier,
3320
-                        $query_param_type
3321
-                    );
3322
-                }
3323
-            }
3324
-        }
3325
-        return $model_query_info_carrier;
3326
-    }
3327
-
3328
-
3329
-
3330
-    /**
3331
-     * For extracting related models from forced_joins, where the array values contain the info about what
3332
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
-     *
3334
-     * @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
3335
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3337
-     * @throws EE_Error
3338
-     * @return \EE_Model_Query_Info_Carrier
3339
-     */
3340
-    private function _extract_related_models_from_sub_params_array_values(
3341
-        $sub_query_params,
3342
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
-        $query_param_type
3344
-    ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3347
-                throw new EE_Error(sprintf(
3348
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
-                    $sub_query_params
3350
-                ));
3351
-            }
3352
-            foreach ($sub_query_params as $param) {
3353
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
-                $this->_extract_related_model_info_from_query_param(
3355
-                    $param,
3356
-                    $model_query_info_carrier,
3357
-                    $query_param_type
3358
-                );
3359
-            }
3360
-        }
3361
-        return $model_query_info_carrier;
3362
-    }
3363
-
3364
-
3365
-    /**
3366
-     * Extract all the query parts from  model query params
3367
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
-     * but use them in a different order. Eg, we need to know what models we are querying
3370
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
-     * other models before we can finalize the where clause SQL.
3372
-     *
3373
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
-     * @throws EE_Error
3375
-     * @return EE_Model_Query_Info_Carrier
3376
-     * @throws ModelConfigurationException
3377
-     */
3378
-    public function _create_model_query_info_carrier($query_params)
3379
-    {
3380
-        if (! is_array($query_params)) {
3381
-            EE_Error::doing_it_wrong(
3382
-                'EEM_Base::_create_model_query_info_carrier',
3383
-                sprintf(
3384
-                    esc_html__(
3385
-                        '$query_params should be an array, you passed a variable of type %s',
3386
-                        'event_espresso'
3387
-                    ),
3388
-                    gettype($query_params)
3389
-                ),
3390
-                '4.6.0'
3391
-            );
3392
-            $query_params = array();
3393
-        }
3394
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
-        // first check if we should alter the query to account for caps or not
3396
-        // because the caps might require us to do extra joins
3397
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
-            $query_params[0] = array_replace_recursive(
3399
-                $query_params[0],
3400
-                $this->caps_where_conditions(
3401
-                    $query_params['caps']
3402
-                )
3403
-            );
3404
-        }
3405
-
3406
-        // check if we should alter the query to remove data related to protected
3407
-        // custom post types
3408
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
-            $where_param_key_for_password = $this->modelChainAndPassword();
3410
-            // only include if related to a cpt where no password has been set
3411
-            $query_params[0]['OR*nopassword'] = array(
3412
-                $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3414
-            );
3415
-        }
3416
-        $query_object = $this->_extract_related_models_from_query($query_params);
3417
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
-        foreach ($query_params[0] as $key => $value) {
3419
-            if (is_int($key)) {
3420
-                throw new EE_Error(
3421
-                    sprintf(
3422
-                        esc_html__(
3423
-                            "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.",
3424
-                            "event_espresso"
3425
-                        ),
3426
-                        $key,
3427
-                        var_export($value, true),
3428
-                        var_export($query_params, true),
3429
-                        get_class($this)
3430
-                    )
3431
-                );
3432
-            }
3433
-        }
3434
-        if (
3435
-            array_key_exists('default_where_conditions', $query_params)
3436
-            && ! empty($query_params['default_where_conditions'])
3437
-        ) {
3438
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3439
-        } else {
3440
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
-        }
3442
-        $query_params[0] = array_merge(
3443
-            $this->_get_default_where_conditions_for_models_in_query(
3444
-                $query_object,
3445
-                $use_default_where_conditions,
3446
-                $query_params[0]
3447
-            ),
3448
-            $query_params[0]
3449
-        );
3450
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
-        // So we need to setup a subquery and use that for the main join.
3453
-        // Note for now this only works on the primary table for the model.
3454
-        // So for instance, you could set the limit array like this:
3455
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
-            $query_object->set_main_model_join_sql(
3458
-                $this->_construct_limit_join_select(
3459
-                    $query_params['on_join_limit'][0],
3460
-                    $query_params['on_join_limit'][1]
3461
-                )
3462
-            );
3463
-        }
3464
-        // set limit
3465
-        if (array_key_exists('limit', $query_params)) {
3466
-            if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
-                    $e = sprintf(
3469
-                        esc_html__(
3470
-                            "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)",
3471
-                            "event_espresso"
3472
-                        ),
3473
-                        http_build_query($query_params['limit'])
3474
-                    );
3475
-                    throw new EE_Error($e . "|" . $e);
3476
-                }
3477
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
-            }
3482
-        }
3483
-        // set order by
3484
-        if (array_key_exists('order_by', $query_params)) {
3485
-            if (is_array($query_params['order_by'])) {
3486
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
-                if (array_key_exists('order', $query_params)) {
3490
-                    throw new EE_Error(
3491
-                        sprintf(
3492
-                            esc_html__(
3493
-                                "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 ",
3494
-                                "event_espresso"
3495
-                            ),
3496
-                            get_class($this),
3497
-                            implode(", ", array_keys($query_params['order_by'])),
3498
-                            implode(", ", $query_params['order_by']),
3499
-                            $query_params['order']
3500
-                        )
3501
-                    );
3502
-                }
3503
-                $this->_extract_related_models_from_sub_params_array_keys(
3504
-                    $query_params['order_by'],
3505
-                    $query_object,
3506
-                    'order_by'
3507
-                );
3508
-                // assume it's an array of fields to order by
3509
-                $order_array = array();
3510
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
-                    $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
-                }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3516
-                $this->_extract_related_model_info_from_query_param(
3517
-                    $query_params['order_by'],
3518
-                    $query_object,
3519
-                    'order',
3520
-                    $query_params['order_by']
3521
-                );
3522
-                $order = isset($query_params['order'])
3523
-                    ? $this->_extract_order($query_params['order'])
3524
-                    : 'DESC';
3525
-                $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
-                );
3528
-            }
3529
-        }
3530
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
-        if (
3532
-            ! array_key_exists('order_by', $query_params)
3533
-            && array_key_exists('order', $query_params)
3534
-            && ! empty($query_params['order'])
3535
-        ) {
3536
-            $pk_field = $this->get_primary_key_field();
3537
-            $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
-        }
3540
-        // set group by
3541
-        if (array_key_exists('group_by', $query_params)) {
3542
-            if (is_array($query_params['group_by'])) {
3543
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3544
-                $group_by_array = array();
3545
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
-                }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3550
-                $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
-                );
3553
-            }
3554
-        }
3555
-        // set having
3556
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
-        }
3559
-        // now, just verify they didn't pass anything wack
3560
-        foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
-                throw new EE_Error(
3563
-                    sprintf(
3564
-                        esc_html__(
3565
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
-                            'event_espresso'
3567
-                        ),
3568
-                        $query_key,
3569
-                        get_class($this),
3570
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3571
-                        implode(',', $this->_allowed_query_params)
3572
-                    )
3573
-                );
3574
-            }
3575
-        }
3576
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3577
-        if (empty($main_model_join_sql)) {
3578
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
-        }
3580
-        return $query_object;
3581
-    }
3582
-
3583
-
3584
-
3585
-    /**
3586
-     * Gets the where conditions that should be imposed on the query based on the
3587
-     * context (eg reading frontend, backend, edit or delete).
3588
-     *
3589
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3590
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
-     * @throws EE_Error
3592
-     */
3593
-    public function caps_where_conditions($context = self::caps_read)
3594
-    {
3595
-        EEM_Base::verify_is_valid_cap_context($context);
3596
-        $cap_where_conditions = array();
3597
-        $cap_restrictions = $this->caps_missing($context);
3598
-        /**
3599
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
-         */
3601
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
-            $cap_where_conditions = array_replace_recursive(
3603
-                $cap_where_conditions,
3604
-                $restriction_if_no_cap->get_default_where_conditions()
3605
-            );
3606
-        }
3607
-        return apply_filters(
3608
-            'FHEE__EEM_Base__caps_where_conditions__return',
3609
-            $cap_where_conditions,
3610
-            $this,
3611
-            $context,
3612
-            $cap_restrictions
3613
-        );
3614
-    }
3615
-
3616
-
3617
-
3618
-    /**
3619
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
-     * otherwise throws an exception
3621
-     *
3622
-     * @param string $should_be_order_string
3623
-     * @return string either ASC, asc, DESC or desc
3624
-     * @throws EE_Error
3625
-     */
3626
-    private function _extract_order($should_be_order_string)
3627
-    {
3628
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
-            return $should_be_order_string;
3630
-        }
3631
-        throw new EE_Error(
3632
-            sprintf(
3633
-                esc_html__(
3634
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
-                    "event_espresso"
3636
-                ),
3637
-                get_class($this),
3638
-                $should_be_order_string
3639
-            )
3640
-        );
3641
-    }
3642
-
3643
-
3644
-
3645
-    /**
3646
-     * Looks at all the models which are included in this query, and asks each
3647
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
-     * so they can be merged
3649
-     *
3650
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
-     *                                                                  'none' means NO default where conditions will
3653
-     *                                                                  be used AT ALL during this query.
3654
-     *                                                                  'other_models_only' means default where
3655
-     *                                                                  conditions from other models will be used, but
3656
-     *                                                                  not for this primary model. 'all', the default,
3657
-     *                                                                  means default where conditions will apply as
3658
-     *                                                                  normal
3659
-     * @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
3660
-     * @throws EE_Error
3661
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
-     */
3663
-    private function _get_default_where_conditions_for_models_in_query(
3664
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3665
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
-        $where_query_params = array()
3667
-    ) {
3668
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
-            throw new EE_Error(sprintf(
3671
-                esc_html__(
3672
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
-                    "event_espresso"
3674
-                ),
3675
-                $use_default_where_conditions,
3676
-                implode(", ", $allowed_used_default_where_conditions_values)
3677
-            ));
3678
-        }
3679
-        $universal_query_params = array();
3680
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_default_where_conditions();
3682
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
-            $universal_query_params = $this->_get_minimum_where_conditions();
3684
-        }
3685
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
-            $related_model = $this->get_related_model_obj($model_name);
3687
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
-            } else {
3692
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3693
-                continue;
3694
-            }
3695
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3696
-                $related_model_universal_where_params,
3697
-                $where_query_params,
3698
-                $related_model,
3699
-                $model_relation_path
3700
-            );
3701
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
-                $universal_query_params,
3703
-                $overrides
3704
-            );
3705
-        }
3706
-        return $universal_query_params;
3707
-    }
3708
-
3709
-
3710
-
3711
-    /**
3712
-     * Determines whether or not we should use default where conditions for the model in question
3713
-     * (this model, or other related models).
3714
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
-     * We should use default where conditions on related models when they requested to use default where conditions
3717
-     * on all models, or specifically just on other related models
3718
-     * @param      $default_where_conditions_value
3719
-     * @param bool $for_this_model false means this is for OTHER related models
3720
-     * @return bool
3721
-     */
3722
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
-    {
3724
-        return (
3725
-                   $for_this_model
3726
-                   && in_array(
3727
-                       $default_where_conditions_value,
3728
-                       array(
3729
-                           EEM_Base::default_where_conditions_all,
3730
-                           EEM_Base::default_where_conditions_this_only,
3731
-                           EEM_Base::default_where_conditions_minimum_others,
3732
-                       ),
3733
-                       true
3734
-                   )
3735
-               )
3736
-               || (
3737
-                   ! $for_this_model
3738
-                   && in_array(
3739
-                       $default_where_conditions_value,
3740
-                       array(
3741
-                           EEM_Base::default_where_conditions_all,
3742
-                           EEM_Base::default_where_conditions_others_only,
3743
-                       ),
3744
-                       true
3745
-                   )
3746
-               );
3747
-    }
3748
-
3749
-    /**
3750
-     * Determines whether or not we should use default minimum conditions for the model in question
3751
-     * (this model, or other related models).
3752
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
-     * where conditions.
3754
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
-     * on this model or others
3756
-     * @param      $default_where_conditions_value
3757
-     * @param bool $for_this_model false means this is for OTHER related models
3758
-     * @return bool
3759
-     */
3760
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
-    {
3762
-        return (
3763
-                   $for_this_model
3764
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
-               )
3766
-               || (
3767
-                   ! $for_this_model
3768
-                   && in_array(
3769
-                       $default_where_conditions_value,
3770
-                       array(
3771
-                           EEM_Base::default_where_conditions_minimum_others,
3772
-                           EEM_Base::default_where_conditions_minimum_all,
3773
-                       ),
3774
-                       true
3775
-                   )
3776
-               );
3777
-    }
3778
-
3779
-
3780
-    /**
3781
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
-     * then we also add a special where condition which allows for that model's primary key
3783
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
-     *
3786
-     * @param array    $default_where_conditions
3787
-     * @param array    $provided_where_conditions
3788
-     * @param EEM_Base $model
3789
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3790
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
-     * @throws EE_Error
3792
-     */
3793
-    private function _override_defaults_or_make_null_friendly(
3794
-        $default_where_conditions,
3795
-        $provided_where_conditions,
3796
-        $model,
3797
-        $model_relation_path
3798
-    ) {
3799
-        $null_friendly_where_conditions = array();
3800
-        $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
-        foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3804
-                $none_overridden = false;
3805
-            } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
-            }
3808
-        }
3809
-        if ($none_overridden && $default_where_conditions) {
3810
-            if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
-                                                                                . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3814
-            }/*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
+	protected 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
+					esc_html__(
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(esc_html__(
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
+							esc_html__(
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
+				EEM_Base::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
+				EEM_Base::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
848
+	 *                             different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							esc_html__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(esc_html__(
1375
+						'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).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(esc_html__(
1478
+				'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.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// 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
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// 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)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// 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
1679
+			// 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
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			$field_settings = $this->field_settings();
1790
+			// no primary key, just grab the first column
1791
+			$field = reset($field_settings);
1792
+			// don't need this array now
1793
+			unset($field_settings);
1794
+		}
1795
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
+		$select_expressions = $field->get_qualified_column();
1797
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1798
+		return $this->_do_wpdb_query('get_col', array($SQL));
1799
+	}
1800
+
1801
+
1802
+
1803
+	/**
1804
+	 * Returns a single column value for a single row from the database
1805
+	 *
1806
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1807
+	 * @param string $field_to_select @see EEM_Base::get_col()
1808
+	 * @return string
1809
+	 * @throws EE_Error
1810
+	 */
1811
+	public function get_var($query_params = array(), $field_to_select = null)
1812
+	{
1813
+		$query_params['limit'] = 1;
1814
+		$col = $this->get_col($query_params, $field_to_select);
1815
+		if (! empty($col)) {
1816
+			return reset($col);
1817
+		}
1818
+		return null;
1819
+	}
1820
+
1821
+
1822
+
1823
+	/**
1824
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1825
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1826
+	 * injection, but currently no further filtering is done
1827
+	 *
1828
+	 * @global      $wpdb
1829
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1830
+	 *                               be updated to in the DB
1831
+	 * @return string of SQL
1832
+	 * @throws EE_Error
1833
+	 */
1834
+	public function _construct_update_sql($fields_n_values)
1835
+	{
1836
+		/** @type WPDB $wpdb */
1837
+		global $wpdb;
1838
+		$cols_n_values = array();
1839
+		foreach ($fields_n_values as $field_name => $value) {
1840
+			$field_obj = $this->field_settings_for($field_name);
1841
+			// if the value is NULL, we want to assign the value to that.
1842
+			// wpdb->prepare doesn't really handle that properly
1843
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844
+			$value_sql = $prepared_value === null ? 'NULL'
1845
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1847
+		}
1848
+		return implode(",", $cols_n_values);
1849
+	}
1850
+
1851
+
1852
+
1853
+	/**
1854
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1855
+	 * Performs a HARD delete, meaning the database row should always be removed,
1856
+	 * not just have a flag field on it switched
1857
+	 * Wrapper for EEM_Base::delete_permanently()
1858
+	 *
1859
+	 * @param mixed $id
1860
+	 * @param boolean $allow_blocking
1861
+	 * @return int the number of rows deleted
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1865
+	{
1866
+		return $this->delete_permanently(
1867
+			array(
1868
+				array($this->get_primary_key_field()->get_name() => $id),
1869
+				'limit' => 1,
1870
+			),
1871
+			$allow_blocking
1872
+		);
1873
+	}
1874
+
1875
+
1876
+
1877
+	/**
1878
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1879
+	 * Wrapper for EEM_Base::delete()
1880
+	 *
1881
+	 * @param mixed $id
1882
+	 * @param boolean $allow_blocking
1883
+	 * @return int the number of rows deleted
1884
+	 * @throws EE_Error
1885
+	 */
1886
+	public function delete_by_ID($id, $allow_blocking = true)
1887
+	{
1888
+		return $this->delete(
1889
+			array(
1890
+				array($this->get_primary_key_field()->get_name() => $id),
1891
+				'limit' => 1,
1892
+			),
1893
+			$allow_blocking
1894
+		);
1895
+	}
1896
+
1897
+
1898
+
1899
+	/**
1900
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1901
+	 * meaning if the model has a field that indicates its been "trashed" or
1902
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1903
+	 *
1904
+	 * @see EEM_Base::delete_permanently
1905
+	 * @param array   $query_params
1906
+	 * @param boolean $allow_blocking
1907
+	 * @return int how many rows got deleted
1908
+	 * @throws EE_Error
1909
+	 */
1910
+	public function delete($query_params, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete_permanently($query_params, $allow_blocking);
1913
+	}
1914
+
1915
+
1916
+
1917
+	/**
1918
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1919
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1920
+	 * as archived, not actually deleted
1921
+	 *
1922
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1923
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1924
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1925
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1926
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1927
+	 *                                DB
1928
+	 * @return int how many rows got deleted
1929
+	 * @throws EE_Error
1930
+	 */
1931
+	public function delete_permanently($query_params, $allow_blocking = true)
1932
+	{
1933
+		/**
1934
+		 * Action called just before performing a real deletion query. You can use the
1935
+		 * model and its $query_params to find exactly which items will be deleted
1936
+		 *
1937
+		 * @param EEM_Base $model
1938
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1939
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1940
+		 *                                 to block (prevent) this deletion
1941
+		 */
1942
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1943
+		// some MySQL databases may be running safe mode, which may restrict
1944
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1945
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1946
+		// to delete them
1947
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1948
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1949
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1950
+			$columns_and_ids_for_deleting
1951
+		);
1952
+		/**
1953
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1954
+		 *
1955
+		 * @param EEM_Base $this  The model instance being acted on.
1956
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1957
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1958
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1959
+		 *                                                  derived from the incoming query parameters.
1960
+		 *                                                  @see details on the structure of this array in the phpdocs
1961
+		 *                                                  for the `_get_ids_for_delete_method`
1962
+		 *
1963
+		 */
1964
+		do_action(
1965
+			'AHEE__EEM_Base__delete__before_query',
1966
+			$this,
1967
+			$query_params,
1968
+			$allow_blocking,
1969
+			$columns_and_ids_for_deleting
1970
+		);
1971
+		if ($deletion_where_query_part) {
1972
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
+			$table_aliases = array_keys($this->_tables);
1974
+			$SQL = "DELETE "
1975
+				   . implode(", ", $table_aliases)
1976
+				   . " FROM "
1977
+				   . $model_query_info->get_full_join_sql()
1978
+				   . " WHERE "
1979
+				   . $deletion_where_query_part;
1980
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
+		} else {
1982
+			$rows_deleted = 0;
1983
+		}
1984
+
1985
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
+		// there was no error with the delete query.
1987
+		if (
1988
+			$this->has_primary_key_field()
1989
+			&& $rows_deleted !== false
1990
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1991
+		) {
1992
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1993
+			foreach ($ids_for_removal as $id) {
1994
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1996
+				}
1997
+			}
1998
+
1999
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2000
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2001
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2002
+			// (although it is possible).
2003
+			// Note this can be skipped by using the provided filter and returning false.
2004
+			if (
2005
+				apply_filters(
2006
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2007
+					! $this instanceof EEM_Extra_Meta,
2008
+					$this
2009
+				)
2010
+			) {
2011
+				EEM_Extra_Meta::instance()->delete_permanently(
2012
+					[
2013
+						0 => [
2014
+							'OBJ_ID'   => ['IN', $ids_for_removal],
2015
+							'EXM_type' => $this->get_this_model_name(),
2016
+						]
2017
+					]
2018
+				);
2019
+			}
2020
+		}
2021
+
2022
+		/**
2023
+		 * Action called just after performing a real deletion query. Although at this point the
2024
+		 * items should have been deleted
2025
+		 *
2026
+		 * @param EEM_Base $model
2027
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2028
+		 * @param int      $rows_deleted
2029
+		 */
2030
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
+		return $rows_deleted;// how many supposedly got deleted
2032
+	}
2033
+
2034
+
2035
+
2036
+	/**
2037
+	 * Checks all the relations that throw error messages when there are blocking related objects
2038
+	 * for related model objects. If there are any related model objects on those relations,
2039
+	 * adds an EE_Error, and return true
2040
+	 *
2041
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2042
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2043
+	 *                                                 should be ignored when determining whether there are related
2044
+	 *                                                 model objects which block this model object's deletion. Useful
2045
+	 *                                                 if you know A is related to B and are considering deleting A,
2046
+	 *                                                 but want to see if A has any other objects blocking its deletion
2047
+	 *                                                 before removing the relation between A and B
2048
+	 * @return boolean
2049
+	 * @throws EE_Error
2050
+	 */
2051
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2052
+	{
2053
+		// first, if $ignore_this_model_obj was supplied, get its model
2054
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2055
+			$ignored_model = $ignore_this_model_obj->get_model();
2056
+		} else {
2057
+			$ignored_model = null;
2058
+		}
2059
+		// now check all the relations of $this_model_obj_or_id and see if there
2060
+		// are any related model objects blocking it?
2061
+		$is_blocked = false;
2062
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2063
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2064
+				// if $ignore_this_model_obj was supplied, then for the query
2065
+				// on that model needs to be told to ignore $ignore_this_model_obj
2066
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2067
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2068
+						array(
2069
+							$ignored_model->get_primary_key_field()->get_name() => array(
2070
+								'!=',
2071
+								$ignore_this_model_obj->ID(),
2072
+							),
2073
+						),
2074
+					));
2075
+				} else {
2076
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2077
+				}
2078
+				if ($related_model_objects) {
2079
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2080
+					$is_blocked = true;
2081
+				}
2082
+			}
2083
+		}
2084
+		return $is_blocked;
2085
+	}
2086
+
2087
+
2088
+	/**
2089
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2090
+	 * @param array $row_results_for_deleting
2091
+	 * @param bool  $allow_blocking
2092
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2093
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2094
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2095
+	 *                 deleted. Example:
2096
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2097
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2098
+	 *                 where each element is a group of columns and values that get deleted. Example:
2099
+	 *                      array(
2100
+	 *                          0 => array(
2101
+	 *                              'Term_Relationship.object_id' => 1
2102
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2103
+	 *                          ),
2104
+	 *                          1 => array(
2105
+	 *                              'Term_Relationship.object_id' => 1
2106
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2107
+	 *                          )
2108
+	 *                      )
2109
+	 * @throws EE_Error
2110
+	 */
2111
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2112
+	{
2113
+		$ids_to_delete_indexed_by_column = array();
2114
+		if ($this->has_primary_key_field()) {
2115
+			$primary_table = $this->_get_main_table();
2116
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2117
+			$other_tables = $this->_get_other_tables();
2118
+			$ids_to_delete_indexed_by_column = $query = array();
2119
+			foreach ($row_results_for_deleting as $item_to_delete) {
2120
+				// before we mark this item for deletion,
2121
+				// make sure there's no related entities blocking its deletion (if we're checking)
2122
+				if (
2123
+					$allow_blocking
2124
+					&& $this->delete_is_blocked_by_related_models(
2125
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2126
+					)
2127
+				) {
2128
+					continue;
2129
+				}
2130
+				// primary table deletes
2131
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2134
+				}
2135
+			}
2136
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2137
+			$fields = $this->get_combined_primary_key_fields();
2138
+			foreach ($row_results_for_deleting as $item_to_delete) {
2139
+				$ids_to_delete_indexed_by_column_for_row = array();
2140
+				foreach ($fields as $cpk_field) {
2141
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2142
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2144
+					}
2145
+				}
2146
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2147
+			}
2148
+		} else {
2149
+			// so there's no primary key and no combined key...
2150
+			// sorry, can't help you
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2155
+						"event_espresso"
2156
+					),
2157
+					get_class($this)
2158
+				)
2159
+			);
2160
+		}
2161
+		return $ids_to_delete_indexed_by_column;
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2167
+	 * the corresponding query_part for the query performing the delete.
2168
+	 *
2169
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2170
+	 * @return string
2171
+	 * @throws EE_Error
2172
+	 */
2173
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2174
+	{
2175
+		$query_part = '';
2176
+		if (empty($ids_to_delete_indexed_by_column)) {
2177
+			return $query_part;
2178
+		} elseif ($this->has_primary_key_field()) {
2179
+			$query = array();
2180
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2182
+			}
2183
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
+			$ways_to_identify_a_row = array();
2186
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
+				$values_for_each_combined_primary_key_for_a_row = array();
2188
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
+				}
2191
+				$ways_to_identify_a_row[] = '('
2192
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
+											. ')';
2194
+			}
2195
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2196
+		}
2197
+		return $query_part;
2198
+	}
2199
+
2200
+
2201
+
2202
+	/**
2203
+	 * Gets the model field by the fully qualified name
2204
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
+	 * @return EE_Model_Field_Base
2206
+	 */
2207
+	public function get_field_by_column($qualified_column_name)
2208
+	{
2209
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
+				return $field_obj;
2212
+			}
2213
+		}
2214
+		throw new EE_Error(
2215
+			sprintf(
2216
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
+				$this->get_this_model_name(),
2218
+				$qualified_column_name
2219
+			)
2220
+		);
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Count all the rows that match criteria the model query params.
2227
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
+	 * column
2229
+	 *
2230
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
+	 * @param string $field_to_count field on model to count by (not column name)
2232
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
+	 *                               that by the setting $distinct to TRUE;
2234
+	 * @return int
2235
+	 * @throws EE_Error
2236
+	 */
2237
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
+	{
2239
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
+		if ($field_to_count) {
2241
+			$field_obj = $this->field_settings_for($field_to_count);
2242
+			$column_to_count = $field_obj->get_qualified_column();
2243
+		} elseif ($this->has_primary_key_field()) {
2244
+			$pk_field_obj = $this->get_primary_key_field();
2245
+			$column_to_count = $pk_field_obj->get_qualified_column();
2246
+		} else {
2247
+			// there's no primary key
2248
+			// if we're counting distinct items, and there's no primary key,
2249
+			// we need to list out the columns for distinction;
2250
+			// otherwise we can just use star
2251
+			if ($distinct) {
2252
+				$columns_to_use = array();
2253
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
+					$columns_to_use[] = $field_obj->get_qualified_column();
2255
+				}
2256
+				$column_to_count = implode(',', $columns_to_use);
2257
+			} else {
2258
+				$column_to_count = '*';
2259
+			}
2260
+		}
2261
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
+	}
2265
+
2266
+
2267
+
2268
+	/**
2269
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
+	 *
2271
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2273
+	 * @return float
2274
+	 * @throws EE_Error
2275
+	 */
2276
+	public function sum($query_params, $field_to_sum = null)
2277
+	{
2278
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
+		if ($field_to_sum) {
2280
+			$field_obj = $this->field_settings_for($field_to_sum);
2281
+		} else {
2282
+			$field_obj = $this->get_primary_key_field();
2283
+		}
2284
+		$column_to_count = $field_obj->get_qualified_column();
2285
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
+		$data_type = $field_obj->get_wpdb_data_type();
2288
+		if ($data_type === '%d' || $data_type === '%s') {
2289
+			return (float) $return_value;
2290
+		}
2291
+		// must be %f
2292
+		return (float) $return_value;
2293
+	}
2294
+
2295
+
2296
+
2297
+	/**
2298
+	 * Just calls the specified method on $wpdb with the given arguments
2299
+	 * Consolidates a little extra error handling code
2300
+	 *
2301
+	 * @param string $wpdb_method
2302
+	 * @param array  $arguments_to_provide
2303
+	 * @throws EE_Error
2304
+	 * @global wpdb  $wpdb
2305
+	 * @return mixed
2306
+	 */
2307
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		// if we're in maintenance mode level 2, DON'T run any queries
2310
+		// because level 2 indicates the database needs updating and
2311
+		// is probably out of sync with the code
2312
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
+			throw new EE_Error(sprintf(esc_html__(
2314
+				"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.",
2315
+				"event_espresso"
2316
+			)));
2317
+		}
2318
+		/** @type WPDB $wpdb */
2319
+		global $wpdb;
2320
+		if (! method_exists($wpdb, $wpdb_method)) {
2321
+			throw new EE_Error(sprintf(esc_html__(
2322
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2323
+				'event_espresso'
2324
+			), $wpdb_method));
2325
+		}
2326
+		if (WP_DEBUG) {
2327
+			$old_show_errors_value = $wpdb->show_errors;
2328
+			$wpdb->show_errors(false);
2329
+		}
2330
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2332
+		if (WP_DEBUG) {
2333
+			$wpdb->show_errors($old_show_errors_value);
2334
+			if (! empty($wpdb->last_error)) {
2335
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
+			}
2337
+			if ($result === false) {
2338
+				throw new EE_Error(sprintf(esc_html__(
2339
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
+					'event_espresso'
2341
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2342
+			}
2343
+		} elseif ($result === false) {
2344
+			EE_Error::add_error(
2345
+				sprintf(
2346
+					esc_html__(
2347
+						'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"',
2348
+						'event_espresso'
2349
+					),
2350
+					$wpdb_method,
2351
+					var_export($arguments_to_provide, true),
2352
+					$wpdb->last_error
2353
+				),
2354
+				__FILE__,
2355
+				__FUNCTION__,
2356
+				__LINE__
2357
+			);
2358
+		}
2359
+		return $result;
2360
+	}
2361
+
2362
+
2363
+
2364
+	/**
2365
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2366
+	 * and if there's an error tries to verify the DB is correct. Uses
2367
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2368
+	 * we should try to fix the EE core db, the addons, or just give up
2369
+	 *
2370
+	 * @param string $wpdb_method
2371
+	 * @param array  $arguments_to_provide
2372
+	 * @return mixed
2373
+	 */
2374
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
+	{
2376
+		/** @type WPDB $wpdb */
2377
+		global $wpdb;
2378
+		$wpdb->last_error = null;
2379
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
+		// was there an error running the query? but we don't care on new activations
2381
+		// (we're going to setup the DB anyway on new activations)
2382
+		if (
2383
+			($result === false || ! empty($wpdb->last_error))
2384
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
+		) {
2386
+			switch (EEM_Base::$_db_verification_level) {
2387
+				case EEM_Base::db_verified_none:
2388
+					// let's double-check core's DB
2389
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
+					break;
2391
+				case EEM_Base::db_verified_core:
2392
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
+					break;
2395
+				case EEM_Base::db_verified_addons:
2396
+					// ummmm... you in trouble
2397
+					return $result;
2398
+					break;
2399
+			}
2400
+			if (! empty($error_message)) {
2401
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
+				trigger_error($error_message);
2403
+			}
2404
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+
2411
+	/**
2412
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2413
+	 * EEM_Base::$_db_verification_level
2414
+	 *
2415
+	 * @param string $wpdb_method
2416
+	 * @param array  $arguments_to_provide
2417
+	 * @return string
2418
+	 */
2419
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
+	{
2421
+		/** @type WPDB $wpdb */
2422
+		global $wpdb;
2423
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2424
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
+		$error_message = sprintf(
2426
+			esc_html__(
2427
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
+				'event_espresso'
2429
+			),
2430
+			$wpdb->last_error,
2431
+			$wpdb_method,
2432
+			wp_json_encode($arguments_to_provide)
2433
+		);
2434
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
+		return $error_message;
2436
+	}
2437
+
2438
+
2439
+
2440
+	/**
2441
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
+	 * EEM_Base::$_db_verification_level
2443
+	 *
2444
+	 * @param $wpdb_method
2445
+	 * @param $arguments_to_provide
2446
+	 * @return string
2447
+	 */
2448
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
+	{
2450
+		/** @type WPDB $wpdb */
2451
+		global $wpdb;
2452
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
+		$error_message = sprintf(
2455
+			esc_html__(
2456
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
+				'event_espresso'
2458
+			),
2459
+			$wpdb->last_error,
2460
+			$wpdb_method,
2461
+			wp_json_encode($arguments_to_provide)
2462
+		);
2463
+		EE_System::instance()->initialize_addons();
2464
+		return $error_message;
2465
+	}
2466
+
2467
+
2468
+
2469
+	/**
2470
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
+	 * ..."
2474
+	 *
2475
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2476
+	 * @return string
2477
+	 */
2478
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
+	{
2480
+		return " FROM " . $model_query_info->get_full_join_sql() .
2481
+			   $model_query_info->get_where_sql() .
2482
+			   $model_query_info->get_group_by_sql() .
2483
+			   $model_query_info->get_having_sql() .
2484
+			   $model_query_info->get_order_by_sql() .
2485
+			   $model_query_info->get_limit_sql();
2486
+	}
2487
+
2488
+
2489
+
2490
+	/**
2491
+	 * Set to easily debug the next X queries ran from this model.
2492
+	 *
2493
+	 * @param int $count
2494
+	 */
2495
+	public function show_next_x_db_queries($count = 1)
2496
+	{
2497
+		$this->_show_next_x_db_queries = $count;
2498
+	}
2499
+
2500
+
2501
+
2502
+	/**
2503
+	 * @param $sql_query
2504
+	 */
2505
+	public function show_db_query_if_previously_requested($sql_query)
2506
+	{
2507
+		if ($this->_show_next_x_db_queries > 0) {
2508
+			echo esc_html($sql_query);
2509
+			$this->_show_next_x_db_queries--;
2510
+		}
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
+	 * There are the 3 cases:
2518
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
+	 * $otherModelObject has no ID, it is first saved.
2520
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
+	 * has no ID, it is first saved.
2522
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
+	 * join table
2525
+	 *
2526
+	 * @param        EE_Base_Class                     /int $thisModelObject
2527
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
+	 * @param string $relationName                     , key in EEM_Base::_relations
2529
+	 *                                                 an attendee to a group, you also want to specify which role they
2530
+	 *                                                 will have in that group. So you would use this parameter to
2531
+	 *                                                 specify array('role-column-name'=>'role-id')
2532
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
+	 *                                                 to for relation to methods that allow you to further specify
2534
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
+	 *                                                 because these will be inserted in any new rows created as well.
2537
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
+	 * @throws EE_Error
2539
+	 */
2540
+	public function add_relationship_to(
2541
+		$id_or_obj,
2542
+		$other_model_id_or_obj,
2543
+		$relationName,
2544
+		$extra_join_model_fields_n_values = array()
2545
+	) {
2546
+		$relation_obj = $this->related_settings_for($relationName);
2547
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
+	}
2549
+
2550
+
2551
+
2552
+	/**
2553
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
+	 * There are the 3 cases:
2555
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
+	 * error
2557
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
+	 * an error
2559
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
+	 *
2561
+	 * @param        EE_Base_Class /int $id_or_obj
2562
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
+	 * @param string $relationName key in EEM_Base::_relations
2564
+	 * @return boolean of success
2565
+	 * @throws EE_Error
2566
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
+	 *                             because these will be inserted in any new rows created as well.
2570
+	 */
2571
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
+	{
2573
+		$relation_obj = $this->related_settings_for($relationName);
2574
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * @param mixed           $id_or_obj
2581
+	 * @param string          $relationName
2582
+	 * @param array           $where_query_params
2583
+	 * @param EE_Base_Class[] objects to which relations were removed
2584
+	 * @return \EE_Base_Class[]
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
+	{
2589
+		$relation_obj = $this->related_settings_for($relationName);
2590
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
+	}
2592
+
2593
+
2594
+
2595
+	/**
2596
+	 * Gets all the related items of the specified $model_name, using $query_params.
2597
+	 * Note: by default, we remove the "default query params"
2598
+	 * because we want to get even deleted items etc.
2599
+	 *
2600
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
+	 * @return EE_Base_Class[]
2604
+	 * @throws EE_Error
2605
+	 */
2606
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
+	{
2608
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2609
+		$relation_settings = $this->related_settings_for($model_name);
2610
+		return $relation_settings->get_all_related($model_obj, $query_params);
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Deletes all the model objects across the relation indicated by $model_name
2617
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2619
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
+	 *
2621
+	 * @param EE_Base_Class|int|string $id_or_obj
2622
+	 * @param string                   $model_name
2623
+	 * @param array                    $query_params
2624
+	 * @return int how many deleted
2625
+	 * @throws EE_Error
2626
+	 */
2627
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
+	{
2629
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2630
+		$relation_settings = $this->related_settings_for($model_name);
2631
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2632
+	}
2633
+
2634
+
2635
+
2636
+	/**
2637
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2638
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
+	 * the model objects can't be hard deleted because of blocking related model objects,
2640
+	 * just does a soft-delete on them instead.
2641
+	 *
2642
+	 * @param EE_Base_Class|int|string $id_or_obj
2643
+	 * @param string                   $model_name
2644
+	 * @param array                    $query_params
2645
+	 * @return int how many deleted
2646
+	 * @throws EE_Error
2647
+	 */
2648
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
+	{
2650
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2651
+		$relation_settings = $this->related_settings_for($model_name);
2652
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
+	}
2654
+
2655
+
2656
+
2657
+	/**
2658
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
+	 * unless otherwise specified in the $query_params
2660
+	 *
2661
+	 * @param        int             /EE_Base_Class $id_or_obj
2662
+	 * @param string $model_name     like 'Event', or 'Registration'
2663
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2665
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
+	 *                               that by the setting $distinct to TRUE;
2667
+	 * @return int
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function count_related(
2671
+		$id_or_obj,
2672
+		$model_name,
2673
+		$query_params = array(),
2674
+		$field_to_count = null,
2675
+		$distinct = false
2676
+	) {
2677
+		$related_model = $this->get_related_model_obj($model_name);
2678
+		// we're just going to use the query params on the related model's normal get_all query,
2679
+		// except add a condition to say to match the current mod
2680
+		if (! isset($query_params['default_where_conditions'])) {
2681
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
+		}
2683
+		$this_model_name = $this->get_this_model_name();
2684
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
+		return $related_model->count($query_params, $field_to_count, $distinct);
2687
+	}
2688
+
2689
+
2690
+
2691
+	/**
2692
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
+	 *
2695
+	 * @param        int           /EE_Base_Class $id_or_obj
2696
+	 * @param string $model_name   like 'Event', or 'Registration'
2697
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
+	 * @return float
2700
+	 * @throws EE_Error
2701
+	 */
2702
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
+	{
2704
+		$related_model = $this->get_related_model_obj($model_name);
2705
+		if (! is_array($query_params)) {
2706
+			EE_Error::doing_it_wrong(
2707
+				'EEM_Base::sum_related',
2708
+				sprintf(
2709
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
+					gettype($query_params)
2711
+				),
2712
+				'4.6.0'
2713
+			);
2714
+			$query_params = array();
2715
+		}
2716
+		// we're just going to use the query params on the related model's normal get_all query,
2717
+		// except add a condition to say to match the current mod
2718
+		if (! isset($query_params['default_where_conditions'])) {
2719
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
+		}
2721
+		$this_model_name = $this->get_this_model_name();
2722
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
+		return $related_model->sum($query_params, $field_to_sum);
2725
+	}
2726
+
2727
+
2728
+
2729
+	/**
2730
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
+	 * $modelObject
2732
+	 *
2733
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
+	 * @return EE_Base_Class
2737
+	 * @throws EE_Error
2738
+	 */
2739
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
+	{
2741
+		$query_params['limit'] = 1;
2742
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
+		if ($results) {
2744
+			return array_shift($results);
2745
+		}
2746
+		return null;
2747
+	}
2748
+
2749
+
2750
+
2751
+	/**
2752
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
+	 *
2754
+	 * @return string
2755
+	 */
2756
+	public function get_this_model_name()
2757
+	{
2758
+		return str_replace("EEM_", "", get_class($this));
2759
+	}
2760
+
2761
+
2762
+
2763
+	/**
2764
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
+	 *
2766
+	 * @return EE_Any_Foreign_Model_Name_Field
2767
+	 * @throws EE_Error
2768
+	 */
2769
+	public function get_field_containing_related_model_name()
2770
+	{
2771
+		foreach ($this->field_settings(true) as $field) {
2772
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
+				$field_with_model_name = $field;
2774
+			}
2775
+		}
2776
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
+			throw new EE_Error(sprintf(
2778
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
+				$this->get_this_model_name()
2780
+			));
2781
+		}
2782
+		return $field_with_model_name;
2783
+	}
2784
+
2785
+
2786
+
2787
+	/**
2788
+	 * Inserts a new entry into the database, for each table.
2789
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
+	 *
2796
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
+	 *                              of EEM_Base)
2800
+	 * @return int|string new primary key on main table that got inserted
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function insert($field_n_values)
2804
+	{
2805
+		/**
2806
+		 * Filters the fields and their values before inserting an item using the models
2807
+		 *
2808
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2809
+		 * @param EEM_Base $model           the model used
2810
+		 */
2811
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
+			$main_table = $this->_get_main_table();
2814
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
+			if ($new_id !== false) {
2816
+				foreach ($this->_get_other_tables() as $other_table) {
2817
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
+				}
2819
+			}
2820
+			/**
2821
+			 * Done just after attempting to insert a new model object
2822
+			 *
2823
+			 * @param EEM_Base   $model           used
2824
+			 * @param array      $fields_n_values fields and their values
2825
+			 * @param int|string the              ID of the newly-inserted model object
2826
+			 */
2827
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
+			return $new_id;
2829
+		}
2830
+		return false;
2831
+	}
2832
+
2833
+
2834
+
2835
+	/**
2836
+	 * Checks that the result would satisfy the unique indexes on this model
2837
+	 *
2838
+	 * @param array  $field_n_values
2839
+	 * @param string $action
2840
+	 * @return boolean
2841
+	 * @throws EE_Error
2842
+	 */
2843
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
+	{
2845
+		foreach ($this->unique_indexes() as $index_name => $index) {
2846
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
+			if ($this->exists(array($uniqueness_where_params))) {
2848
+				EE_Error::add_error(
2849
+					sprintf(
2850
+						esc_html__(
2851
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
+							"event_espresso"
2853
+						),
2854
+						$action,
2855
+						$this->_get_class_name(),
2856
+						$index_name,
2857
+						implode(",", $index->field_names()),
2858
+						http_build_query($uniqueness_where_params)
2859
+					),
2860
+					__FILE__,
2861
+					__FUNCTION__,
2862
+					__LINE__
2863
+				);
2864
+				return false;
2865
+			}
2866
+		}
2867
+		return true;
2868
+	}
2869
+
2870
+
2871
+
2872
+	/**
2873
+	 * Checks the database for an item that conflicts (ie, if this item were
2874
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2875
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
+	 * can be either an EE_Base_Class or an array of fields n values
2877
+	 *
2878
+	 * @param EE_Base_Class|array $obj_or_fields_array
2879
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2880
+	 *                                                 when looking for conflicts
2881
+	 *                                                 (ie, if false, we ignore the model object's primary key
2882
+	 *                                                 when finding "conflicts". If true, it's also considered).
2883
+	 *                                                 Only works for INT primary key,
2884
+	 *                                                 STRING primary keys cannot be ignored
2885
+	 * @throws EE_Error
2886
+	 * @return EE_Base_Class|array
2887
+	 */
2888
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
+	{
2890
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2892
+		} elseif (is_array($obj_or_fields_array)) {
2893
+			$fields_n_values = $obj_or_fields_array;
2894
+		} else {
2895
+			throw new EE_Error(
2896
+				sprintf(
2897
+					esc_html__(
2898
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
+						"event_espresso"
2900
+					),
2901
+					get_class($this),
2902
+					$obj_or_fields_array
2903
+				)
2904
+			);
2905
+		}
2906
+		$query_params = array();
2907
+		if (
2908
+			$this->has_primary_key_field()
2909
+			&& ($include_primary_key
2910
+				|| $this->get_primary_key_field()
2911
+				   instanceof
2912
+				   EE_Primary_Key_String_Field)
2913
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2914
+		) {
2915
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
+		}
2917
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
+		}
2921
+		// if there is nothing to base this search on, then we shouldn't find anything
2922
+		if (empty($query_params)) {
2923
+			return array();
2924
+		}
2925
+		return $this->get_one($query_params);
2926
+	}
2927
+
2928
+
2929
+
2930
+	/**
2931
+	 * Like count, but is optimized and returns a boolean instead of an int
2932
+	 *
2933
+	 * @param array $query_params
2934
+	 * @return boolean
2935
+	 * @throws EE_Error
2936
+	 */
2937
+	public function exists($query_params)
2938
+	{
2939
+		$query_params['limit'] = 1;
2940
+		return $this->count($query_params) > 0;
2941
+	}
2942
+
2943
+
2944
+
2945
+	/**
2946
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
+	 *
2948
+	 * @param int|string $id
2949
+	 * @return boolean
2950
+	 * @throws EE_Error
2951
+	 */
2952
+	public function exists_by_ID($id)
2953
+	{
2954
+		return $this->exists(
2955
+			array(
2956
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
+				array(
2958
+					$this->primary_key_name() => $id,
2959
+				),
2960
+			)
2961
+		);
2962
+	}
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
+	 * on the main table)
2971
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
+	 * cases where we want to call it directly rather than via insert().
2973
+	 *
2974
+	 * @access   protected
2975
+	 * @param EE_Table_Base $table
2976
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
+	 *                                       float
2978
+	 * @param int           $new_id          for now we assume only int keys
2979
+	 * @throws EE_Error
2980
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
+	 * @return int ID of new row inserted, or FALSE on failure
2982
+	 */
2983
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
+	{
2985
+		global $wpdb;
2986
+		$insertion_col_n_values = array();
2987
+		$format_for_insertion = array();
2988
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
+		foreach ($fields_on_table as $field_name => $field_obj) {
2990
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
+			if ($field_obj->is_auto_increment()) {
2992
+				continue;
2993
+			}
2994
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
+			if ($prepared_value !== null) {
2997
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
+			}
3000
+		}
3001
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3002
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3003
+			// so add the fk to the main table as a column
3004
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
+		}
3007
+		// insert the new entry
3008
+		$result = $this->_do_wpdb_query(
3009
+			'insert',
3010
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
+		);
3012
+		if ($result === false) {
3013
+			return false;
3014
+		}
3015
+		// ok, now what do we return for the ID of the newly-inserted thing?
3016
+		if ($this->has_primary_key_field()) {
3017
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3018
+				return $wpdb->insert_id;
3019
+			}
3020
+			// it's not an auto-increment primary key, so
3021
+			// it must have been supplied
3022
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
+		}
3024
+		// we can't return a  primary key because there is none. instead return
3025
+		// a unique string indicating this model
3026
+		return $this->get_index_primary_key_string($fields_n_values);
3027
+	}
3028
+
3029
+
3030
+
3031
+	/**
3032
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
+	 * and there is no default, we pass it along. WPDB will take care of it)
3035
+	 *
3036
+	 * @param EE_Model_Field_Base $field_obj
3037
+	 * @param array               $fields_n_values
3038
+	 * @return mixed string|int|float depending on what the table column will be expecting
3039
+	 * @throws EE_Error
3040
+	 */
3041
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
+	{
3043
+		// if this field doesn't allow nullable, don't allow it
3044
+		if (
3045
+			! $field_obj->is_nullable()
3046
+			&& (
3047
+				! isset($fields_n_values[ $field_obj->get_name() ])
3048
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3049
+			)
3050
+		) {
3051
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
+		}
3053
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
+			? $fields_n_values[ $field_obj->get_name() ]
3055
+			: null;
3056
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
+	}
3058
+
3059
+
3060
+
3061
+	/**
3062
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
+	 * the field's prepare_for_set() method.
3065
+	 *
3066
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
+	 *                                   top of file)
3069
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
+	 *                                   $value is a custom selection
3071
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
+	 */
3073
+	private function _prepare_value_for_use_in_db($value, $field)
3074
+	{
3075
+		if ($field && $field instanceof EE_Model_Field_Base) {
3076
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
+			switch ($this->_values_already_prepared_by_model_object) {
3078
+				/** @noinspection PhpMissingBreakStatementInspection */
3079
+				case self::not_prepared_by_model_object:
3080
+					$value = $field->prepare_for_set($value);
3081
+				// purposefully left out "return"
3082
+				case self::prepared_by_model_object:
3083
+					/** @noinspection SuspiciousAssignmentsInspection */
3084
+					$value = $field->prepare_for_use_in_db($value);
3085
+				case self::prepared_for_use_in_db:
3086
+					// leave the value alone
3087
+			}
3088
+			return $value;
3089
+			// phpcs:enable
3090
+		}
3091
+		return $value;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Returns the main table on this model
3098
+	 *
3099
+	 * @return EE_Primary_Table
3100
+	 * @throws EE_Error
3101
+	 */
3102
+	protected function _get_main_table()
3103
+	{
3104
+		foreach ($this->_tables as $table) {
3105
+			if ($table instanceof EE_Primary_Table) {
3106
+				return $table;
3107
+			}
3108
+		}
3109
+		throw new EE_Error(sprintf(esc_html__(
3110
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
+			'event_espresso'
3112
+		), get_class($this)));
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * table
3119
+	 * returns EE_Primary_Table table name
3120
+	 *
3121
+	 * @return string
3122
+	 * @throws EE_Error
3123
+	 */
3124
+	public function table()
3125
+	{
3126
+		return $this->_get_main_table()->get_table_name();
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * table
3133
+	 * returns first EE_Secondary_Table table name
3134
+	 *
3135
+	 * @return string
3136
+	 */
3137
+	public function second_table()
3138
+	{
3139
+		// grab second table from tables array
3140
+		$second_table = end($this->_tables);
3141
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * get_table_obj_by_alias
3148
+	 * returns table name given it's alias
3149
+	 *
3150
+	 * @param string $table_alias
3151
+	 * @return EE_Primary_Table | EE_Secondary_Table
3152
+	 */
3153
+	public function get_table_obj_by_alias($table_alias = '')
3154
+	{
3155
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
+	 *
3163
+	 * @return EE_Secondary_Table[]
3164
+	 */
3165
+	protected function _get_other_tables()
3166
+	{
3167
+		$other_tables = array();
3168
+		foreach ($this->_tables as $table_alias => $table) {
3169
+			if ($table instanceof EE_Secondary_Table) {
3170
+				$other_tables[ $table_alias ] = $table;
3171
+			}
3172
+		}
3173
+		return $other_tables;
3174
+	}
3175
+
3176
+
3177
+
3178
+	/**
3179
+	 * Finds all the fields that correspond to the given table
3180
+	 *
3181
+	 * @param string $table_alias , array key in EEM_Base::_tables
3182
+	 * @return EE_Model_Field_Base[]
3183
+	 */
3184
+	public function _get_fields_for_table($table_alias)
3185
+	{
3186
+		return $this->_fields[ $table_alias ];
3187
+	}
3188
+
3189
+
3190
+
3191
+	/**
3192
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3193
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
+	 * related Registration, Transaction, and Payment models.
3197
+	 *
3198
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 * @throws EE_Error
3201
+	 */
3202
+	public function _extract_related_models_from_query($query_params)
3203
+	{
3204
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
+		if (array_key_exists(0, $query_params)) {
3206
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
+		}
3208
+		if (array_key_exists('group_by', $query_params)) {
3209
+			if (is_array($query_params['group_by'])) {
3210
+				$this->_extract_related_models_from_sub_params_array_values(
3211
+					$query_params['group_by'],
3212
+					$query_info_carrier,
3213
+					'group_by'
3214
+				);
3215
+			} elseif (! empty($query_params['group_by'])) {
3216
+				$this->_extract_related_model_info_from_query_param(
3217
+					$query_params['group_by'],
3218
+					$query_info_carrier,
3219
+					'group_by'
3220
+				);
3221
+			}
3222
+		}
3223
+		if (array_key_exists('having', $query_params)) {
3224
+			$this->_extract_related_models_from_sub_params_array_keys(
3225
+				$query_params[0],
3226
+				$query_info_carrier,
3227
+				'having'
3228
+			);
3229
+		}
3230
+		if (array_key_exists('order_by', $query_params)) {
3231
+			if (is_array($query_params['order_by'])) {
3232
+				$this->_extract_related_models_from_sub_params_array_keys(
3233
+					$query_params['order_by'],
3234
+					$query_info_carrier,
3235
+					'order_by'
3236
+				);
3237
+			} elseif (! empty($query_params['order_by'])) {
3238
+				$this->_extract_related_model_info_from_query_param(
3239
+					$query_params['order_by'],
3240
+					$query_info_carrier,
3241
+					'order_by'
3242
+				);
3243
+			}
3244
+		}
3245
+		if (array_key_exists('force_join', $query_params)) {
3246
+			$this->_extract_related_models_from_sub_params_array_values(
3247
+				$query_params['force_join'],
3248
+				$query_info_carrier,
3249
+				'force_join'
3250
+			);
3251
+		}
3252
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
+		return $query_info_carrier;
3254
+	}
3255
+
3256
+
3257
+
3258
+	/**
3259
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
+	 *
3261
+	 * @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
3262
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3264
+	 * @throws EE_Error
3265
+	 * @return \EE_Model_Query_Info_Carrier
3266
+	 */
3267
+	private function _extract_related_models_from_sub_params_array_keys(
3268
+		$sub_query_params,
3269
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
+		$query_param_type
3271
+	) {
3272
+		if (! empty($sub_query_params)) {
3273
+			$sub_query_params = (array) $sub_query_params;
3274
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
+				$this->_extract_related_model_info_from_query_param(
3277
+					$param,
3278
+					$model_query_info_carrier,
3279
+					$query_param_type
3280
+				);
3281
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
+				// of array('Registration.TXN_ID'=>23)
3285
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
+					if (! is_array($possibly_array_of_params)) {
3288
+						throw new EE_Error(sprintf(
3289
+							esc_html__(
3290
+								"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'))",
3291
+								"event_espresso"
3292
+							),
3293
+							$param,
3294
+							$possibly_array_of_params
3295
+						));
3296
+					}
3297
+					$this->_extract_related_models_from_sub_params_array_keys(
3298
+						$possibly_array_of_params,
3299
+						$model_query_info_carrier,
3300
+						$query_param_type
3301
+					);
3302
+				} elseif (
3303
+					$query_param_type === 0 // ie WHERE
3304
+						  && is_array($possibly_array_of_params)
3305
+						  && isset($possibly_array_of_params[2])
3306
+						  && $possibly_array_of_params[2] == true
3307
+				) {
3308
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
+					// indicating that $possible_array_of_params[1] is actually a field name,
3310
+					// from which we should extract query parameters!
3311
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
+						throw new EE_Error(sprintf(esc_html__(
3313
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
+							"event_espresso"
3315
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3316
+					}
3317
+					$this->_extract_related_model_info_from_query_param(
3318
+						$possibly_array_of_params[1],
3319
+						$model_query_info_carrier,
3320
+						$query_param_type
3321
+					);
3322
+				}
3323
+			}
3324
+		}
3325
+		return $model_query_info_carrier;
3326
+	}
3327
+
3328
+
3329
+
3330
+	/**
3331
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3332
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
+	 *
3334
+	 * @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
3335
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3337
+	 * @throws EE_Error
3338
+	 * @return \EE_Model_Query_Info_Carrier
3339
+	 */
3340
+	private function _extract_related_models_from_sub_params_array_values(
3341
+		$sub_query_params,
3342
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
+		$query_param_type
3344
+	) {
3345
+		if (! empty($sub_query_params)) {
3346
+			if (! is_array($sub_query_params)) {
3347
+				throw new EE_Error(sprintf(
3348
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
+					$sub_query_params
3350
+				));
3351
+			}
3352
+			foreach ($sub_query_params as $param) {
3353
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
+				$this->_extract_related_model_info_from_query_param(
3355
+					$param,
3356
+					$model_query_info_carrier,
3357
+					$query_param_type
3358
+				);
3359
+			}
3360
+		}
3361
+		return $model_query_info_carrier;
3362
+	}
3363
+
3364
+
3365
+	/**
3366
+	 * Extract all the query parts from  model query params
3367
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
+	 * but use them in a different order. Eg, we need to know what models we are querying
3370
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
+	 * other models before we can finalize the where clause SQL.
3372
+	 *
3373
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
+	 * @throws EE_Error
3375
+	 * @return EE_Model_Query_Info_Carrier
3376
+	 * @throws ModelConfigurationException
3377
+	 */
3378
+	public function _create_model_query_info_carrier($query_params)
3379
+	{
3380
+		if (! is_array($query_params)) {
3381
+			EE_Error::doing_it_wrong(
3382
+				'EEM_Base::_create_model_query_info_carrier',
3383
+				sprintf(
3384
+					esc_html__(
3385
+						'$query_params should be an array, you passed a variable of type %s',
3386
+						'event_espresso'
3387
+					),
3388
+					gettype($query_params)
3389
+				),
3390
+				'4.6.0'
3391
+			);
3392
+			$query_params = array();
3393
+		}
3394
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
+		// first check if we should alter the query to account for caps or not
3396
+		// because the caps might require us to do extra joins
3397
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
+			$query_params[0] = array_replace_recursive(
3399
+				$query_params[0],
3400
+				$this->caps_where_conditions(
3401
+					$query_params['caps']
3402
+				)
3403
+			);
3404
+		}
3405
+
3406
+		// check if we should alter the query to remove data related to protected
3407
+		// custom post types
3408
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
+			$where_param_key_for_password = $this->modelChainAndPassword();
3410
+			// only include if related to a cpt where no password has been set
3411
+			$query_params[0]['OR*nopassword'] = array(
3412
+				$where_param_key_for_password => '',
3413
+				$where_param_key_for_password . '*' => array('IS_NULL')
3414
+			);
3415
+		}
3416
+		$query_object = $this->_extract_related_models_from_query($query_params);
3417
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
+		foreach ($query_params[0] as $key => $value) {
3419
+			if (is_int($key)) {
3420
+				throw new EE_Error(
3421
+					sprintf(
3422
+						esc_html__(
3423
+							"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.",
3424
+							"event_espresso"
3425
+						),
3426
+						$key,
3427
+						var_export($value, true),
3428
+						var_export($query_params, true),
3429
+						get_class($this)
3430
+					)
3431
+				);
3432
+			}
3433
+		}
3434
+		if (
3435
+			array_key_exists('default_where_conditions', $query_params)
3436
+			&& ! empty($query_params['default_where_conditions'])
3437
+		) {
3438
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3439
+		} else {
3440
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
+		}
3442
+		$query_params[0] = array_merge(
3443
+			$this->_get_default_where_conditions_for_models_in_query(
3444
+				$query_object,
3445
+				$use_default_where_conditions,
3446
+				$query_params[0]
3447
+			),
3448
+			$query_params[0]
3449
+		);
3450
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
+		// So we need to setup a subquery and use that for the main join.
3453
+		// Note for now this only works on the primary table for the model.
3454
+		// So for instance, you could set the limit array like this:
3455
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
+			$query_object->set_main_model_join_sql(
3458
+				$this->_construct_limit_join_select(
3459
+					$query_params['on_join_limit'][0],
3460
+					$query_params['on_join_limit'][1]
3461
+				)
3462
+			);
3463
+		}
3464
+		// set limit
3465
+		if (array_key_exists('limit', $query_params)) {
3466
+			if (is_array($query_params['limit'])) {
3467
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
+					$e = sprintf(
3469
+						esc_html__(
3470
+							"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)",
3471
+							"event_espresso"
3472
+						),
3473
+						http_build_query($query_params['limit'])
3474
+					);
3475
+					throw new EE_Error($e . "|" . $e);
3476
+				}
3477
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
+			} elseif (! empty($query_params['limit'])) {
3480
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
+			}
3482
+		}
3483
+		// set order by
3484
+		if (array_key_exists('order_by', $query_params)) {
3485
+			if (is_array($query_params['order_by'])) {
3486
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
+				if (array_key_exists('order', $query_params)) {
3490
+					throw new EE_Error(
3491
+						sprintf(
3492
+							esc_html__(
3493
+								"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 ",
3494
+								"event_espresso"
3495
+							),
3496
+							get_class($this),
3497
+							implode(", ", array_keys($query_params['order_by'])),
3498
+							implode(", ", $query_params['order_by']),
3499
+							$query_params['order']
3500
+						)
3501
+					);
3502
+				}
3503
+				$this->_extract_related_models_from_sub_params_array_keys(
3504
+					$query_params['order_by'],
3505
+					$query_object,
3506
+					'order_by'
3507
+				);
3508
+				// assume it's an array of fields to order by
3509
+				$order_array = array();
3510
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
+					$order = $this->_extract_order($order);
3512
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
+				}
3514
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
+			} elseif (! empty($query_params['order_by'])) {
3516
+				$this->_extract_related_model_info_from_query_param(
3517
+					$query_params['order_by'],
3518
+					$query_object,
3519
+					'order',
3520
+					$query_params['order_by']
3521
+				);
3522
+				$order = isset($query_params['order'])
3523
+					? $this->_extract_order($query_params['order'])
3524
+					: 'DESC';
3525
+				$query_object->set_order_by_sql(
3526
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
+				);
3528
+			}
3529
+		}
3530
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
+		if (
3532
+			! array_key_exists('order_by', $query_params)
3533
+			&& array_key_exists('order', $query_params)
3534
+			&& ! empty($query_params['order'])
3535
+		) {
3536
+			$pk_field = $this->get_primary_key_field();
3537
+			$order = $this->_extract_order($query_params['order']);
3538
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
+		}
3540
+		// set group by
3541
+		if (array_key_exists('group_by', $query_params)) {
3542
+			if (is_array($query_params['group_by'])) {
3543
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3544
+				$group_by_array = array();
3545
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
+				}
3548
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
+			} elseif (! empty($query_params['group_by'])) {
3550
+				$query_object->set_group_by_sql(
3551
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
+				);
3553
+			}
3554
+		}
3555
+		// set having
3556
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
+		}
3559
+		// now, just verify they didn't pass anything wack
3560
+		foreach ($query_params as $query_key => $query_value) {
3561
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
+				throw new EE_Error(
3563
+					sprintf(
3564
+						esc_html__(
3565
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
+							'event_espresso'
3567
+						),
3568
+						$query_key,
3569
+						get_class($this),
3570
+						//                      print_r( $this->_allowed_query_params, TRUE )
3571
+						implode(',', $this->_allowed_query_params)
3572
+					)
3573
+				);
3574
+			}
3575
+		}
3576
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3577
+		if (empty($main_model_join_sql)) {
3578
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
+		}
3580
+		return $query_object;
3581
+	}
3582
+
3583
+
3584
+
3585
+	/**
3586
+	 * Gets the where conditions that should be imposed on the query based on the
3587
+	 * context (eg reading frontend, backend, edit or delete).
3588
+	 *
3589
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3590
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
+	 * @throws EE_Error
3592
+	 */
3593
+	public function caps_where_conditions($context = self::caps_read)
3594
+	{
3595
+		EEM_Base::verify_is_valid_cap_context($context);
3596
+		$cap_where_conditions = array();
3597
+		$cap_restrictions = $this->caps_missing($context);
3598
+		/**
3599
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
+		 */
3601
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
+			$cap_where_conditions = array_replace_recursive(
3603
+				$cap_where_conditions,
3604
+				$restriction_if_no_cap->get_default_where_conditions()
3605
+			);
3606
+		}
3607
+		return apply_filters(
3608
+			'FHEE__EEM_Base__caps_where_conditions__return',
3609
+			$cap_where_conditions,
3610
+			$this,
3611
+			$context,
3612
+			$cap_restrictions
3613
+		);
3614
+	}
3615
+
3616
+
3617
+
3618
+	/**
3619
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
+	 * otherwise throws an exception
3621
+	 *
3622
+	 * @param string $should_be_order_string
3623
+	 * @return string either ASC, asc, DESC or desc
3624
+	 * @throws EE_Error
3625
+	 */
3626
+	private function _extract_order($should_be_order_string)
3627
+	{
3628
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
+			return $should_be_order_string;
3630
+		}
3631
+		throw new EE_Error(
3632
+			sprintf(
3633
+				esc_html__(
3634
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
+					"event_espresso"
3636
+				),
3637
+				get_class($this),
3638
+				$should_be_order_string
3639
+			)
3640
+		);
3641
+	}
3642
+
3643
+
3644
+
3645
+	/**
3646
+	 * Looks at all the models which are included in this query, and asks each
3647
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
+	 * so they can be merged
3649
+	 *
3650
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
+	 *                                                                  'none' means NO default where conditions will
3653
+	 *                                                                  be used AT ALL during this query.
3654
+	 *                                                                  'other_models_only' means default where
3655
+	 *                                                                  conditions from other models will be used, but
3656
+	 *                                                                  not for this primary model. 'all', the default,
3657
+	 *                                                                  means default where conditions will apply as
3658
+	 *                                                                  normal
3659
+	 * @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
3660
+	 * @throws EE_Error
3661
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
+	 */
3663
+	private function _get_default_where_conditions_for_models_in_query(
3664
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3665
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
+		$where_query_params = array()
3667
+	) {
3668
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
+			throw new EE_Error(sprintf(
3671
+				esc_html__(
3672
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
+					"event_espresso"
3674
+				),
3675
+				$use_default_where_conditions,
3676
+				implode(", ", $allowed_used_default_where_conditions_values)
3677
+			));
3678
+		}
3679
+		$universal_query_params = array();
3680
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_default_where_conditions();
3682
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
+			$universal_query_params = $this->_get_minimum_where_conditions();
3684
+		}
3685
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
+			$related_model = $this->get_related_model_obj($model_name);
3687
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
+			} else {
3692
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3693
+				continue;
3694
+			}
3695
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3696
+				$related_model_universal_where_params,
3697
+				$where_query_params,
3698
+				$related_model,
3699
+				$model_relation_path
3700
+			);
3701
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
+				$universal_query_params,
3703
+				$overrides
3704
+			);
3705
+		}
3706
+		return $universal_query_params;
3707
+	}
3708
+
3709
+
3710
+
3711
+	/**
3712
+	 * Determines whether or not we should use default where conditions for the model in question
3713
+	 * (this model, or other related models).
3714
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
+	 * We should use default where conditions on related models when they requested to use default where conditions
3717
+	 * on all models, or specifically just on other related models
3718
+	 * @param      $default_where_conditions_value
3719
+	 * @param bool $for_this_model false means this is for OTHER related models
3720
+	 * @return bool
3721
+	 */
3722
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
+	{
3724
+		return (
3725
+				   $for_this_model
3726
+				   && in_array(
3727
+					   $default_where_conditions_value,
3728
+					   array(
3729
+						   EEM_Base::default_where_conditions_all,
3730
+						   EEM_Base::default_where_conditions_this_only,
3731
+						   EEM_Base::default_where_conditions_minimum_others,
3732
+					   ),
3733
+					   true
3734
+				   )
3735
+			   )
3736
+			   || (
3737
+				   ! $for_this_model
3738
+				   && in_array(
3739
+					   $default_where_conditions_value,
3740
+					   array(
3741
+						   EEM_Base::default_where_conditions_all,
3742
+						   EEM_Base::default_where_conditions_others_only,
3743
+					   ),
3744
+					   true
3745
+				   )
3746
+			   );
3747
+	}
3748
+
3749
+	/**
3750
+	 * Determines whether or not we should use default minimum conditions for the model in question
3751
+	 * (this model, or other related models).
3752
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
+	 * where conditions.
3754
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
+	 * on this model or others
3756
+	 * @param      $default_where_conditions_value
3757
+	 * @param bool $for_this_model false means this is for OTHER related models
3758
+	 * @return bool
3759
+	 */
3760
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
+	{
3762
+		return (
3763
+				   $for_this_model
3764
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
+			   )
3766
+			   || (
3767
+				   ! $for_this_model
3768
+				   && in_array(
3769
+					   $default_where_conditions_value,
3770
+					   array(
3771
+						   EEM_Base::default_where_conditions_minimum_others,
3772
+						   EEM_Base::default_where_conditions_minimum_all,
3773
+					   ),
3774
+					   true
3775
+				   )
3776
+			   );
3777
+	}
3778
+
3779
+
3780
+	/**
3781
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
+	 * then we also add a special where condition which allows for that model's primary key
3783
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
+	 *
3786
+	 * @param array    $default_where_conditions
3787
+	 * @param array    $provided_where_conditions
3788
+	 * @param EEM_Base $model
3789
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3790
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
+	 * @throws EE_Error
3792
+	 */
3793
+	private function _override_defaults_or_make_null_friendly(
3794
+		$default_where_conditions,
3795
+		$provided_where_conditions,
3796
+		$model,
3797
+		$model_relation_path
3798
+	) {
3799
+		$null_friendly_where_conditions = array();
3800
+		$none_overridden = true;
3801
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
+		foreach ($default_where_conditions as $key => $val) {
3803
+			if (isset($provided_where_conditions[ $key ])) {
3804
+				$none_overridden = false;
3805
+			} else {
3806
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
+			}
3808
+		}
3809
+		if ($none_overridden && $default_where_conditions) {
3810
+			if ($model->has_primary_key_field()) {
3811
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
+																				. "."
3813
+																				. $model->primary_key_name() ] = array('IS NULL');
3814
+			}/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
3817
-        }
3818
-        return $null_friendly_where_conditions;
3819
-    }
3820
-
3821
-
3822
-
3823
-    /**
3824
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3825
-     * default where conditions on all get_all, update, and delete queries done by this model.
3826
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3828
-     *
3829
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
-     */
3832
-    private function _get_default_where_conditions($model_relation_path = null)
3833
-    {
3834
-        if ($this->_ignore_where_strategy) {
3835
-            return array();
3836
-        }
3837
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
-    }
3839
-
3840
-
3841
-
3842
-    /**
3843
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3847
-     * Similar to _get_default_where_conditions
3848
-     *
3849
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
-     */
3852
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3853
-    {
3854
-        if ($this->_ignore_where_strategy) {
3855
-            return array();
3856
-        }
3857
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
-    }
3859
-
3860
-
3861
-
3862
-    /**
3863
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
-     *
3866
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3867
-     * @return string
3868
-     * @throws EE_Error
3869
-     */
3870
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
-    {
3872
-        $selects = $this->_get_columns_to_select_for_this_model();
3873
-        foreach (
3874
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3875
-        ) {
3876
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3877
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3878
-            foreach ($other_model_selects as $key => $value) {
3879
-                $selects[] = $value;
3880
-            }
3881
-        }
3882
-        return implode(", ", $selects);
3883
-    }
3884
-
3885
-
3886
-
3887
-    /**
3888
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3889
-     * So that's going to be the columns for all the fields on the model
3890
-     *
3891
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3892
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3893
-     */
3894
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3895
-    {
3896
-        $fields = $this->field_settings();
3897
-        $selects = array();
3898
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3899
-            $model_relation_chain,
3900
-            $this->get_this_model_name()
3901
-        );
3902
-        foreach ($fields as $field_obj) {
3903
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3904
-                         . $field_obj->get_table_alias()
3905
-                         . "."
3906
-                         . $field_obj->get_table_column()
3907
-                         . " AS '"
3908
-                         . $table_alias_with_model_relation_chain_prefix
3909
-                         . $field_obj->get_table_alias()
3910
-                         . "."
3911
-                         . $field_obj->get_table_column()
3912
-                         . "'";
3913
-        }
3914
-        // make sure we are also getting the PKs of each table
3915
-        $tables = $this->get_tables();
3916
-        if (count($tables) > 1) {
3917
-            foreach ($tables as $table_obj) {
3918
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919
-                                       . $table_obj->get_fully_qualified_pk_column();
3920
-                if (! in_array($qualified_pk_column, $selects)) {
3921
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922
-                }
3923
-            }
3924
-        }
3925
-        return $selects;
3926
-    }
3927
-
3928
-
3929
-
3930
-    /**
3931
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3932
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3933
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3934
-     * SQL for joining, and the data types
3935
-     *
3936
-     * @param null|string                 $original_query_param
3937
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3938
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3939
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3940
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3941
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3942
-     *                                                          or 'Registration's
3943
-     * @param string                      $original_query_param what it originally was (eg
3944
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3945
-     *                                                          matches $query_param
3946
-     * @throws EE_Error
3947
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3948
-     */
3949
-    private function _extract_related_model_info_from_query_param(
3950
-        $query_param,
3951
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3952
-        $query_param_type,
3953
-        $original_query_param = null
3954
-    ) {
3955
-        if ($original_query_param === null) {
3956
-            $original_query_param = $query_param;
3957
-        }
3958
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3959
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3960
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3961
-        $allow_fields = in_array(
3962
-            $query_param_type,
3963
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3964
-            true
3965
-        );
3966
-        // check to see if we have a field on this model
3967
-        $this_model_fields = $this->field_settings(true);
3968
-        if (array_key_exists($query_param, $this_model_fields)) {
3969
-            if ($allow_fields) {
3970
-                return;
3971
-            }
3972
-            throw new EE_Error(
3973
-                sprintf(
3974
-                    esc_html__(
3975
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3976
-                        "event_espresso"
3977
-                    ),
3978
-                    $query_param,
3979
-                    get_class($this),
3980
-                    $query_param_type,
3981
-                    $original_query_param
3982
-                )
3983
-            );
3984
-        }
3985
-        // check if this is a special logic query param
3986
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3987
-            if ($allow_logic_query_params) {
3988
-                return;
3989
-            }
3990
-            throw new EE_Error(
3991
-                sprintf(
3992
-                    esc_html__(
3993
-                        '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',
3994
-                        'event_espresso'
3995
-                    ),
3996
-                    implode('", "', $this->_logic_query_param_keys),
3997
-                    $query_param,
3998
-                    get_class($this),
3999
-                    '<br />',
4000
-                    "\t"
4001
-                    . ' $passed_in_query_info = <pre>'
4002
-                    . print_r($passed_in_query_info, true)
4003
-                    . '</pre>'
4004
-                    . "\n\t"
4005
-                    . ' $query_param_type = '
4006
-                    . $query_param_type
4007
-                    . "\n\t"
4008
-                    . ' $original_query_param = '
4009
-                    . $original_query_param
4010
-                )
4011
-            );
4012
-        }
4013
-        // check if it's a custom selection
4014
-        if (
4015
-            $this->_custom_selections instanceof CustomSelects
4016
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4017
-        ) {
4018
-            return;
4019
-        }
4020
-        // check if has a model name at the beginning
4021
-        // and
4022
-        // check if it's a field on a related model
4023
-        if (
4024
-            $this->extractJoinModelFromQueryParams(
4025
-                $passed_in_query_info,
4026
-                $query_param,
4027
-                $original_query_param,
4028
-                $query_param_type
4029
-            )
4030
-        ) {
4031
-            return;
4032
-        }
4033
-
4034
-        // ok so $query_param didn't start with a model name
4035
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4036
-        // it's wack, that's what it is
4037
-        throw new EE_Error(
4038
-            sprintf(
4039
-                esc_html__(
4040
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4041
-                    "event_espresso"
4042
-                ),
4043
-                $query_param,
4044
-                get_class($this),
4045
-                $query_param_type,
4046
-                $original_query_param
4047
-            )
4048
-        );
4049
-    }
4050
-
4051
-
4052
-    /**
4053
-     * Extracts any possible join model information from the provided possible_join_string.
4054
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4055
-     * parts that should be added to the query.
4056
-     *
4057
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4058
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4059
-     * @param null|string                 $original_query_param
4060
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4061
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4062
-     * @return bool  returns true if a join was added and false if not.
4063
-     * @throws EE_Error
4064
-     */
4065
-    private function extractJoinModelFromQueryParams(
4066
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4067
-        $possible_join_string,
4068
-        $original_query_param,
4069
-        $query_parameter_type
4070
-    ) {
4071
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4073
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4075
-                if ($possible_join_string === '') {
4076
-                    // nothing left to $query_param
4077
-                    // we should actually end in a field name, not a model like this!
4078
-                    throw new EE_Error(
4079
-                        sprintf(
4080
-                            esc_html__(
4081
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4082
-                                "event_espresso"
4083
-                            ),
4084
-                            $possible_join_string,
4085
-                            $query_parameter_type,
4086
-                            get_class($this),
4087
-                            $valid_related_model_name
4088
-                        )
4089
-                    );
4090
-                }
4091
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4092
-                $related_model_obj->_extract_related_model_info_from_query_param(
4093
-                    $possible_join_string,
4094
-                    $query_info_carrier,
4095
-                    $query_parameter_type,
4096
-                    $original_query_param
4097
-                );
4098
-                return true;
4099
-            }
4100
-            if ($possible_join_string === $valid_related_model_name) {
4101
-                $this->_add_join_to_model(
4102
-                    $valid_related_model_name,
4103
-                    $query_info_carrier,
4104
-                    $original_query_param
4105
-                );
4106
-                return true;
4107
-            }
4108
-        }
4109
-        return false;
4110
-    }
4111
-
4112
-
4113
-    /**
4114
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4115
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4116
-     * @throws EE_Error
4117
-     */
4118
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4119
-    {
4120
-        if (
4121
-            $this->_custom_selections instanceof CustomSelects
4122
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4123
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4124
-            )
4125
-        ) {
4126
-            $original_selects = $this->_custom_selections->originalSelects();
4127
-            foreach ($original_selects as $alias => $select_configuration) {
4128
-                $this->extractJoinModelFromQueryParams(
4129
-                    $query_info_carrier,
4130
-                    $select_configuration[0],
4131
-                    $select_configuration[0],
4132
-                    'custom_selects'
4133
-                );
4134
-            }
4135
-        }
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4142
-     * and store it on $passed_in_query_info
4143
-     *
4144
-     * @param string                      $model_name
4145
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4146
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4147
-     *                                                          model and $model_name. Eg, if we are querying Event,
4148
-     *                                                          and are adding a join to 'Payment' with the original
4149
-     *                                                          query param key
4150
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4151
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4152
-     *                                                          Payment wants to add default query params so that it
4153
-     *                                                          will know what models to prepend onto its default query
4154
-     *                                                          params or in case it wants to rename tables (in case
4155
-     *                                                          there are multiple joins to the same table)
4156
-     * @return void
4157
-     * @throws EE_Error
4158
-     */
4159
-    private function _add_join_to_model(
4160
-        $model_name,
4161
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4162
-        $original_query_param
4163
-    ) {
4164
-        $relation_obj = $this->related_settings_for($model_name);
4165
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4166
-        // check if the relation is HABTM, because then we're essentially doing two joins
4167
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4168
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4169
-            $join_model_obj = $relation_obj->get_join_model();
4170
-            // replace the model specified with the join model for this relation chain, whi
4171
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4172
-                $model_name,
4173
-                $join_model_obj->get_this_model_name(),
4174
-                $model_relation_chain
4175
-            );
4176
-            $passed_in_query_info->merge(
4177
-                new EE_Model_Query_Info_Carrier(
4178
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4179
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4180
-                )
4181
-            );
4182
-        }
4183
-        // now just join to the other table pointed to by the relation object, and add its data types
4184
-        $passed_in_query_info->merge(
4185
-            new EE_Model_Query_Info_Carrier(
4186
-                array($model_relation_chain => $model_name),
4187
-                $relation_obj->get_join_statement($model_relation_chain)
4188
-            )
4189
-        );
4190
-    }
4191
-
4192
-
4193
-
4194
-    /**
4195
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4196
-     *
4197
-     * @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
4198
-     * @return string of SQL
4199
-     * @throws EE_Error
4200
-     */
4201
-    private function _construct_where_clause($where_params)
4202
-    {
4203
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204
-        if ($SQL) {
4205
-            return " WHERE " . $SQL;
4206
-        }
4207
-        return '';
4208
-    }
4209
-
4210
-
4211
-
4212
-    /**
4213
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4214
-     * and should be passed HAVING parameters, not WHERE parameters
4215
-     *
4216
-     * @param array $having_params
4217
-     * @return string
4218
-     * @throws EE_Error
4219
-     */
4220
-    private function _construct_having_clause($having_params)
4221
-    {
4222
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223
-        if ($SQL) {
4224
-            return " HAVING " . $SQL;
4225
-        }
4226
-        return '';
4227
-    }
4228
-
4229
-
4230
-    /**
4231
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4232
-     * Event_Meta.meta_value = 'foo'))"
4233
-     *
4234
-     * @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
4235
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4236
-     * @throws EE_Error
4237
-     * @return string of SQL
4238
-     */
4239
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4240
-    {
4241
-        $where_clauses = array();
4242
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4244
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4245
-                switch ($query_param) {
4246
-                    case 'not':
4247
-                    case 'NOT':
4248
-                        $where_clauses[] = "! ("
4249
-                                           . $this->_construct_condition_clause_recursive(
4250
-                                               $op_and_value_or_sub_condition,
4251
-                                               $glue
4252
-                                           )
4253
-                                           . ")";
4254
-                        break;
4255
-                    case 'and':
4256
-                    case 'AND':
4257
-                        $where_clauses[] = " ("
4258
-                                           . $this->_construct_condition_clause_recursive(
4259
-                                               $op_and_value_or_sub_condition,
4260
-                                               ' AND '
4261
-                                           )
4262
-                                           . ")";
4263
-                        break;
4264
-                    case 'or':
4265
-                    case 'OR':
4266
-                        $where_clauses[] = " ("
4267
-                                           . $this->_construct_condition_clause_recursive(
4268
-                                               $op_and_value_or_sub_condition,
4269
-                                               ' OR '
4270
-                                           )
4271
-                                           . ")";
4272
-                        break;
4273
-                }
4274
-            } else {
4275
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4276
-                // if it's not a normal field, maybe it's a custom selection?
4277
-                if (! $field_obj) {
4278
-                    if ($this->_custom_selections instanceof CustomSelects) {
4279
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280
-                    } else {
4281
-                        throw new EE_Error(sprintf(esc_html__(
4282
-                            "%s is neither a valid model field name, nor a custom selection",
4283
-                            "event_espresso"
4284
-                        ), $query_param));
4285
-                    }
4286
-                }
4287
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4289
-            }
4290
-        }
4291
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4292
-    }
4293
-
4294
-
4295
-
4296
-    /**
4297
-     * Takes the input parameter and extract the table name (alias) and column name
4298
-     *
4299
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4300
-     * @throws EE_Error
4301
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4302
-     */
4303
-    private function _deduce_column_name_from_query_param($query_param)
4304
-    {
4305
-        $field = $this->_deduce_field_from_query_param($query_param);
4306
-        if ($field) {
4307
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4308
-                $field->get_model_name(),
4309
-                $query_param
4310
-            );
4311
-            return $table_alias_prefix . $field->get_qualified_column();
4312
-        }
4313
-        if (
4314
-            $this->_custom_selections instanceof CustomSelects
4315
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4316
-        ) {
4317
-            // maybe it's custom selection item?
4318
-            // if so, just use it as the "column name"
4319
-            return $query_param;
4320
-        }
4321
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4322
-            ? implode(',', $this->_custom_selections->columnAliases())
4323
-            : '';
4324
-        throw new EE_Error(
4325
-            sprintf(
4326
-                esc_html__(
4327
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4328
-                    "event_espresso"
4329
-                ),
4330
-                $query_param,
4331
-                $custom_select_aliases
4332
-            )
4333
-        );
4334
-    }
4335
-
4336
-
4337
-
4338
-    /**
4339
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4340
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4341
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4342
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4343
-     *
4344
-     * @param string $condition_query_param_key
4345
-     * @return string
4346
-     */
4347
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4348
-    {
4349
-        $pos_of_star = strpos($condition_query_param_key, '*');
4350
-        if ($pos_of_star === false) {
4351
-            return $condition_query_param_key;
4352
-        }
4353
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4354
-        return $condition_query_param_sans_star;
4355
-    }
4356
-
4357
-
4358
-
4359
-    /**
4360
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4361
-     *
4362
-     * @param                            mixed      array | string    $op_and_value
4363
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4364
-     * @throws EE_Error
4365
-     * @return string
4366
-     */
4367
-    private function _construct_op_and_value($op_and_value, $field_obj)
4368
-    {
4369
-        if (is_array($op_and_value)) {
4370
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
-            if (! $operator) {
4372
-                $php_array_like_string = array();
4373
-                foreach ($op_and_value as $key => $value) {
4374
-                    $php_array_like_string[] = "$key=>$value";
4375
-                }
4376
-                throw new EE_Error(
4377
-                    sprintf(
4378
-                        esc_html__(
4379
-                            "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))",
4380
-                            "event_espresso"
4381
-                        ),
4382
-                        implode(",", $php_array_like_string)
4383
-                    )
4384
-                );
4385
-            }
4386
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4387
-        } else {
4388
-            $operator = '=';
4389
-            $value = $op_and_value;
4390
-        }
4391
-        // check to see if the value is actually another field
4392
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4394
-        }
4395
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396
-            // in this case, the value should be an array, or at least a comma-separated list
4397
-            // it will need to handle a little differently
4398
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4399
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4400
-            return $operator . SP . $cleaned_value;
4401
-        }
4402
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403
-            // the value should be an array with count of two.
4404
-            if (count($value) !== 2) {
4405
-                throw new EE_Error(
4406
-                    sprintf(
4407
-                        esc_html__(
4408
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4409
-                            'event_espresso'
4410
-                        ),
4411
-                        "BETWEEN"
4412
-                    )
4413
-                );
4414
-            }
4415
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
-            return $operator . SP . $cleaned_value;
4417
-        }
4418
-        if (in_array($operator, $this->valid_null_style_operators())) {
4419
-            if ($value !== null) {
4420
-                throw new EE_Error(
4421
-                    sprintf(
4422
-                        esc_html__(
4423
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4424
-                            "event_espresso"
4425
-                        ),
4426
-                        $value,
4427
-                        $operator
4428
-                    )
4429
-                );
4430
-            }
4431
-            return $operator;
4432
-        }
4433
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4435
-            // remove other junk. So just treat it as a string.
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4437
-        }
4438
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4440
-        }
4441
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442
-            throw new EE_Error(
4443
-                sprintf(
4444
-                    esc_html__(
4445
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4446
-                        'event_espresso'
4447
-                    ),
4448
-                    $operator,
4449
-                    $operator
4450
-                )
4451
-            );
4452
-        }
4453
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454
-            throw new EE_Error(
4455
-                sprintf(
4456
-                    esc_html__(
4457
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4458
-                        'event_espresso'
4459
-                    ),
4460
-                    $operator,
4461
-                    $operator
4462
-                )
4463
-            );
4464
-        }
4465
-        throw new EE_Error(
4466
-            sprintf(
4467
-                esc_html__(
4468
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4469
-                    "event_espresso"
4470
-                ),
4471
-                http_build_query($op_and_value)
4472
-            )
4473
-        );
4474
-    }
4475
-
4476
-
4477
-
4478
-    /**
4479
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4480
-     *
4481
-     * @param array                      $values
4482
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4483
-     *                                              '%s'
4484
-     * @return string
4485
-     * @throws EE_Error
4486
-     */
4487
-    public function _construct_between_value($values, $field_obj)
4488
-    {
4489
-        $cleaned_values = array();
4490
-        foreach ($values as $value) {
4491
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492
-        }
4493
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4494
-    }
4495
-
4496
-
4497
-    /**
4498
-     * Takes an array or a comma-separated list of $values and cleans them
4499
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4500
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4501
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4502
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4503
-     *
4504
-     * @param mixed                      $values    array or comma-separated string
4505
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4506
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4507
-     * @throws EE_Error
4508
-     */
4509
-    public function _construct_in_value($values, $field_obj)
4510
-    {
4511
-        $prepped = [];
4512
-        // check if the value is a CSV list
4513
-        if (is_string($values)) {
4514
-            // in which case, turn it into an array
4515
-            $values = explode(',', $values);
4516
-        }
4517
-        // make sure we only have one of each value in the list
4518
-        $values = array_unique($values);
4519
-        foreach ($values as $value) {
4520
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4521
-        }
4522
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4523
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4524
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525
-        if (empty($prepped)) {
4526
-            $all_fields = $this->field_settings();
4527
-            $first_field    = reset($all_fields);
4528
-            $main_table = $this->_get_main_table();
4529
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530
-        }
4531
-        return '(' . implode(',', $prepped) . ')';
4532
-    }
4533
-
4534
-
4535
-
4536
-    /**
4537
-     * @param mixed                      $value
4538
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
-     * @throws EE_Error
4540
-     * @return false|null|string
4541
-     */
4542
-    private function _wpdb_prepare_using_field($value, $field_obj)
4543
-    {
4544
-        /** @type WPDB $wpdb */
4545
-        global $wpdb;
4546
-        if ($field_obj instanceof EE_Model_Field_Base) {
4547
-            return $wpdb->prepare(
4548
-                $field_obj->get_wpdb_data_type(),
4549
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4550
-            );
4551
-        } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
-            throw new EE_Error(
4554
-                sprintf(
4555
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
-                    $field_obj,
4557
-                    implode(",", $this->_valid_wpdb_data_types)
4558
-                )
4559
-            );
4560
-        }
4561
-        return $wpdb->prepare($field_obj, $value);
4562
-    }
4563
-
4564
-
4565
-
4566
-    /**
4567
-     * Takes the input parameter and finds the model field that it indicates.
4568
-     *
4569
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
-     * @throws EE_Error
4571
-     * @return EE_Model_Field_Base
4572
-     */
4573
-    protected function _deduce_field_from_query_param($query_param_name)
4574
-    {
4575
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
-        // which will help us find the database table and column
4577
-        $query_param_parts = explode(".", $query_param_name);
4578
-        if (empty($query_param_parts)) {
4579
-            throw new EE_Error(sprintf(esc_html__(
4580
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4581
-                'event_espresso'
4582
-            ), $query_param_name));
4583
-        }
4584
-        $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
-        if ($number_of_parts === 1) {
4587
-            $field_name = $last_query_param_part;
4588
-            $model_obj = $this;
4589
-        } else {// $number_of_parts >= 2
4590
-            // the last part is the column name, and there are only 2parts. therefore...
4591
-            $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
-        }
4594
-        try {
4595
-            return $model_obj->field_settings_for($field_name);
4596
-        } catch (EE_Error $e) {
4597
-            return null;
4598
-        }
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
-     * alias and column which corresponds to it
4606
-     *
4607
-     * @param string $field_name
4608
-     * @throws EE_Error
4609
-     * @return string
4610
-     */
4611
-    public function _get_qualified_column_for_field($field_name)
4612
-    {
4613
-        $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
-        if ($field) {
4616
-            return $field->get_qualified_column();
4617
-        }
4618
-        throw new EE_Error(
4619
-            sprintf(
4620
-                esc_html__(
4621
-                    "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.",
4622
-                    'event_espresso'
4623
-                ),
4624
-                $field_name,
4625
-                get_class($this)
4626
-            )
4627
-        );
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
-     * Example usage:
4635
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4636
-     *      array(),
4637
-     *      ARRAY_A,
4638
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
-     *  );
4640
-     * is equivalent to
4641
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
-     * and
4643
-     *  EEM_Event::instance()->get_all_wpdb_results(
4644
-     *      array(
4645
-     *          array(
4646
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
-     *          ),
4648
-     *          ARRAY_A,
4649
-     *          implode(
4650
-     *              ', ',
4651
-     *              array_merge(
4652
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
-     *              )
4655
-     *          )
4656
-     *      )
4657
-     *  );
4658
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
-     *
4660
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
-     *                                            and the one whose fields you are selecting for example: when querying
4662
-     *                                            tickets model and selecting fields from the tickets model you would
4663
-     *                                            leave this parameter empty, because no models are needed to join
4664
-     *                                            between the queried model and the selected one. Likewise when
4665
-     *                                            querying the datetime model and selecting fields from the tickets
4666
-     *                                            model, it would also be left empty, because there is a direct
4667
-     *                                            relation from datetimes to tickets, so no model is needed to join
4668
-     *                                            them together. However, when querying from the event model and
4669
-     *                                            selecting fields from the ticket model, you should provide the string
4670
-     *                                            'Datetime', indicating that the event model must first join to the
4671
-     *                                            datetime model in order to find its relation to ticket model.
4672
-     *                                            Also, when querying from the venue model and selecting fields from
4673
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
-     *                                            indicating you need to join the venue model to the event model,
4675
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4676
-     *                                            This string is used to deduce the prefix that gets added onto the
4677
-     *                                            models' tables qualified columns
4678
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4680
-     *                                            qualified column names
4681
-     * @return array|string
4682
-     */
4683
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
-    {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
-        $qualified_columns = array();
4687
-        foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
-        }
4690
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
-    }
4692
-
4693
-
4694
-
4695
-    /**
4696
-     * constructs the select use on special limit joins
4697
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
-     * (as that is typically where the limits would be set).
4700
-     *
4701
-     * @param  string       $table_alias The table the select is being built for
4702
-     * @param  mixed|string $limit       The limit for this select
4703
-     * @return string                The final select join element for the query.
4704
-     */
4705
-    public function _construct_limit_join_select($table_alias, $limit)
4706
-    {
4707
-        $SQL = '';
4708
-        foreach ($this->_tables as $table_obj) {
4709
-            if ($table_obj instanceof EE_Primary_Table) {
4710
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4711
-                    ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4714
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4715
-                    ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4717
-            }
4718
-        }
4719
-        return $SQL;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
-     *
4728
-     * @return string SQL
4729
-     * @throws EE_Error
4730
-     */
4731
-    public function _construct_internal_join()
4732
-    {
4733
-        $SQL = $this->_get_main_table()->get_table_sql();
4734
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
-        return $SQL;
4736
-    }
4737
-
4738
-
4739
-
4740
-    /**
4741
-     * Constructs the SQL for joining all the tables on this model.
4742
-     * Normally $alias should be the primary table's alias, but in cases where
4743
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
-     * alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     * With $alias being a secondary table's alias, this will construct SQL like:
4748
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
-     *
4750
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
-     * @return string
4752
-     */
4753
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
-    {
4755
-        $SQL = '';
4756
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
-        foreach ($this->_tables as $table_obj) {
4758
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
-                    // so we're joining to this table, meaning the table is already in
4761
-                    // the FROM statement, BUT the primary table isn't. So we want
4762
-                    // to add the inverse join sql
4763
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
-                } else {
4765
-                    // just add a regular JOIN to this table from the primary table
4766
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
-                }
4768
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
-        }
4770
-        return $SQL;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
-     * their data type (eg, '%s', '%d', etc)
4779
-     *
4780
-     * @return array
4781
-     */
4782
-    public function _get_data_types()
4783
-    {
4784
-        $data_types = array();
4785
-        foreach ($this->field_settings() as $field_obj) {
4786
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
-            /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
-        }
4790
-        return $data_types;
4791
-    }
4792
-
4793
-
4794
-
4795
-    /**
4796
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
-     *
4798
-     * @param string $model_name
4799
-     * @throws EE_Error
4800
-     * @return EEM_Base
4801
-     */
4802
-    public function get_related_model_obj($model_name)
4803
-    {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4806
-            throw new EE_Error(sprintf(esc_html__(
4807
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
-                'event_espresso'
4809
-            ), $model_name, $model_classname));
4810
-        }
4811
-        return call_user_func($model_classname . "::instance");
4812
-    }
4813
-
4814
-
4815
-
4816
-    /**
4817
-     * Returns the array of EE_ModelRelations for this model.
4818
-     *
4819
-     * @return EE_Model_Relation_Base[]
4820
-     */
4821
-    public function relation_settings()
4822
-    {
4823
-        return $this->_model_relations;
4824
-    }
4825
-
4826
-
4827
-
4828
-    /**
4829
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
-     * because without THOSE models, this model probably doesn't have much purpose.
4831
-     * (Eg, without an event, datetimes have little purpose.)
4832
-     *
4833
-     * @return EE_Belongs_To_Relation[]
4834
-     */
4835
-    public function belongs_to_relations()
4836
-    {
4837
-        $belongs_to_relations = array();
4838
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4841
-            }
4842
-        }
4843
-        return $belongs_to_relations;
4844
-    }
4845
-
4846
-
4847
-
4848
-    /**
4849
-     * Returns the specified EE_Model_Relation, or throws an exception
4850
-     *
4851
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4852
-     * @throws EE_Error
4853
-     * @return EE_Model_Relation_Base
4854
-     */
4855
-    public function related_settings_for($relation_name)
4856
-    {
4857
-        $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4859
-            throw new EE_Error(
4860
-                sprintf(
4861
-                    esc_html__(
4862
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
-                        'event_espresso'
4864
-                    ),
4865
-                    $relation_name,
4866
-                    $this->_get_class_name(),
4867
-                    implode(', ', array_keys($relatedModels))
4868
-                )
4869
-            );
4870
-        }
4871
-        return $relatedModels[ $relation_name ];
4872
-    }
4873
-
4874
-
4875
-
4876
-    /**
4877
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
-     * fields
4879
-     *
4880
-     * @param string $fieldName
4881
-     * @param boolean $include_db_only_fields
4882
-     * @throws EE_Error
4883
-     * @return EE_Model_Field_Base
4884
-     */
4885
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
-    {
4887
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4889
-            throw new EE_Error(sprintf(
4890
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
-                $fieldName,
4892
-                get_class($this)
4893
-            ));
4894
-        }
4895
-        return $fieldSettings[ $fieldName ];
4896
-    }
4897
-
4898
-
4899
-
4900
-    /**
4901
-     * Checks if this field exists on this model
4902
-     *
4903
-     * @param string $fieldName a key in the model's _field_settings array
4904
-     * @return boolean
4905
-     */
4906
-    public function has_field($fieldName)
4907
-    {
4908
-        $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4910
-            return true;
4911
-        }
4912
-        return false;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Returns whether or not this model has a relation to the specified model
4919
-     *
4920
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4921
-     * @return boolean
4922
-     */
4923
-    public function has_relation($relation_name)
4924
-    {
4925
-        $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4927
-            return true;
4928
-        }
4929
-        return false;
4930
-    }
4931
-
4932
-
4933
-
4934
-    /**
4935
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
-     * Eg, on EE_Answer that would be ANS_ID field object
4937
-     *
4938
-     * @param $field_obj
4939
-     * @return boolean
4940
-     */
4941
-    public function is_primary_key_field($field_obj)
4942
-    {
4943
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
-    }
4945
-
4946
-
4947
-
4948
-    /**
4949
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
-     * Eg, on EE_Answer that would be ANS_ID field object
4951
-     *
4952
-     * @return EE_Model_Field_Base
4953
-     * @throws EE_Error
4954
-     */
4955
-    public function get_primary_key_field()
4956
-    {
4957
-        if ($this->_primary_key_field === null) {
4958
-            foreach ($this->field_settings(true) as $field_obj) {
4959
-                if ($this->is_primary_key_field($field_obj)) {
4960
-                    $this->_primary_key_field = $field_obj;
4961
-                    break;
4962
-                }
4963
-            }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
-                throw new EE_Error(sprintf(
4966
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967
-                    get_class($this)
4968
-                ));
4969
-            }
4970
-        }
4971
-        return $this->_primary_key_field;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * Returns whether or not not there is a primary key on this model.
4978
-     * Internally does some caching.
4979
-     *
4980
-     * @return boolean
4981
-     */
4982
-    public function has_primary_key_field()
4983
-    {
4984
-        if ($this->_has_primary_key_field === null) {
4985
-            try {
4986
-                $this->get_primary_key_field();
4987
-                $this->_has_primary_key_field = true;
4988
-            } catch (EE_Error $e) {
4989
-                $this->_has_primary_key_field = false;
4990
-            }
4991
-        }
4992
-        return $this->_has_primary_key_field;
4993
-    }
4994
-
4995
-
4996
-
4997
-    /**
4998
-     * Finds the first field of type $field_class_name.
4999
-     *
5000
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
-     *                                 EE_Foreign_Key_Field, etc
5002
-     * @return EE_Model_Field_Base or null if none is found
5003
-     */
5004
-    public function get_a_field_of_type($field_class_name)
5005
-    {
5006
-        foreach ($this->field_settings() as $field) {
5007
-            if ($field instanceof $field_class_name) {
5008
-                return $field;
5009
-            }
5010
-        }
5011
-        return null;
5012
-    }
5013
-
5014
-
5015
-
5016
-    /**
5017
-     * Gets a foreign key field pointing to model.
5018
-     *
5019
-     * @param string $model_name eg Event, Registration, not EEM_Event
5020
-     * @return EE_Foreign_Key_Field_Base
5021
-     * @throws EE_Error
5022
-     */
5023
-    public function get_foreign_key_to($model_name)
5024
-    {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
-            foreach ($this->field_settings() as $field) {
5027
-                if (
5028
-                    $field instanceof EE_Foreign_Key_Field_Base
5029
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5030
-                ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
-                    break;
5033
-                }
5034
-            }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
-                throw new EE_Error(sprintf(esc_html__(
5037
-                    "There is no foreign key field pointing to model %s on model %s",
5038
-                    'event_espresso'
5039
-                ), $model_name, get_class($this)));
5040
-            }
5041
-        }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
-    }
5044
-
5045
-
5046
-
5047
-    /**
5048
-     * Gets the table name (including $wpdb->prefix) for the table alias
5049
-     *
5050
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
-     *                            Either one works
5053
-     * @return string
5054
-     */
5055
-    public function get_table_for_alias($table_alias)
5056
-    {
5057
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
-    }
5060
-
5061
-
5062
-
5063
-    /**
5064
-     * Returns a flat array of all field son this model, instead of organizing them
5065
-     * by table_alias as they are in the constructor.
5066
-     *
5067
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5069
-     */
5070
-    public function field_settings($include_db_only_fields = false)
5071
-    {
5072
-        if ($include_db_only_fields) {
5073
-            if ($this->_cached_fields === null) {
5074
-                $this->_cached_fields = array();
5075
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5076
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5078
-                    }
5079
-                }
5080
-            }
5081
-            return $this->_cached_fields;
5082
-        }
5083
-        if ($this->_cached_fields_non_db_only === null) {
5084
-            $this->_cached_fields_non_db_only = array();
5085
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5086
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
-                    /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
-                    }
5091
-                }
5092
-            }
5093
-        }
5094
-        return $this->_cached_fields_non_db_only;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     *        cycle though array of attendees and create objects out of each item
5101
-     *
5102
-     * @access        private
5103
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
-     *                           numerically indexed)
5106
-     * @throws EE_Error
5107
-     */
5108
-    protected function _create_objects($rows = array())
5109
-    {
5110
-        $array_of_objects = array();
5111
-        if (empty($rows)) {
5112
-            return array();
5113
-        }
5114
-        $count_if_model_has_no_primary_key = 0;
5115
-        $has_primary_key = $this->has_primary_key_field();
5116
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
-        foreach ((array) $rows as $row) {
5118
-            if (empty($row)) {
5119
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
-                return array();
5121
-            }
5122
-            // check if we've already set this object in the results array,
5123
-            // in which case there's no need to process it further (again)
5124
-            if ($has_primary_key) {
5125
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
-                    $row,
5127
-                    $primary_key_field->get_qualified_column(),
5128
-                    $primary_key_field->get_table_column()
5129
-                );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
-                    continue;
5132
-                }
5133
-            }
5134
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5136
-                throw new EE_Error(
5137
-                    sprintf(
5138
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5139
-                        $this->get_this_model_name(),
5140
-                        http_build_query($row)
5141
-                    )
5142
-                );
5143
-            }
5144
-            // set the timezone on the instantiated objects
5145
-            $classInstance->set_timezone($this->_timezone);
5146
-            // make sure if there is any timezone setting present that we set the timezone for the object
5147
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5149
-            // also, for all the relations of type BelongsTo, see if we can cache
5150
-            // those related models
5151
-            // (we could do this for other relations too, but if there are conditions
5152
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5153
-            // so it requires a little more thought than just caching them immediately...)
5154
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
-                    // check if this model's INFO is present. If so, cache it on the model
5157
-                    $other_model = $relation_obj->get_other_model();
5158
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
-                    // if we managed to make a model object from the results, cache it on the main model object
5160
-                    if ($other_model_obj_maybe) {
5161
-                        // set timezone on these other model objects if they are present
5162
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5163
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5164
-                    }
5165
-                }
5166
-            }
5167
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
-            // the field in the CustomSelects object
5170
-            if ($this->_custom_selections instanceof CustomSelects) {
5171
-                $classInstance->setCustomSelectsValues(
5172
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5173
-                );
5174
-            }
5175
-        }
5176
-        return $array_of_objects;
5177
-    }
5178
-
5179
-
5180
-    /**
5181
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
-     *
5184
-     * @param array $db_results_row
5185
-     * @return array
5186
-     */
5187
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
-    {
5189
-        $results = array();
5190
-        if ($this->_custom_selections instanceof CustomSelects) {
5191
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5195
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5196
-                    );
5197
-                }
5198
-            }
5199
-        }
5200
-        return $results;
5201
-    }
5202
-
5203
-
5204
-    /**
5205
-     * This will set the value for the given alias
5206
-     * @param string $value
5207
-     * @param string $datatype (one of %d, %s, %f)
5208
-     * @return int|string|float (int for %d, string for %s, float for %f)
5209
-     */
5210
-    protected function convertValueToDataType($value, $datatype)
5211
-    {
5212
-        switch ($datatype) {
5213
-            case '%f':
5214
-                return (float) $value;
5215
-            case '%d':
5216
-                return (int) $value;
5217
-            default:
5218
-                return (string) $value;
5219
-        }
5220
-    }
5221
-
5222
-
5223
-    /**
5224
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
-     * object (as set in the model_field!).
5228
-     *
5229
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
-     */
5231
-    public function create_default_object()
5232
-    {
5233
-        $this_model_fields_and_values = array();
5234
-        // setup the row using default values;
5235
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
-        }
5238
-        $className = $this->_get_class_name();
5239
-        $classInstance = EE_Registry::instance()
5240
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5241
-        return $classInstance;
5242
-    }
5243
-
5244
-
5245
-
5246
-    /**
5247
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
-     *                             or an stdClass where each property is the name of a column,
5249
-     * @return EE_Base_Class
5250
-     * @throws EE_Error
5251
-     */
5252
-    public function instantiate_class_from_array_or_object($cols_n_values)
5253
-    {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
-            $cols_n_values = get_object_vars($cols_n_values);
5256
-        }
5257
-        $primary_key = null;
5258
-        // make sure the array only has keys that are fields/columns on this model
5259
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
-        }
5263
-        $className = $this->_get_class_name();
5264
-        // check we actually found results that we can use to build our model object
5265
-        // if not, return null
5266
-        if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
-                return null;
5269
-            }
5270
-        } elseif ($this->unique_indexes()) {
5271
-            $first_column = reset($this_model_fields_n_values);
5272
-            if (empty($first_column)) {
5273
-                return null;
5274
-            }
5275
-        }
5276
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
-        if ($primary_key) {
5278
-            $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5280
-                $classInstance = EE_Registry::instance()
5281
-                                            ->load_class(
5282
-                                                $className,
5283
-                                                array($this_model_fields_n_values, $this->_timezone),
5284
-                                                true,
5285
-                                                false
5286
-                                            );
5287
-                // add this new object to the entity map
5288
-                $classInstance = $this->add_to_entity_map($classInstance);
5289
-            }
5290
-        } else {
5291
-            $classInstance = EE_Registry::instance()
5292
-                                        ->load_class(
5293
-                                            $className,
5294
-                                            array($this_model_fields_n_values, $this->_timezone),
5295
-                                            true,
5296
-                                            false
5297
-                                        );
5298
-        }
5299
-        return $classInstance;
5300
-    }
5301
-
5302
-
5303
-
5304
-    /**
5305
-     * Gets the model object from the  entity map if it exists
5306
-     *
5307
-     * @param int|string $id the ID of the model object
5308
-     * @return EE_Base_Class
5309
-     */
5310
-    public function get_from_entity_map($id)
5311
-    {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
-    }
5315
-
5316
-
5317
-
5318
-    /**
5319
-     * add_to_entity_map
5320
-     * Adds the object to the model's entity mappings
5321
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
-     *        then this method should be called immediately after the update query
5326
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5328
-     *
5329
-     * @param    EE_Base_Class $object
5330
-     * @throws EE_Error
5331
-     * @return \EE_Base_Class
5332
-     */
5333
-    public function add_to_entity_map(EE_Base_Class $object)
5334
-    {
5335
-        $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5337
-            throw new EE_Error(sprintf(
5338
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
-                is_object($object) ? get_class($object) : $object,
5340
-                $className
5341
-            ));
5342
-        }
5343
-        /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5345
-            throw new EE_Error(sprintf(esc_html__(
5346
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5347
-                "event_espresso"
5348
-            ), get_class($this)));
5349
-        }
5350
-        // double check it's not already there
5351
-        $classInstance = $this->get_from_entity_map($object->ID());
5352
-        if ($classInstance) {
5353
-            return $classInstance;
5354
-        }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
-        return $object;
5357
-    }
5358
-
5359
-
5360
-
5361
-    /**
5362
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5363
-     * if no identifier is provided, then the entire entity map is emptied
5364
-     *
5365
-     * @param int|string $id the ID of the model object
5366
-     * @return boolean
5367
-     */
5368
-    public function clear_entity_map($id = null)
5369
-    {
5370
-        if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
-            return true;
5373
-        }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
-            return true;
5377
-        }
5378
-        return false;
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
-     * Given an array where keys are column (or column alias) names and values,
5386
-     * returns an array of their corresponding field names and database values
5387
-     *
5388
-     * @param array $cols_n_values
5389
-     * @return array
5390
-     */
5391
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
-    {
5393
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * _deduce_fields_n_values_from_cols_n_values
5400
-     * Given an array where keys are column (or column alias) names and values,
5401
-     * returns an array of their corresponding field names and database values
5402
-     *
5403
-     * @param string $cols_n_values
5404
-     * @return array
5405
-     */
5406
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
-    {
5408
-        $this_model_fields_n_values = array();
5409
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
-                $cols_n_values,
5412
-                $table_obj->get_fully_qualified_pk_column(),
5413
-                $table_obj->get_pk_column()
5414
-            );
5415
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5416
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5419
-                        // prepare field as if its coming from db
5420
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
-                    }
5423
-                }
5424
-            } else {
5425
-                // the table's rows existed. Use their values
5426
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
-                            $cols_n_values,
5430
-                            $field_obj->get_qualified_column(),
5431
-                            $field_obj->get_table_column()
5432
-                        );
5433
-                    }
5434
-                }
5435
-            }
5436
-        }
5437
-        return $this_model_fields_n_values;
5438
-    }
5439
-
5440
-
5441
-    /**
5442
-     * @param $cols_n_values
5443
-     * @param $qualified_column
5444
-     * @param $regular_column
5445
-     * @return null
5446
-     * @throws EE_Error
5447
-     * @throws ReflectionException
5448
-     */
5449
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
-    {
5451
-        $value = null;
5452
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
-        // does the field on the model relate to this column retrieved from the db?
5454
-        // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5460
-            // no PK?  ok check if there is a foreign key alias set for this table
5461
-            // then check if that alias exists in the incoming data
5462
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5466
-                    [$pk_class] = explode('.', $PK_column);
5467
-                    $pk_model_name = "EEM_{$pk_class}";
5468
-                    /** @var EEM_Base $pk_model */
5469
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
-                    if ($pk_model instanceof EEM_Base) {
5471
-                        // make sure object is pulled from db and added to entity map
5472
-                        $pk_model->get_one_by_ID($value);
5473
-                    }
5474
-                    break;
5475
-                }
5476
-            }
5477
-        }
5478
-        return $value;
5479
-    }
5480
-
5481
-
5482
-
5483
-    /**
5484
-     * refresh_entity_map_from_db
5485
-     * Makes sure the model object in the entity map at $id assumes the values
5486
-     * of the database (opposite of EE_base_Class::save())
5487
-     *
5488
-     * @param int|string $id
5489
-     * @return EE_Base_Class
5490
-     * @throws EE_Error
5491
-     */
5492
-    public function refresh_entity_map_from_db($id)
5493
-    {
5494
-        $obj_in_map = $this->get_from_entity_map($id);
5495
-        if ($obj_in_map) {
5496
-            $wpdb_results = $this->_get_all_wpdb_results(
5497
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
-            );
5499
-            if ($wpdb_results && is_array($wpdb_results)) {
5500
-                $one_row = reset($wpdb_results);
5501
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
-                    $obj_in_map->set_from_db($field_name, $db_value);
5503
-                }
5504
-                // clear the cache of related model objects
5505
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
-                    $obj_in_map->clear_cache($relation_name, null, true);
5507
-                }
5508
-            }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
-            return $obj_in_map;
5511
-        }
5512
-        return $this->get_one_by_ID($id);
5513
-    }
5514
-
5515
-
5516
-
5517
-    /**
5518
-     * refresh_entity_map_with
5519
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5520
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
-     *
5524
-     * @param int|string    $id
5525
-     * @param EE_Base_Class $replacing_model_obj
5526
-     * @return \EE_Base_Class
5527
-     * @throws EE_Error
5528
-     */
5529
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5530
-    {
5531
-        $obj_in_map = $this->get_from_entity_map($id);
5532
-        if ($obj_in_map) {
5533
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5534
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
-                    $obj_in_map->set($field_name, $value);
5536
-                }
5537
-                // make the model object in the entity map's cache match the $replacing_model_obj
5538
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
-                    $obj_in_map->clear_cache($relation_name, null, true);
5540
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
-                    }
5543
-                }
5544
-            }
5545
-            return $obj_in_map;
5546
-        }
5547
-        $this->add_to_entity_map($replacing_model_obj);
5548
-        return $replacing_model_obj;
5549
-    }
5550
-
5551
-
5552
-
5553
-    /**
5554
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
-     * require_once($this->_getClassName().".class.php");
5557
-     *
5558
-     * @return string
5559
-     */
5560
-    private function _get_class_name()
5561
-    {
5562
-        return "EE_" . $this->get_this_model_name();
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5569
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
-     * it would be 'Events'.
5571
-     *
5572
-     * @param int $quantity
5573
-     * @return string
5574
-     */
5575
-    public function item_name($quantity = 1)
5576
-    {
5577
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
-    }
5579
-
5580
-
5581
-
5582
-    /**
5583
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
-     *        return $previousReturnValue.$returnString;
5595
-     * }
5596
-     * require('EEM_Answer.model.php');
5597
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5598
-     * // will output "you called my_callback! and passed args:monkeys,100"
5599
-     *
5600
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5601
-     * @param array  $args       array of original arguments passed to the function
5602
-     * @throws EE_Error
5603
-     * @return mixed whatever the plugin which calls add_filter decides
5604
-     */
5605
-    public function __call($methodName, $args)
5606
-    {
5607
-        $className = get_class($this);
5608
-        $tagName = "FHEE__{$className}__{$methodName}";
5609
-        if (! has_filter($tagName)) {
5610
-            throw new EE_Error(
5611
-                sprintf(
5612
-                    esc_html__(
5613
-                        '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 );',
5614
-                        'event_espresso'
5615
-                    ),
5616
-                    $methodName,
5617
-                    $className,
5618
-                    $tagName,
5619
-                    '<br />'
5620
-                )
5621
-            );
5622
-        }
5623
-        return apply_filters($tagName, null, $this, $args);
5624
-    }
5625
-
5626
-
5627
-
5628
-    /**
5629
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5630
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5631
-     *
5632
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5633
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5634
-     *                                                       the object's class name
5635
-     *                                                       or object's ID
5636
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5637
-     *                                                       exists in the database. If it does not, we add it
5638
-     * @throws EE_Error
5639
-     * @return EE_Base_Class
5640
-     */
5641
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5642
-    {
5643
-        $className = $this->_get_class_name();
5644
-        if ($base_class_obj_or_id instanceof $className) {
5645
-            $model_object = $base_class_obj_or_id;
5646
-        } else {
5647
-            $primary_key_field = $this->get_primary_key_field();
5648
-            if (
5649
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5650
-                && (
5651
-                    is_int($base_class_obj_or_id)
5652
-                    || is_string($base_class_obj_or_id)
5653
-                )
5654
-            ) {
5655
-                // assume it's an ID.
5656
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5657
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5658
-            } elseif (
5659
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5660
-                && is_string($base_class_obj_or_id)
5661
-            ) {
5662
-                // assume its a string representation of the object
5663
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5664
-            } else {
5665
-                throw new EE_Error(
5666
-                    sprintf(
5667
-                        esc_html__(
5668
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5669
-                            'event_espresso'
5670
-                        ),
5671
-                        $base_class_obj_or_id,
5672
-                        $this->_get_class_name(),
5673
-                        print_r($base_class_obj_or_id, true)
5674
-                    )
5675
-                );
5676
-            }
5677
-        }
5678
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5679
-            $model_object->save();
5680
-        }
5681
-        return $model_object;
5682
-    }
5683
-
5684
-
5685
-
5686
-    /**
5687
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5688
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5689
-     * returns it ID.
5690
-     *
5691
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5692
-     * @return int|string depending on the type of this model object's ID
5693
-     * @throws EE_Error
5694
-     */
5695
-    public function ensure_is_ID($base_class_obj_or_id)
5696
-    {
5697
-        $className = $this->_get_class_name();
5698
-        if ($base_class_obj_or_id instanceof $className) {
5699
-            /** @var $base_class_obj_or_id EE_Base_Class */
5700
-            $id = $base_class_obj_or_id->ID();
5701
-        } elseif (is_int($base_class_obj_or_id)) {
5702
-            // assume it's an ID
5703
-            $id = $base_class_obj_or_id;
5704
-        } elseif (is_string($base_class_obj_or_id)) {
5705
-            // assume its a string representation of the object
5706
-            $id = $base_class_obj_or_id;
5707
-        } else {
5708
-            throw new EE_Error(sprintf(
5709
-                esc_html__(
5710
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5711
-                    'event_espresso'
5712
-                ),
5713
-                $base_class_obj_or_id,
5714
-                $this->_get_class_name(),
5715
-                print_r($base_class_obj_or_id, true)
5716
-            ));
5717
-        }
5718
-        return $id;
5719
-    }
5720
-
5721
-
5722
-
5723
-    /**
5724
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5725
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5726
-     * been sanitized and converted into the appropriate domain.
5727
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5728
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5729
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5730
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5731
-     * $EVT = EEM_Event::instance(); $old_setting =
5732
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5733
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5734
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5735
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5736
-     *
5737
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5738
-     * @return void
5739
-     */
5740
-    public function assume_values_already_prepared_by_model_object(
5741
-        $values_already_prepared = self::not_prepared_by_model_object
5742
-    ) {
5743
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5744
-    }
5745
-
5746
-
5747
-
5748
-    /**
5749
-     * Read comments for assume_values_already_prepared_by_model_object()
5750
-     *
5751
-     * @return int
5752
-     */
5753
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5754
-    {
5755
-        return $this->_values_already_prepared_by_model_object;
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * Gets all the indexes on this model
5762
-     *
5763
-     * @return EE_Index[]
5764
-     */
5765
-    public function indexes()
5766
-    {
5767
-        return $this->_indexes;
5768
-    }
5769
-
5770
-
5771
-
5772
-    /**
5773
-     * Gets all the Unique Indexes on this model
5774
-     *
5775
-     * @return EE_Unique_Index[]
5776
-     */
5777
-    public function unique_indexes()
5778
-    {
5779
-        $unique_indexes = array();
5780
-        foreach ($this->_indexes as $name => $index) {
5781
-            if ($index instanceof EE_Unique_Index) {
5782
-                $unique_indexes [ $name ] = $index;
5783
-            }
5784
-        }
5785
-        return $unique_indexes;
5786
-    }
5787
-
5788
-
5789
-
5790
-    /**
5791
-     * Gets all the fields which, when combined, make the primary key.
5792
-     * This is usually just an array with 1 element (the primary key), but in cases
5793
-     * where there is no primary key, it's a combination of fields as defined
5794
-     * on a primary index
5795
-     *
5796
-     * @return EE_Model_Field_Base[] indexed by the field's name
5797
-     * @throws EE_Error
5798
-     */
5799
-    public function get_combined_primary_key_fields()
5800
-    {
5801
-        foreach ($this->indexes() as $index) {
5802
-            if ($index instanceof EE_Primary_Key_Index) {
5803
-                return $index->fields();
5804
-            }
5805
-        }
5806
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5807
-    }
5808
-
5809
-
5810
-
5811
-    /**
5812
-     * Used to build a primary key string (when the model has no primary key),
5813
-     * which can be used a unique string to identify this model object.
5814
-     *
5815
-     * @param array $fields_n_values keys are field names, values are their values.
5816
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5817
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5818
-     *                               before passing it to this function (that will convert it from columns-n-values
5819
-     *                               to field-names-n-values).
5820
-     * @return string
5821
-     * @throws EE_Error
5822
-     */
5823
-    public function get_index_primary_key_string($fields_n_values)
5824
-    {
5825
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5826
-            $fields_n_values,
5827
-            $this->get_combined_primary_key_fields()
5828
-        );
5829
-        return http_build_query($cols_n_values_for_primary_key_index);
5830
-    }
5831
-
5832
-
5833
-
5834
-    /**
5835
-     * Gets the field values from the primary key string
5836
-     *
5837
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5838
-     * @param string $index_primary_key_string
5839
-     * @return null|array
5840
-     * @throws EE_Error
5841
-     */
5842
-    public function parse_index_primary_key_string($index_primary_key_string)
5843
-    {
5844
-        $key_fields = $this->get_combined_primary_key_fields();
5845
-        // check all of them are in the $id
5846
-        $key_vals_in_combined_pk = array();
5847
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848
-        foreach ($key_fields as $key_field_name => $field_obj) {
5849
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5850
-                return null;
5851
-            }
5852
-        }
5853
-        return $key_vals_in_combined_pk;
5854
-    }
5855
-
5856
-
5857
-
5858
-    /**
5859
-     * verifies that an array of key-value pairs for model fields has a key
5860
-     * for each field comprising the primary key index
5861
-     *
5862
-     * @param array $key_vals
5863
-     * @return boolean
5864
-     * @throws EE_Error
5865
-     */
5866
-    public function has_all_combined_primary_key_fields($key_vals)
5867
-    {
5868
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869
-        foreach ($keys_it_should_have as $key) {
5870
-            if (! isset($key_vals[ $key ])) {
5871
-                return false;
5872
-            }
5873
-        }
5874
-        return true;
5875
-    }
5876
-
5877
-
5878
-
5879
-    /**
5880
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5881
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5882
-     *
5883
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5884
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5885
-     * @throws EE_Error
5886
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5887
-     *                                                              indexed)
5888
-     */
5889
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5890
-    {
5891
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5892
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5893
-        } elseif (is_array($model_object_or_attributes_array)) {
5894
-            $attributes_array = $model_object_or_attributes_array;
5895
-        } else {
5896
-            throw new EE_Error(sprintf(esc_html__(
5897
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5898
-                "event_espresso"
5899
-            ), $model_object_or_attributes_array));
5900
-        }
5901
-        // even copies obviously won't have the same ID, so remove the primary key
5902
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
-            unset($attributes_array[ $this->primary_key_name() ]);
5905
-        }
5906
-        if (isset($query_params[0])) {
5907
-            $query_params[0] = array_merge($attributes_array, $query_params);
5908
-        } else {
5909
-            $query_params[0] = $attributes_array;
5910
-        }
5911
-        return $this->get_all($query_params);
5912
-    }
5913
-
5914
-
5915
-
5916
-    /**
5917
-     * Gets the first copy we find. See get_all_copies for more details
5918
-     *
5919
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5920
-     * @param array $query_params
5921
-     * @return EE_Base_Class
5922
-     * @throws EE_Error
5923
-     */
5924
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925
-    {
5926
-        if (! is_array($query_params)) {
5927
-            EE_Error::doing_it_wrong(
5928
-                'EEM_Base::get_one_copy',
5929
-                sprintf(
5930
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5931
-                    gettype($query_params)
5932
-                ),
5933
-                '4.6.0'
5934
-            );
5935
-            $query_params = array();
5936
-        }
5937
-        $query_params['limit'] = 1;
5938
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5939
-        if (is_array($copies)) {
5940
-            return array_shift($copies);
5941
-        }
5942
-        return null;
5943
-    }
5944
-
5945
-
5946
-
5947
-    /**
5948
-     * Updates the item with the specified id. Ignores default query parameters because
5949
-     * we have specified the ID, and its assumed we KNOW what we're doing
5950
-     *
5951
-     * @param array      $fields_n_values keys are field names, values are their new values
5952
-     * @param int|string $id              the value of the primary key to update
5953
-     * @return int number of rows updated
5954
-     * @throws EE_Error
5955
-     */
5956
-    public function update_by_ID($fields_n_values, $id)
5957
-    {
5958
-        $query_params = array(
5959
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5960
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5961
-        );
5962
-        return $this->update($fields_n_values, $query_params);
5963
-    }
5964
-
5965
-
5966
-
5967
-    /**
5968
-     * Changes an operator which was supplied to the models into one usable in SQL
5969
-     *
5970
-     * @param string $operator_supplied
5971
-     * @return string an operator which can be used in SQL
5972
-     * @throws EE_Error
5973
-     */
5974
-    private function _prepare_operator_for_sql($operator_supplied)
5975
-    {
5976
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5977
-            : null;
5978
-        if ($sql_operator) {
5979
-            return $sql_operator;
5980
-        }
5981
-        throw new EE_Error(
5982
-            sprintf(
5983
-                esc_html__(
5984
-                    "The operator '%s' is not in the list of valid operators: %s",
5985
-                    "event_espresso"
5986
-                ),
5987
-                $operator_supplied,
5988
-                implode(",", array_keys($this->_valid_operators))
5989
-            )
5990
-        );
5991
-    }
5992
-
5993
-
5994
-
5995
-    /**
5996
-     * Gets the valid operators
5997
-     * @return array keys are accepted strings, values are the SQL they are converted to
5998
-     */
5999
-    public function valid_operators()
6000
-    {
6001
-        return $this->_valid_operators;
6002
-    }
6003
-
6004
-
6005
-
6006
-    /**
6007
-     * Gets the between-style operators (take 2 arguments).
6008
-     * @return array keys are accepted strings, values are the SQL they are converted to
6009
-     */
6010
-    public function valid_between_style_operators()
6011
-    {
6012
-        return array_intersect(
6013
-            $this->valid_operators(),
6014
-            $this->_between_style_operators
6015
-        );
6016
-    }
6017
-
6018
-    /**
6019
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6020
-     * @return array keys are accepted strings, values are the SQL they are converted to
6021
-     */
6022
-    public function valid_like_style_operators()
6023
-    {
6024
-        return array_intersect(
6025
-            $this->valid_operators(),
6026
-            $this->_like_style_operators
6027
-        );
6028
-    }
6029
-
6030
-    /**
6031
-     * Gets the "in"-style operators
6032
-     * @return array keys are accepted strings, values are the SQL they are converted to
6033
-     */
6034
-    public function valid_in_style_operators()
6035
-    {
6036
-        return array_intersect(
6037
-            $this->valid_operators(),
6038
-            $this->_in_style_operators
6039
-        );
6040
-    }
6041
-
6042
-    /**
6043
-     * Gets the "null"-style operators (accept no arguments)
6044
-     * @return array keys are accepted strings, values are the SQL they are converted to
6045
-     */
6046
-    public function valid_null_style_operators()
6047
-    {
6048
-        return array_intersect(
6049
-            $this->valid_operators(),
6050
-            $this->_null_style_operators
6051
-        );
6052
-    }
6053
-
6054
-    /**
6055
-     * Gets an array where keys are the primary keys and values are their 'names'
6056
-     * (as determined by the model object's name() function, which is often overridden)
6057
-     *
6058
-     * @param array $query_params like get_all's
6059
-     * @return string[]
6060
-     * @throws EE_Error
6061
-     */
6062
-    public function get_all_names($query_params = array())
6063
-    {
6064
-        $objs = $this->get_all($query_params);
6065
-        $names = array();
6066
-        foreach ($objs as $obj) {
6067
-            $names[ $obj->ID() ] = $obj->name();
6068
-        }
6069
-        return $names;
6070
-    }
6071
-
6072
-
6073
-
6074
-    /**
6075
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6076
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6077
-     * this is duplicated effort and reduces efficiency) you would be better to use
6078
-     * array_keys() on $model_objects.
6079
-     *
6080
-     * @param \EE_Base_Class[] $model_objects
6081
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6082
-     *                                               in the returned array
6083
-     * @return array
6084
-     * @throws EE_Error
6085
-     */
6086
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087
-    {
6088
-        if (! $this->has_primary_key_field()) {
6089
-            if (WP_DEBUG) {
6090
-                EE_Error::add_error(
6091
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6092
-                    __FILE__,
6093
-                    __FUNCTION__,
6094
-                    __LINE__
6095
-                );
6096
-            }
6097
-        }
6098
-        $IDs = array();
6099
-        foreach ($model_objects as $model_object) {
6100
-            $id = $model_object->ID();
6101
-            if (! $id) {
6102
-                if ($filter_out_empty_ids) {
6103
-                    continue;
6104
-                }
6105
-                if (WP_DEBUG) {
6106
-                    EE_Error::add_error(
6107
-                        esc_html__(
6108
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6109
-                            'event_espresso'
6110
-                        ),
6111
-                        __FILE__,
6112
-                        __FUNCTION__,
6113
-                        __LINE__
6114
-                    );
6115
-                }
6116
-            }
6117
-            $IDs[] = $id;
6118
-        }
6119
-        return $IDs;
6120
-    }
6121
-
6122
-
6123
-
6124
-    /**
6125
-     * Returns the string used in capabilities relating to this model. If there
6126
-     * are no capabilities that relate to this model returns false
6127
-     *
6128
-     * @return string|false
6129
-     */
6130
-    public function cap_slug()
6131
-    {
6132
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6133
-    }
6134
-
6135
-
6136
-
6137
-    /**
6138
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6139
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6140
-     * only returns the cap restrictions array in that context (ie, the array
6141
-     * at that key)
6142
-     *
6143
-     * @param string $context
6144
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6145
-     * @throws EE_Error
6146
-     */
6147
-    public function cap_restrictions($context = EEM_Base::caps_read)
6148
-    {
6149
-        EEM_Base::verify_is_valid_cap_context($context);
6150
-        // check if we ought to run the restriction generator first
6151
-        if (
6152
-            isset($this->_cap_restriction_generators[ $context ])
6153
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6155
-        ) {
6156
-            $this->_cap_restrictions[ $context ] = array_merge(
6157
-                $this->_cap_restrictions[ $context ],
6158
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6159
-            );
6160
-        }
6161
-        // and make sure we've finalized the construction of each restriction
6162
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6163
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164
-                $where_conditions_obj->_finalize_construct($this);
6165
-            }
6166
-        }
6167
-        return $this->_cap_restrictions[ $context ];
6168
-    }
6169
-
6170
-
6171
-
6172
-    /**
6173
-     * Indicating whether or not this model thinks its a wp core model
6174
-     *
6175
-     * @return boolean
6176
-     */
6177
-    public function is_wp_core_model()
6178
-    {
6179
-        return $this->_wp_core_model;
6180
-    }
6181
-
6182
-
6183
-
6184
-    /**
6185
-     * Gets all the caps that are missing which impose a restriction on
6186
-     * queries made in this context
6187
-     *
6188
-     * @param string $context one of EEM_Base::caps_ constants
6189
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6190
-     * @throws EE_Error
6191
-     */
6192
-    public function caps_missing($context = EEM_Base::caps_read)
6193
-    {
6194
-        $missing_caps = array();
6195
-        $cap_restrictions = $this->cap_restrictions($context);
6196
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197
-            if (
6198
-                ! EE_Capabilities::instance()
6199
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6200
-            ) {
6201
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6202
-            }
6203
-        }
6204
-        return $missing_caps;
6205
-    }
6206
-
6207
-
6208
-
6209
-    /**
6210
-     * Gets the mapping from capability contexts to action strings used in capability names
6211
-     *
6212
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6213
-     * one of 'read', 'edit', or 'delete'
6214
-     */
6215
-    public function cap_contexts_to_cap_action_map()
6216
-    {
6217
-        return apply_filters(
6218
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6219
-            $this->_cap_contexts_to_cap_action_map,
6220
-            $this
6221
-        );
6222
-    }
6223
-
6224
-
6225
-
6226
-    /**
6227
-     * Gets the action string for the specified capability context
6228
-     *
6229
-     * @param string $context
6230
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6231
-     * @throws EE_Error
6232
-     */
6233
-    public function cap_action_for_context($context)
6234
-    {
6235
-        $mapping = $this->cap_contexts_to_cap_action_map();
6236
-        if (isset($mapping[ $context ])) {
6237
-            return $mapping[ $context ];
6238
-        }
6239
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240
-            return $action;
6241
-        }
6242
-        throw new EE_Error(
6243
-            sprintf(
6244
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6245
-                $context,
6246
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6247
-            )
6248
-        );
6249
-    }
6250
-
6251
-
6252
-
6253
-    /**
6254
-     * Returns all the capability contexts which are valid when querying models
6255
-     *
6256
-     * @return array
6257
-     */
6258
-    public static function valid_cap_contexts()
6259
-    {
6260
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6261
-            self::caps_read,
6262
-            self::caps_read_admin,
6263
-            self::caps_edit,
6264
-            self::caps_delete,
6265
-        ));
6266
-    }
6267
-
6268
-
6269
-
6270
-    /**
6271
-     * Returns all valid options for 'default_where_conditions'
6272
-     *
6273
-     * @return array
6274
-     */
6275
-    public static function valid_default_where_conditions()
6276
-    {
6277
-        return array(
6278
-            EEM_Base::default_where_conditions_all,
6279
-            EEM_Base::default_where_conditions_this_only,
6280
-            EEM_Base::default_where_conditions_others_only,
6281
-            EEM_Base::default_where_conditions_minimum_all,
6282
-            EEM_Base::default_where_conditions_minimum_others,
6283
-            EEM_Base::default_where_conditions_none
6284
-        );
6285
-    }
6286
-
6287
-    // public static function default_where_conditions_full
6288
-    /**
6289
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6290
-     *
6291
-     * @param string $context
6292
-     * @return bool
6293
-     * @throws EE_Error
6294
-     */
6295
-    public static function verify_is_valid_cap_context($context)
6296
-    {
6297
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6298
-        if (in_array($context, $valid_cap_contexts)) {
6299
-            return true;
6300
-        }
6301
-        throw new EE_Error(
6302
-            sprintf(
6303
-                esc_html__(
6304
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6305
-                    'event_espresso'
6306
-                ),
6307
-                $context,
6308
-                'EEM_Base',
6309
-                implode(',', $valid_cap_contexts)
6310
-            )
6311
-        );
6312
-    }
6313
-
6314
-
6315
-
6316
-    /**
6317
-     * Clears all the models field caches. This is only useful when a sub-class
6318
-     * might have added a field or something and these caches might be invalidated
6319
-     */
6320
-    protected function _invalidate_field_caches()
6321
-    {
6322
-        $this->_cache_foreign_key_to_fields = array();
6323
-        $this->_cached_fields = null;
6324
-        $this->_cached_fields_non_db_only = null;
6325
-    }
6326
-
6327
-
6328
-
6329
-    /**
6330
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6331
-     * (eg "and", "or", "not").
6332
-     *
6333
-     * @return array
6334
-     */
6335
-    public function logic_query_param_keys()
6336
-    {
6337
-        return $this->_logic_query_param_keys;
6338
-    }
6339
-
6340
-
6341
-
6342
-    /**
6343
-     * Determines whether or not the where query param array key is for a logic query param.
6344
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6345
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6346
-     *
6347
-     * @param $query_param_key
6348
-     * @return bool
6349
-     */
6350
-    public function is_logic_query_param_key($query_param_key)
6351
-    {
6352
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353
-            if (
6354
-                $query_param_key === $logic_query_param_key
6355
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6356
-            ) {
6357
-                return true;
6358
-            }
6359
-        }
6360
-        return false;
6361
-    }
6362
-
6363
-    /**
6364
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6365
-     * @since 4.9.74.p
6366
-     * @return boolean
6367
-     */
6368
-    public function hasPassword()
6369
-    {
6370
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6371
-        if ($this->has_password_field === null) {
6372
-            $password_field = $this->getPasswordField();
6373
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6374
-        }
6375
-        return $this->has_password_field;
6376
-    }
6377
-
6378
-    /**
6379
-     * Returns the password field on this model, if there is one
6380
-     * @since 4.9.74.p
6381
-     * @return EE_Password_Field|null
6382
-     */
6383
-    public function getPasswordField()
6384
-    {
6385
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6386
-        // there's no need to search for it. If we don't know yet, then find out
6387
-        if ($this->has_password_field === null && $this->password_field === null) {
6388
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6389
-        }
6390
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6391
-        return $this->password_field;
6392
-    }
6393
-
6394
-
6395
-    /**
6396
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6397
-     * @since 4.9.74.p
6398
-     * @return EE_Model_Field_Base[]
6399
-     * @throws EE_Error
6400
-     */
6401
-    public function getPasswordProtectedFields()
6402
-    {
6403
-        $password_field = $this->getPasswordField();
6404
-        $fields = array();
6405
-        if ($password_field instanceof EE_Password_Field) {
6406
-            $field_names = $password_field->protectedFields();
6407
-            foreach ($field_names as $field_name) {
6408
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6409
-            }
6410
-        }
6411
-        return $fields;
6412
-    }
6413
-
6414
-
6415
-    /**
6416
-     * Checks if the current user can perform the requested action on this model
6417
-     * @since 4.9.74.p
6418
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6419
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6420
-     * @return bool
6421
-     * @throws EE_Error
6422
-     * @throws InvalidArgumentException
6423
-     * @throws InvalidDataTypeException
6424
-     * @throws InvalidInterfaceException
6425
-     * @throws ReflectionException
6426
-     * @throws UnexpectedEntityException
6427
-     */
6428
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6429
-    {
6430
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432
-        }
6433
-        if (!is_array($model_obj_or_fields_n_values)) {
6434
-            throw new UnexpectedEntityException(
6435
-                $model_obj_or_fields_n_values,
6436
-                'EE_Base_Class',
6437
-                sprintf(
6438
-                    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'),
6439
-                    __FUNCTION__
6440
-                )
6441
-            );
6442
-        }
6443
-        return $this->exists(
6444
-            $this->alter_query_params_to_restrict_by_ID(
6445
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6446
-                array(
6447
-                    'default_where_conditions' => 'none',
6448
-                    'caps'                     => $cap_to_check,
6449
-                )
6450
-            )
6451
-        );
6452
-    }
6453
-
6454
-    /**
6455
-     * Returns the query param where conditions key to the password affecting this model.
6456
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6457
-     * @since 4.9.74.p
6458
-     * @return null|string
6459
-     * @throws EE_Error
6460
-     * @throws InvalidArgumentException
6461
-     * @throws InvalidDataTypeException
6462
-     * @throws InvalidInterfaceException
6463
-     * @throws ModelConfigurationException
6464
-     * @throws ReflectionException
6465
-     */
6466
-    public function modelChainAndPassword()
6467
-    {
6468
-        if ($this->model_chain_to_password === null) {
6469
-            throw new ModelConfigurationException(
6470
-                $this,
6471
-                esc_html_x(
6472
-                // @codingStandardsIgnoreStart
6473
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6474
-                    // @codingStandardsIgnoreEnd
6475
-                    '1: model name',
6476
-                    'event_espresso'
6477
-                )
6478
-            );
6479
-        }
6480
-        if ($this->model_chain_to_password === '') {
6481
-            $model_with_password = $this;
6482
-        } else {
6483
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6484
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6485
-            } else {
6486
-                $last_model_in_chain = $this->model_chain_to_password;
6487
-            }
6488
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6489
-        }
6490
-
6491
-        $password_field = $model_with_password->getPasswordField();
6492
-        if ($password_field instanceof EE_Password_Field) {
6493
-            $password_field_name = $password_field->get_name();
6494
-        } else {
6495
-            throw new ModelConfigurationException(
6496
-                $this,
6497
-                sprintf(
6498
-                    esc_html_x(
6499
-                        '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"',
6500
-                        '1: model name, 2: special string',
6501
-                        'event_espresso'
6502
-                    ),
6503
-                    $model_with_password->get_this_model_name(),
6504
-                    $this->model_chain_to_password
6505
-                )
6506
-            );
6507
-        }
6508
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6509
-    }
6510
-
6511
-    /**
6512
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6513
-     * or if this model itself has a password affecting access to some of its other fields.
6514
-     * @since 4.9.74.p
6515
-     * @return boolean
6516
-     */
6517
-    public function restrictedByRelatedModelPassword()
6518
-    {
6519
-        return $this->model_chain_to_password !== null;
6520
-    }
3817
+		}
3818
+		return $null_friendly_where_conditions;
3819
+	}
3820
+
3821
+
3822
+
3823
+	/**
3824
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3825
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3826
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3828
+	 *
3829
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
+	 */
3832
+	private function _get_default_where_conditions($model_relation_path = null)
3833
+	{
3834
+		if ($this->_ignore_where_strategy) {
3835
+			return array();
3836
+		}
3837
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
+	}
3839
+
3840
+
3841
+
3842
+	/**
3843
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3847
+	 * Similar to _get_default_where_conditions
3848
+	 *
3849
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
+	 */
3852
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3853
+	{
3854
+		if ($this->_ignore_where_strategy) {
3855
+			return array();
3856
+		}
3857
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
+	}
3859
+
3860
+
3861
+
3862
+	/**
3863
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
+	 *
3866
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3867
+	 * @return string
3868
+	 * @throws EE_Error
3869
+	 */
3870
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
+	{
3872
+		$selects = $this->_get_columns_to_select_for_this_model();
3873
+		foreach (
3874
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3875
+		) {
3876
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3877
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3878
+			foreach ($other_model_selects as $key => $value) {
3879
+				$selects[] = $value;
3880
+			}
3881
+		}
3882
+		return implode(", ", $selects);
3883
+	}
3884
+
3885
+
3886
+
3887
+	/**
3888
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3889
+	 * So that's going to be the columns for all the fields on the model
3890
+	 *
3891
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3892
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3893
+	 */
3894
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3895
+	{
3896
+		$fields = $this->field_settings();
3897
+		$selects = array();
3898
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3899
+			$model_relation_chain,
3900
+			$this->get_this_model_name()
3901
+		);
3902
+		foreach ($fields as $field_obj) {
3903
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3904
+						 . $field_obj->get_table_alias()
3905
+						 . "."
3906
+						 . $field_obj->get_table_column()
3907
+						 . " AS '"
3908
+						 . $table_alias_with_model_relation_chain_prefix
3909
+						 . $field_obj->get_table_alias()
3910
+						 . "."
3911
+						 . $field_obj->get_table_column()
3912
+						 . "'";
3913
+		}
3914
+		// make sure we are also getting the PKs of each table
3915
+		$tables = $this->get_tables();
3916
+		if (count($tables) > 1) {
3917
+			foreach ($tables as $table_obj) {
3918
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919
+									   . $table_obj->get_fully_qualified_pk_column();
3920
+				if (! in_array($qualified_pk_column, $selects)) {
3921
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922
+				}
3923
+			}
3924
+		}
3925
+		return $selects;
3926
+	}
3927
+
3928
+
3929
+
3930
+	/**
3931
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3932
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3933
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3934
+	 * SQL for joining, and the data types
3935
+	 *
3936
+	 * @param null|string                 $original_query_param
3937
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3938
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3939
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3940
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3941
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3942
+	 *                                                          or 'Registration's
3943
+	 * @param string                      $original_query_param what it originally was (eg
3944
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3945
+	 *                                                          matches $query_param
3946
+	 * @throws EE_Error
3947
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3948
+	 */
3949
+	private function _extract_related_model_info_from_query_param(
3950
+		$query_param,
3951
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3952
+		$query_param_type,
3953
+		$original_query_param = null
3954
+	) {
3955
+		if ($original_query_param === null) {
3956
+			$original_query_param = $query_param;
3957
+		}
3958
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3959
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3960
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3961
+		$allow_fields = in_array(
3962
+			$query_param_type,
3963
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3964
+			true
3965
+		);
3966
+		// check to see if we have a field on this model
3967
+		$this_model_fields = $this->field_settings(true);
3968
+		if (array_key_exists($query_param, $this_model_fields)) {
3969
+			if ($allow_fields) {
3970
+				return;
3971
+			}
3972
+			throw new EE_Error(
3973
+				sprintf(
3974
+					esc_html__(
3975
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3976
+						"event_espresso"
3977
+					),
3978
+					$query_param,
3979
+					get_class($this),
3980
+					$query_param_type,
3981
+					$original_query_param
3982
+				)
3983
+			);
3984
+		}
3985
+		// check if this is a special logic query param
3986
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3987
+			if ($allow_logic_query_params) {
3988
+				return;
3989
+			}
3990
+			throw new EE_Error(
3991
+				sprintf(
3992
+					esc_html__(
3993
+						'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',
3994
+						'event_espresso'
3995
+					),
3996
+					implode('", "', $this->_logic_query_param_keys),
3997
+					$query_param,
3998
+					get_class($this),
3999
+					'<br />',
4000
+					"\t"
4001
+					. ' $passed_in_query_info = <pre>'
4002
+					. print_r($passed_in_query_info, true)
4003
+					. '</pre>'
4004
+					. "\n\t"
4005
+					. ' $query_param_type = '
4006
+					. $query_param_type
4007
+					. "\n\t"
4008
+					. ' $original_query_param = '
4009
+					. $original_query_param
4010
+				)
4011
+			);
4012
+		}
4013
+		// check if it's a custom selection
4014
+		if (
4015
+			$this->_custom_selections instanceof CustomSelects
4016
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4017
+		) {
4018
+			return;
4019
+		}
4020
+		// check if has a model name at the beginning
4021
+		// and
4022
+		// check if it's a field on a related model
4023
+		if (
4024
+			$this->extractJoinModelFromQueryParams(
4025
+				$passed_in_query_info,
4026
+				$query_param,
4027
+				$original_query_param,
4028
+				$query_param_type
4029
+			)
4030
+		) {
4031
+			return;
4032
+		}
4033
+
4034
+		// ok so $query_param didn't start with a model name
4035
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4036
+		// it's wack, that's what it is
4037
+		throw new EE_Error(
4038
+			sprintf(
4039
+				esc_html__(
4040
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4041
+					"event_espresso"
4042
+				),
4043
+				$query_param,
4044
+				get_class($this),
4045
+				$query_param_type,
4046
+				$original_query_param
4047
+			)
4048
+		);
4049
+	}
4050
+
4051
+
4052
+	/**
4053
+	 * Extracts any possible join model information from the provided possible_join_string.
4054
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4055
+	 * parts that should be added to the query.
4056
+	 *
4057
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4058
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4059
+	 * @param null|string                 $original_query_param
4060
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4061
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4062
+	 * @return bool  returns true if a join was added and false if not.
4063
+	 * @throws EE_Error
4064
+	 */
4065
+	private function extractJoinModelFromQueryParams(
4066
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4067
+		$possible_join_string,
4068
+		$original_query_param,
4069
+		$query_parameter_type
4070
+	) {
4071
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4073
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4075
+				if ($possible_join_string === '') {
4076
+					// nothing left to $query_param
4077
+					// we should actually end in a field name, not a model like this!
4078
+					throw new EE_Error(
4079
+						sprintf(
4080
+							esc_html__(
4081
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4082
+								"event_espresso"
4083
+							),
4084
+							$possible_join_string,
4085
+							$query_parameter_type,
4086
+							get_class($this),
4087
+							$valid_related_model_name
4088
+						)
4089
+					);
4090
+				}
4091
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4092
+				$related_model_obj->_extract_related_model_info_from_query_param(
4093
+					$possible_join_string,
4094
+					$query_info_carrier,
4095
+					$query_parameter_type,
4096
+					$original_query_param
4097
+				);
4098
+				return true;
4099
+			}
4100
+			if ($possible_join_string === $valid_related_model_name) {
4101
+				$this->_add_join_to_model(
4102
+					$valid_related_model_name,
4103
+					$query_info_carrier,
4104
+					$original_query_param
4105
+				);
4106
+				return true;
4107
+			}
4108
+		}
4109
+		return false;
4110
+	}
4111
+
4112
+
4113
+	/**
4114
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4115
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4116
+	 * @throws EE_Error
4117
+	 */
4118
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4119
+	{
4120
+		if (
4121
+			$this->_custom_selections instanceof CustomSelects
4122
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4123
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4124
+			)
4125
+		) {
4126
+			$original_selects = $this->_custom_selections->originalSelects();
4127
+			foreach ($original_selects as $alias => $select_configuration) {
4128
+				$this->extractJoinModelFromQueryParams(
4129
+					$query_info_carrier,
4130
+					$select_configuration[0],
4131
+					$select_configuration[0],
4132
+					'custom_selects'
4133
+				);
4134
+			}
4135
+		}
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4142
+	 * and store it on $passed_in_query_info
4143
+	 *
4144
+	 * @param string                      $model_name
4145
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4146
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4147
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4148
+	 *                                                          and are adding a join to 'Payment' with the original
4149
+	 *                                                          query param key
4150
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4151
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4152
+	 *                                                          Payment wants to add default query params so that it
4153
+	 *                                                          will know what models to prepend onto its default query
4154
+	 *                                                          params or in case it wants to rename tables (in case
4155
+	 *                                                          there are multiple joins to the same table)
4156
+	 * @return void
4157
+	 * @throws EE_Error
4158
+	 */
4159
+	private function _add_join_to_model(
4160
+		$model_name,
4161
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4162
+		$original_query_param
4163
+	) {
4164
+		$relation_obj = $this->related_settings_for($model_name);
4165
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4166
+		// check if the relation is HABTM, because then we're essentially doing two joins
4167
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4168
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4169
+			$join_model_obj = $relation_obj->get_join_model();
4170
+			// replace the model specified with the join model for this relation chain, whi
4171
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4172
+				$model_name,
4173
+				$join_model_obj->get_this_model_name(),
4174
+				$model_relation_chain
4175
+			);
4176
+			$passed_in_query_info->merge(
4177
+				new EE_Model_Query_Info_Carrier(
4178
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4179
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4180
+				)
4181
+			);
4182
+		}
4183
+		// now just join to the other table pointed to by the relation object, and add its data types
4184
+		$passed_in_query_info->merge(
4185
+			new EE_Model_Query_Info_Carrier(
4186
+				array($model_relation_chain => $model_name),
4187
+				$relation_obj->get_join_statement($model_relation_chain)
4188
+			)
4189
+		);
4190
+	}
4191
+
4192
+
4193
+
4194
+	/**
4195
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4196
+	 *
4197
+	 * @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
4198
+	 * @return string of SQL
4199
+	 * @throws EE_Error
4200
+	 */
4201
+	private function _construct_where_clause($where_params)
4202
+	{
4203
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204
+		if ($SQL) {
4205
+			return " WHERE " . $SQL;
4206
+		}
4207
+		return '';
4208
+	}
4209
+
4210
+
4211
+
4212
+	/**
4213
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4214
+	 * and should be passed HAVING parameters, not WHERE parameters
4215
+	 *
4216
+	 * @param array $having_params
4217
+	 * @return string
4218
+	 * @throws EE_Error
4219
+	 */
4220
+	private function _construct_having_clause($having_params)
4221
+	{
4222
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223
+		if ($SQL) {
4224
+			return " HAVING " . $SQL;
4225
+		}
4226
+		return '';
4227
+	}
4228
+
4229
+
4230
+	/**
4231
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4232
+	 * Event_Meta.meta_value = 'foo'))"
4233
+	 *
4234
+	 * @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
4235
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4236
+	 * @throws EE_Error
4237
+	 * @return string of SQL
4238
+	 */
4239
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4240
+	{
4241
+		$where_clauses = array();
4242
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4244
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4245
+				switch ($query_param) {
4246
+					case 'not':
4247
+					case 'NOT':
4248
+						$where_clauses[] = "! ("
4249
+										   . $this->_construct_condition_clause_recursive(
4250
+											   $op_and_value_or_sub_condition,
4251
+											   $glue
4252
+										   )
4253
+										   . ")";
4254
+						break;
4255
+					case 'and':
4256
+					case 'AND':
4257
+						$where_clauses[] = " ("
4258
+										   . $this->_construct_condition_clause_recursive(
4259
+											   $op_and_value_or_sub_condition,
4260
+											   ' AND '
4261
+										   )
4262
+										   . ")";
4263
+						break;
4264
+					case 'or':
4265
+					case 'OR':
4266
+						$where_clauses[] = " ("
4267
+										   . $this->_construct_condition_clause_recursive(
4268
+											   $op_and_value_or_sub_condition,
4269
+											   ' OR '
4270
+										   )
4271
+										   . ")";
4272
+						break;
4273
+				}
4274
+			} else {
4275
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4276
+				// if it's not a normal field, maybe it's a custom selection?
4277
+				if (! $field_obj) {
4278
+					if ($this->_custom_selections instanceof CustomSelects) {
4279
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280
+					} else {
4281
+						throw new EE_Error(sprintf(esc_html__(
4282
+							"%s is neither a valid model field name, nor a custom selection",
4283
+							"event_espresso"
4284
+						), $query_param));
4285
+					}
4286
+				}
4287
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4289
+			}
4290
+		}
4291
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4292
+	}
4293
+
4294
+
4295
+
4296
+	/**
4297
+	 * Takes the input parameter and extract the table name (alias) and column name
4298
+	 *
4299
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4300
+	 * @throws EE_Error
4301
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4302
+	 */
4303
+	private function _deduce_column_name_from_query_param($query_param)
4304
+	{
4305
+		$field = $this->_deduce_field_from_query_param($query_param);
4306
+		if ($field) {
4307
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4308
+				$field->get_model_name(),
4309
+				$query_param
4310
+			);
4311
+			return $table_alias_prefix . $field->get_qualified_column();
4312
+		}
4313
+		if (
4314
+			$this->_custom_selections instanceof CustomSelects
4315
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4316
+		) {
4317
+			// maybe it's custom selection item?
4318
+			// if so, just use it as the "column name"
4319
+			return $query_param;
4320
+		}
4321
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4322
+			? implode(',', $this->_custom_selections->columnAliases())
4323
+			: '';
4324
+		throw new EE_Error(
4325
+			sprintf(
4326
+				esc_html__(
4327
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4328
+					"event_espresso"
4329
+				),
4330
+				$query_param,
4331
+				$custom_select_aliases
4332
+			)
4333
+		);
4334
+	}
4335
+
4336
+
4337
+
4338
+	/**
4339
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4340
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4341
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4342
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4343
+	 *
4344
+	 * @param string $condition_query_param_key
4345
+	 * @return string
4346
+	 */
4347
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4348
+	{
4349
+		$pos_of_star = strpos($condition_query_param_key, '*');
4350
+		if ($pos_of_star === false) {
4351
+			return $condition_query_param_key;
4352
+		}
4353
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4354
+		return $condition_query_param_sans_star;
4355
+	}
4356
+
4357
+
4358
+
4359
+	/**
4360
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4361
+	 *
4362
+	 * @param                            mixed      array | string    $op_and_value
4363
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4364
+	 * @throws EE_Error
4365
+	 * @return string
4366
+	 */
4367
+	private function _construct_op_and_value($op_and_value, $field_obj)
4368
+	{
4369
+		if (is_array($op_and_value)) {
4370
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
+			if (! $operator) {
4372
+				$php_array_like_string = array();
4373
+				foreach ($op_and_value as $key => $value) {
4374
+					$php_array_like_string[] = "$key=>$value";
4375
+				}
4376
+				throw new EE_Error(
4377
+					sprintf(
4378
+						esc_html__(
4379
+							"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))",
4380
+							"event_espresso"
4381
+						),
4382
+						implode(",", $php_array_like_string)
4383
+					)
4384
+				);
4385
+			}
4386
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4387
+		} else {
4388
+			$operator = '=';
4389
+			$value = $op_and_value;
4390
+		}
4391
+		// check to see if the value is actually another field
4392
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4394
+		}
4395
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396
+			// in this case, the value should be an array, or at least a comma-separated list
4397
+			// it will need to handle a little differently
4398
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4399
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4400
+			return $operator . SP . $cleaned_value;
4401
+		}
4402
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403
+			// the value should be an array with count of two.
4404
+			if (count($value) !== 2) {
4405
+				throw new EE_Error(
4406
+					sprintf(
4407
+						esc_html__(
4408
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4409
+							'event_espresso'
4410
+						),
4411
+						"BETWEEN"
4412
+					)
4413
+				);
4414
+			}
4415
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
+			return $operator . SP . $cleaned_value;
4417
+		}
4418
+		if (in_array($operator, $this->valid_null_style_operators())) {
4419
+			if ($value !== null) {
4420
+				throw new EE_Error(
4421
+					sprintf(
4422
+						esc_html__(
4423
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4424
+							"event_espresso"
4425
+						),
4426
+						$value,
4427
+						$operator
4428
+					)
4429
+				);
4430
+			}
4431
+			return $operator;
4432
+		}
4433
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4435
+			// remove other junk. So just treat it as a string.
4436
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4437
+		}
4438
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4440
+		}
4441
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442
+			throw new EE_Error(
4443
+				sprintf(
4444
+					esc_html__(
4445
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4446
+						'event_espresso'
4447
+					),
4448
+					$operator,
4449
+					$operator
4450
+				)
4451
+			);
4452
+		}
4453
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454
+			throw new EE_Error(
4455
+				sprintf(
4456
+					esc_html__(
4457
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4458
+						'event_espresso'
4459
+					),
4460
+					$operator,
4461
+					$operator
4462
+				)
4463
+			);
4464
+		}
4465
+		throw new EE_Error(
4466
+			sprintf(
4467
+				esc_html__(
4468
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4469
+					"event_espresso"
4470
+				),
4471
+				http_build_query($op_and_value)
4472
+			)
4473
+		);
4474
+	}
4475
+
4476
+
4477
+
4478
+	/**
4479
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4480
+	 *
4481
+	 * @param array                      $values
4482
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4483
+	 *                                              '%s'
4484
+	 * @return string
4485
+	 * @throws EE_Error
4486
+	 */
4487
+	public function _construct_between_value($values, $field_obj)
4488
+	{
4489
+		$cleaned_values = array();
4490
+		foreach ($values as $value) {
4491
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492
+		}
4493
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4494
+	}
4495
+
4496
+
4497
+	/**
4498
+	 * Takes an array or a comma-separated list of $values and cleans them
4499
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4500
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4501
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4502
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4503
+	 *
4504
+	 * @param mixed                      $values    array or comma-separated string
4505
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4506
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4507
+	 * @throws EE_Error
4508
+	 */
4509
+	public function _construct_in_value($values, $field_obj)
4510
+	{
4511
+		$prepped = [];
4512
+		// check if the value is a CSV list
4513
+		if (is_string($values)) {
4514
+			// in which case, turn it into an array
4515
+			$values = explode(',', $values);
4516
+		}
4517
+		// make sure we only have one of each value in the list
4518
+		$values = array_unique($values);
4519
+		foreach ($values as $value) {
4520
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4521
+		}
4522
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4523
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4524
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525
+		if (empty($prepped)) {
4526
+			$all_fields = $this->field_settings();
4527
+			$first_field    = reset($all_fields);
4528
+			$main_table = $this->_get_main_table();
4529
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530
+		}
4531
+		return '(' . implode(',', $prepped) . ')';
4532
+	}
4533
+
4534
+
4535
+
4536
+	/**
4537
+	 * @param mixed                      $value
4538
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
+	 * @throws EE_Error
4540
+	 * @return false|null|string
4541
+	 */
4542
+	private function _wpdb_prepare_using_field($value, $field_obj)
4543
+	{
4544
+		/** @type WPDB $wpdb */
4545
+		global $wpdb;
4546
+		if ($field_obj instanceof EE_Model_Field_Base) {
4547
+			return $wpdb->prepare(
4548
+				$field_obj->get_wpdb_data_type(),
4549
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4550
+			);
4551
+		} //$field_obj should really just be a data type
4552
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
+			throw new EE_Error(
4554
+				sprintf(
4555
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
+					$field_obj,
4557
+					implode(",", $this->_valid_wpdb_data_types)
4558
+				)
4559
+			);
4560
+		}
4561
+		return $wpdb->prepare($field_obj, $value);
4562
+	}
4563
+
4564
+
4565
+
4566
+	/**
4567
+	 * Takes the input parameter and finds the model field that it indicates.
4568
+	 *
4569
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
+	 * @throws EE_Error
4571
+	 * @return EE_Model_Field_Base
4572
+	 */
4573
+	protected function _deduce_field_from_query_param($query_param_name)
4574
+	{
4575
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
+		// which will help us find the database table and column
4577
+		$query_param_parts = explode(".", $query_param_name);
4578
+		if (empty($query_param_parts)) {
4579
+			throw new EE_Error(sprintf(esc_html__(
4580
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4581
+				'event_espresso'
4582
+			), $query_param_name));
4583
+		}
4584
+		$number_of_parts = count($query_param_parts);
4585
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
+		if ($number_of_parts === 1) {
4587
+			$field_name = $last_query_param_part;
4588
+			$model_obj = $this;
4589
+		} else {// $number_of_parts >= 2
4590
+			// the last part is the column name, and there are only 2parts. therefore...
4591
+			$field_name = $last_query_param_part;
4592
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
+		}
4594
+		try {
4595
+			return $model_obj->field_settings_for($field_name);
4596
+		} catch (EE_Error $e) {
4597
+			return null;
4598
+		}
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
+	 * alias and column which corresponds to it
4606
+	 *
4607
+	 * @param string $field_name
4608
+	 * @throws EE_Error
4609
+	 * @return string
4610
+	 */
4611
+	public function _get_qualified_column_for_field($field_name)
4612
+	{
4613
+		$all_fields = $this->field_settings();
4614
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
+		if ($field) {
4616
+			return $field->get_qualified_column();
4617
+		}
4618
+		throw new EE_Error(
4619
+			sprintf(
4620
+				esc_html__(
4621
+					"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.",
4622
+					'event_espresso'
4623
+				),
4624
+				$field_name,
4625
+				get_class($this)
4626
+			)
4627
+		);
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
+	 * Example usage:
4635
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4636
+	 *      array(),
4637
+	 *      ARRAY_A,
4638
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
+	 *  );
4640
+	 * is equivalent to
4641
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
+	 * and
4643
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4644
+	 *      array(
4645
+	 *          array(
4646
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
+	 *          ),
4648
+	 *          ARRAY_A,
4649
+	 *          implode(
4650
+	 *              ', ',
4651
+	 *              array_merge(
4652
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
+	 *              )
4655
+	 *          )
4656
+	 *      )
4657
+	 *  );
4658
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
+	 *
4660
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
+	 *                                            and the one whose fields you are selecting for example: when querying
4662
+	 *                                            tickets model and selecting fields from the tickets model you would
4663
+	 *                                            leave this parameter empty, because no models are needed to join
4664
+	 *                                            between the queried model and the selected one. Likewise when
4665
+	 *                                            querying the datetime model and selecting fields from the tickets
4666
+	 *                                            model, it would also be left empty, because there is a direct
4667
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4668
+	 *                                            them together. However, when querying from the event model and
4669
+	 *                                            selecting fields from the ticket model, you should provide the string
4670
+	 *                                            'Datetime', indicating that the event model must first join to the
4671
+	 *                                            datetime model in order to find its relation to ticket model.
4672
+	 *                                            Also, when querying from the venue model and selecting fields from
4673
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
+	 *                                            indicating you need to join the venue model to the event model,
4675
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4676
+	 *                                            This string is used to deduce the prefix that gets added onto the
4677
+	 *                                            models' tables qualified columns
4678
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4680
+	 *                                            qualified column names
4681
+	 * @return array|string
4682
+	 */
4683
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
+	{
4685
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
+		$qualified_columns = array();
4687
+		foreach ($this->field_settings() as $field_name => $field) {
4688
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
+		}
4690
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
+	}
4692
+
4693
+
4694
+
4695
+	/**
4696
+	 * constructs the select use on special limit joins
4697
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
+	 * (as that is typically where the limits would be set).
4700
+	 *
4701
+	 * @param  string       $table_alias The table the select is being built for
4702
+	 * @param  mixed|string $limit       The limit for this select
4703
+	 * @return string                The final select join element for the query.
4704
+	 */
4705
+	public function _construct_limit_join_select($table_alias, $limit)
4706
+	{
4707
+		$SQL = '';
4708
+		foreach ($this->_tables as $table_obj) {
4709
+			if ($table_obj instanceof EE_Primary_Table) {
4710
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4711
+					? $table_obj->get_select_join_limit($limit)
4712
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4714
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4715
+					? $table_obj->get_select_join_limit_join($limit)
4716
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4717
+			}
4718
+		}
4719
+		return $SQL;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
+	 *
4728
+	 * @return string SQL
4729
+	 * @throws EE_Error
4730
+	 */
4731
+	public function _construct_internal_join()
4732
+	{
4733
+		$SQL = $this->_get_main_table()->get_table_sql();
4734
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
+		return $SQL;
4736
+	}
4737
+
4738
+
4739
+
4740
+	/**
4741
+	 * Constructs the SQL for joining all the tables on this model.
4742
+	 * Normally $alias should be the primary table's alias, but in cases where
4743
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
+	 * alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4748
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
+	 *
4750
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
+	 * @return string
4752
+	 */
4753
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
+	{
4755
+		$SQL = '';
4756
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
+		foreach ($this->_tables as $table_obj) {
4758
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
+					// so we're joining to this table, meaning the table is already in
4761
+					// the FROM statement, BUT the primary table isn't. So we want
4762
+					// to add the inverse join sql
4763
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
+				} else {
4765
+					// just add a regular JOIN to this table from the primary table
4766
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
+				}
4768
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
+		}
4770
+		return $SQL;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
+	 * their data type (eg, '%s', '%d', etc)
4779
+	 *
4780
+	 * @return array
4781
+	 */
4782
+	public function _get_data_types()
4783
+	{
4784
+		$data_types = array();
4785
+		foreach ($this->field_settings() as $field_obj) {
4786
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
+			/** @var $field_obj EE_Model_Field_Base */
4788
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
+		}
4790
+		return $data_types;
4791
+	}
4792
+
4793
+
4794
+
4795
+	/**
4796
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
+	 *
4798
+	 * @param string $model_name
4799
+	 * @throws EE_Error
4800
+	 * @return EEM_Base
4801
+	 */
4802
+	public function get_related_model_obj($model_name)
4803
+	{
4804
+		$model_classname = "EEM_" . $model_name;
4805
+		if (! class_exists($model_classname)) {
4806
+			throw new EE_Error(sprintf(esc_html__(
4807
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
+				'event_espresso'
4809
+			), $model_name, $model_classname));
4810
+		}
4811
+		return call_user_func($model_classname . "::instance");
4812
+	}
4813
+
4814
+
4815
+
4816
+	/**
4817
+	 * Returns the array of EE_ModelRelations for this model.
4818
+	 *
4819
+	 * @return EE_Model_Relation_Base[]
4820
+	 */
4821
+	public function relation_settings()
4822
+	{
4823
+		return $this->_model_relations;
4824
+	}
4825
+
4826
+
4827
+
4828
+	/**
4829
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
+	 * because without THOSE models, this model probably doesn't have much purpose.
4831
+	 * (Eg, without an event, datetimes have little purpose.)
4832
+	 *
4833
+	 * @return EE_Belongs_To_Relation[]
4834
+	 */
4835
+	public function belongs_to_relations()
4836
+	{
4837
+		$belongs_to_relations = array();
4838
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4841
+			}
4842
+		}
4843
+		return $belongs_to_relations;
4844
+	}
4845
+
4846
+
4847
+
4848
+	/**
4849
+	 * Returns the specified EE_Model_Relation, or throws an exception
4850
+	 *
4851
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4852
+	 * @throws EE_Error
4853
+	 * @return EE_Model_Relation_Base
4854
+	 */
4855
+	public function related_settings_for($relation_name)
4856
+	{
4857
+		$relatedModels = $this->relation_settings();
4858
+		if (! array_key_exists($relation_name, $relatedModels)) {
4859
+			throw new EE_Error(
4860
+				sprintf(
4861
+					esc_html__(
4862
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
+						'event_espresso'
4864
+					),
4865
+					$relation_name,
4866
+					$this->_get_class_name(),
4867
+					implode(', ', array_keys($relatedModels))
4868
+				)
4869
+			);
4870
+		}
4871
+		return $relatedModels[ $relation_name ];
4872
+	}
4873
+
4874
+
4875
+
4876
+	/**
4877
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
+	 * fields
4879
+	 *
4880
+	 * @param string $fieldName
4881
+	 * @param boolean $include_db_only_fields
4882
+	 * @throws EE_Error
4883
+	 * @return EE_Model_Field_Base
4884
+	 */
4885
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
+	{
4887
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4888
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4889
+			throw new EE_Error(sprintf(
4890
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
+				$fieldName,
4892
+				get_class($this)
4893
+			));
4894
+		}
4895
+		return $fieldSettings[ $fieldName ];
4896
+	}
4897
+
4898
+
4899
+
4900
+	/**
4901
+	 * Checks if this field exists on this model
4902
+	 *
4903
+	 * @param string $fieldName a key in the model's _field_settings array
4904
+	 * @return boolean
4905
+	 */
4906
+	public function has_field($fieldName)
4907
+	{
4908
+		$fieldSettings = $this->field_settings(true);
4909
+		if (isset($fieldSettings[ $fieldName ])) {
4910
+			return true;
4911
+		}
4912
+		return false;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Returns whether or not this model has a relation to the specified model
4919
+	 *
4920
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4921
+	 * @return boolean
4922
+	 */
4923
+	public function has_relation($relation_name)
4924
+	{
4925
+		$relations = $this->relation_settings();
4926
+		if (isset($relations[ $relation_name ])) {
4927
+			return true;
4928
+		}
4929
+		return false;
4930
+	}
4931
+
4932
+
4933
+
4934
+	/**
4935
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
+	 * Eg, on EE_Answer that would be ANS_ID field object
4937
+	 *
4938
+	 * @param $field_obj
4939
+	 * @return boolean
4940
+	 */
4941
+	public function is_primary_key_field($field_obj)
4942
+	{
4943
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
+	}
4945
+
4946
+
4947
+
4948
+	/**
4949
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
+	 * Eg, on EE_Answer that would be ANS_ID field object
4951
+	 *
4952
+	 * @return EE_Model_Field_Base
4953
+	 * @throws EE_Error
4954
+	 */
4955
+	public function get_primary_key_field()
4956
+	{
4957
+		if ($this->_primary_key_field === null) {
4958
+			foreach ($this->field_settings(true) as $field_obj) {
4959
+				if ($this->is_primary_key_field($field_obj)) {
4960
+					$this->_primary_key_field = $field_obj;
4961
+					break;
4962
+				}
4963
+			}
4964
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
+				throw new EE_Error(sprintf(
4966
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967
+					get_class($this)
4968
+				));
4969
+			}
4970
+		}
4971
+		return $this->_primary_key_field;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * Returns whether or not not there is a primary key on this model.
4978
+	 * Internally does some caching.
4979
+	 *
4980
+	 * @return boolean
4981
+	 */
4982
+	public function has_primary_key_field()
4983
+	{
4984
+		if ($this->_has_primary_key_field === null) {
4985
+			try {
4986
+				$this->get_primary_key_field();
4987
+				$this->_has_primary_key_field = true;
4988
+			} catch (EE_Error $e) {
4989
+				$this->_has_primary_key_field = false;
4990
+			}
4991
+		}
4992
+		return $this->_has_primary_key_field;
4993
+	}
4994
+
4995
+
4996
+
4997
+	/**
4998
+	 * Finds the first field of type $field_class_name.
4999
+	 *
5000
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
+	 *                                 EE_Foreign_Key_Field, etc
5002
+	 * @return EE_Model_Field_Base or null if none is found
5003
+	 */
5004
+	public function get_a_field_of_type($field_class_name)
5005
+	{
5006
+		foreach ($this->field_settings() as $field) {
5007
+			if ($field instanceof $field_class_name) {
5008
+				return $field;
5009
+			}
5010
+		}
5011
+		return null;
5012
+	}
5013
+
5014
+
5015
+
5016
+	/**
5017
+	 * Gets a foreign key field pointing to model.
5018
+	 *
5019
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5020
+	 * @return EE_Foreign_Key_Field_Base
5021
+	 * @throws EE_Error
5022
+	 */
5023
+	public function get_foreign_key_to($model_name)
5024
+	{
5025
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
+			foreach ($this->field_settings() as $field) {
5027
+				if (
5028
+					$field instanceof EE_Foreign_Key_Field_Base
5029
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5030
+				) {
5031
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
+					break;
5033
+				}
5034
+			}
5035
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
+				throw new EE_Error(sprintf(esc_html__(
5037
+					"There is no foreign key field pointing to model %s on model %s",
5038
+					'event_espresso'
5039
+				), $model_name, get_class($this)));
5040
+			}
5041
+		}
5042
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
+	}
5044
+
5045
+
5046
+
5047
+	/**
5048
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5049
+	 *
5050
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
+	 *                            Either one works
5053
+	 * @return string
5054
+	 */
5055
+	public function get_table_for_alias($table_alias)
5056
+	{
5057
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
+	}
5060
+
5061
+
5062
+
5063
+	/**
5064
+	 * Returns a flat array of all field son this model, instead of organizing them
5065
+	 * by table_alias as they are in the constructor.
5066
+	 *
5067
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5069
+	 */
5070
+	public function field_settings($include_db_only_fields = false)
5071
+	{
5072
+		if ($include_db_only_fields) {
5073
+			if ($this->_cached_fields === null) {
5074
+				$this->_cached_fields = array();
5075
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5076
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
+						$this->_cached_fields[ $field_name ] = $field_obj;
5078
+					}
5079
+				}
5080
+			}
5081
+			return $this->_cached_fields;
5082
+		}
5083
+		if ($this->_cached_fields_non_db_only === null) {
5084
+			$this->_cached_fields_non_db_only = array();
5085
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5086
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
+					/** @var $field_obj EE_Model_Field_Base */
5088
+					if (! $field_obj->is_db_only_field()) {
5089
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
+					}
5091
+				}
5092
+			}
5093
+		}
5094
+		return $this->_cached_fields_non_db_only;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 *        cycle though array of attendees and create objects out of each item
5101
+	 *
5102
+	 * @access        private
5103
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
+	 *                           numerically indexed)
5106
+	 * @throws EE_Error
5107
+	 */
5108
+	protected function _create_objects($rows = array())
5109
+	{
5110
+		$array_of_objects = array();
5111
+		if (empty($rows)) {
5112
+			return array();
5113
+		}
5114
+		$count_if_model_has_no_primary_key = 0;
5115
+		$has_primary_key = $this->has_primary_key_field();
5116
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
+		foreach ((array) $rows as $row) {
5118
+			if (empty($row)) {
5119
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
+				return array();
5121
+			}
5122
+			// check if we've already set this object in the results array,
5123
+			// in which case there's no need to process it further (again)
5124
+			if ($has_primary_key) {
5125
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
+					$row,
5127
+					$primary_key_field->get_qualified_column(),
5128
+					$primary_key_field->get_table_column()
5129
+				);
5130
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
+					continue;
5132
+				}
5133
+			}
5134
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5135
+			if (! $classInstance) {
5136
+				throw new EE_Error(
5137
+					sprintf(
5138
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5139
+						$this->get_this_model_name(),
5140
+						http_build_query($row)
5141
+					)
5142
+				);
5143
+			}
5144
+			// set the timezone on the instantiated objects
5145
+			$classInstance->set_timezone($this->_timezone);
5146
+			// make sure if there is any timezone setting present that we set the timezone for the object
5147
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
+			$array_of_objects[ $key ] = $classInstance;
5149
+			// also, for all the relations of type BelongsTo, see if we can cache
5150
+			// those related models
5151
+			// (we could do this for other relations too, but if there are conditions
5152
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5153
+			// so it requires a little more thought than just caching them immediately...)
5154
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
+					// check if this model's INFO is present. If so, cache it on the model
5157
+					$other_model = $relation_obj->get_other_model();
5158
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
+					// if we managed to make a model object from the results, cache it on the main model object
5160
+					if ($other_model_obj_maybe) {
5161
+						// set timezone on these other model objects if they are present
5162
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5163
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5164
+					}
5165
+				}
5166
+			}
5167
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
+			// the field in the CustomSelects object
5170
+			if ($this->_custom_selections instanceof CustomSelects) {
5171
+				$classInstance->setCustomSelectsValues(
5172
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5173
+				);
5174
+			}
5175
+		}
5176
+		return $array_of_objects;
5177
+	}
5178
+
5179
+
5180
+	/**
5181
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
+	 *
5184
+	 * @param array $db_results_row
5185
+	 * @return array
5186
+	 */
5187
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
+	{
5189
+		$results = array();
5190
+		if ($this->_custom_selections instanceof CustomSelects) {
5191
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
+				if (isset($db_results_row[ $alias ])) {
5193
+					$results[ $alias ] = $this->convertValueToDataType(
5194
+						$db_results_row[ $alias ],
5195
+						$this->_custom_selections->getDataTypeForAlias($alias)
5196
+					);
5197
+				}
5198
+			}
5199
+		}
5200
+		return $results;
5201
+	}
5202
+
5203
+
5204
+	/**
5205
+	 * This will set the value for the given alias
5206
+	 * @param string $value
5207
+	 * @param string $datatype (one of %d, %s, %f)
5208
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5209
+	 */
5210
+	protected function convertValueToDataType($value, $datatype)
5211
+	{
5212
+		switch ($datatype) {
5213
+			case '%f':
5214
+				return (float) $value;
5215
+			case '%d':
5216
+				return (int) $value;
5217
+			default:
5218
+				return (string) $value;
5219
+		}
5220
+	}
5221
+
5222
+
5223
+	/**
5224
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
+	 * object (as set in the model_field!).
5228
+	 *
5229
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
+	 */
5231
+	public function create_default_object()
5232
+	{
5233
+		$this_model_fields_and_values = array();
5234
+		// setup the row using default values;
5235
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5236
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
+		}
5238
+		$className = $this->_get_class_name();
5239
+		$classInstance = EE_Registry::instance()
5240
+									->load_class($className, array($this_model_fields_and_values), false, false);
5241
+		return $classInstance;
5242
+	}
5243
+
5244
+
5245
+
5246
+	/**
5247
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
+	 *                             or an stdClass where each property is the name of a column,
5249
+	 * @return EE_Base_Class
5250
+	 * @throws EE_Error
5251
+	 */
5252
+	public function instantiate_class_from_array_or_object($cols_n_values)
5253
+	{
5254
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
+			$cols_n_values = get_object_vars($cols_n_values);
5256
+		}
5257
+		$primary_key = null;
5258
+		// make sure the array only has keys that are fields/columns on this model
5259
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
+		}
5263
+		$className = $this->_get_class_name();
5264
+		// check we actually found results that we can use to build our model object
5265
+		// if not, return null
5266
+		if ($this->has_primary_key_field()) {
5267
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
+				return null;
5269
+			}
5270
+		} elseif ($this->unique_indexes()) {
5271
+			$first_column = reset($this_model_fields_n_values);
5272
+			if (empty($first_column)) {
5273
+				return null;
5274
+			}
5275
+		}
5276
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
+		if ($primary_key) {
5278
+			$classInstance = $this->get_from_entity_map($primary_key);
5279
+			if (! $classInstance) {
5280
+				$classInstance = EE_Registry::instance()
5281
+											->load_class(
5282
+												$className,
5283
+												array($this_model_fields_n_values, $this->_timezone),
5284
+												true,
5285
+												false
5286
+											);
5287
+				// add this new object to the entity map
5288
+				$classInstance = $this->add_to_entity_map($classInstance);
5289
+			}
5290
+		} else {
5291
+			$classInstance = EE_Registry::instance()
5292
+										->load_class(
5293
+											$className,
5294
+											array($this_model_fields_n_values, $this->_timezone),
5295
+											true,
5296
+											false
5297
+										);
5298
+		}
5299
+		return $classInstance;
5300
+	}
5301
+
5302
+
5303
+
5304
+	/**
5305
+	 * Gets the model object from the  entity map if it exists
5306
+	 *
5307
+	 * @param int|string $id the ID of the model object
5308
+	 * @return EE_Base_Class
5309
+	 */
5310
+	public function get_from_entity_map($id)
5311
+	{
5312
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
+	}
5315
+
5316
+
5317
+
5318
+	/**
5319
+	 * add_to_entity_map
5320
+	 * Adds the object to the model's entity mappings
5321
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
+	 *        then this method should be called immediately after the update query
5326
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5328
+	 *
5329
+	 * @param    EE_Base_Class $object
5330
+	 * @throws EE_Error
5331
+	 * @return \EE_Base_Class
5332
+	 */
5333
+	public function add_to_entity_map(EE_Base_Class $object)
5334
+	{
5335
+		$className = $this->_get_class_name();
5336
+		if (! $object instanceof $className) {
5337
+			throw new EE_Error(sprintf(
5338
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
+				is_object($object) ? get_class($object) : $object,
5340
+				$className
5341
+			));
5342
+		}
5343
+		/** @var $object EE_Base_Class */
5344
+		if (! $object->ID()) {
5345
+			throw new EE_Error(sprintf(esc_html__(
5346
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5347
+				"event_espresso"
5348
+			), get_class($this)));
5349
+		}
5350
+		// double check it's not already there
5351
+		$classInstance = $this->get_from_entity_map($object->ID());
5352
+		if ($classInstance) {
5353
+			return $classInstance;
5354
+		}
5355
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
+		return $object;
5357
+	}
5358
+
5359
+
5360
+
5361
+	/**
5362
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5363
+	 * if no identifier is provided, then the entire entity map is emptied
5364
+	 *
5365
+	 * @param int|string $id the ID of the model object
5366
+	 * @return boolean
5367
+	 */
5368
+	public function clear_entity_map($id = null)
5369
+	{
5370
+		if (empty($id)) {
5371
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
+			return true;
5373
+		}
5374
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
+			return true;
5377
+		}
5378
+		return false;
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
+	 * Given an array where keys are column (or column alias) names and values,
5386
+	 * returns an array of their corresponding field names and database values
5387
+	 *
5388
+	 * @param array $cols_n_values
5389
+	 * @return array
5390
+	 */
5391
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
+	{
5393
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * _deduce_fields_n_values_from_cols_n_values
5400
+	 * Given an array where keys are column (or column alias) names and values,
5401
+	 * returns an array of their corresponding field names and database values
5402
+	 *
5403
+	 * @param string $cols_n_values
5404
+	 * @return array
5405
+	 */
5406
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
+	{
5408
+		$this_model_fields_n_values = array();
5409
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
+				$cols_n_values,
5412
+				$table_obj->get_fully_qualified_pk_column(),
5413
+				$table_obj->get_pk_column()
5414
+			);
5415
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5416
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
+					if (! $field_obj->is_db_only_field()) {
5419
+						// prepare field as if its coming from db
5420
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
+					}
5423
+				}
5424
+			} else {
5425
+				// the table's rows existed. Use their values
5426
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
+					if (! $field_obj->is_db_only_field()) {
5428
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
+							$cols_n_values,
5430
+							$field_obj->get_qualified_column(),
5431
+							$field_obj->get_table_column()
5432
+						);
5433
+					}
5434
+				}
5435
+			}
5436
+		}
5437
+		return $this_model_fields_n_values;
5438
+	}
5439
+
5440
+
5441
+	/**
5442
+	 * @param $cols_n_values
5443
+	 * @param $qualified_column
5444
+	 * @param $regular_column
5445
+	 * @return null
5446
+	 * @throws EE_Error
5447
+	 * @throws ReflectionException
5448
+	 */
5449
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
+	{
5451
+		$value = null;
5452
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
+		// does the field on the model relate to this column retrieved from the db?
5454
+		// or is it a db-only field? (not relating to the model)
5455
+		if (isset($cols_n_values[ $qualified_column ])) {
5456
+			$value = $cols_n_values[ $qualified_column ];
5457
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5458
+			$value = $cols_n_values[ $regular_column ];
5459
+		} elseif (! empty($this->foreign_key_aliases)) {
5460
+			// no PK?  ok check if there is a foreign key alias set for this table
5461
+			// then check if that alias exists in the incoming data
5462
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
+					$value = $cols_n_values[ $FK_alias ];
5466
+					[$pk_class] = explode('.', $PK_column);
5467
+					$pk_model_name = "EEM_{$pk_class}";
5468
+					/** @var EEM_Base $pk_model */
5469
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
+					if ($pk_model instanceof EEM_Base) {
5471
+						// make sure object is pulled from db and added to entity map
5472
+						$pk_model->get_one_by_ID($value);
5473
+					}
5474
+					break;
5475
+				}
5476
+			}
5477
+		}
5478
+		return $value;
5479
+	}
5480
+
5481
+
5482
+
5483
+	/**
5484
+	 * refresh_entity_map_from_db
5485
+	 * Makes sure the model object in the entity map at $id assumes the values
5486
+	 * of the database (opposite of EE_base_Class::save())
5487
+	 *
5488
+	 * @param int|string $id
5489
+	 * @return EE_Base_Class
5490
+	 * @throws EE_Error
5491
+	 */
5492
+	public function refresh_entity_map_from_db($id)
5493
+	{
5494
+		$obj_in_map = $this->get_from_entity_map($id);
5495
+		if ($obj_in_map) {
5496
+			$wpdb_results = $this->_get_all_wpdb_results(
5497
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
+			);
5499
+			if ($wpdb_results && is_array($wpdb_results)) {
5500
+				$one_row = reset($wpdb_results);
5501
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
+					$obj_in_map->set_from_db($field_name, $db_value);
5503
+				}
5504
+				// clear the cache of related model objects
5505
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
+					$obj_in_map->clear_cache($relation_name, null, true);
5507
+				}
5508
+			}
5509
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
+			return $obj_in_map;
5511
+		}
5512
+		return $this->get_one_by_ID($id);
5513
+	}
5514
+
5515
+
5516
+
5517
+	/**
5518
+	 * refresh_entity_map_with
5519
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5520
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
+	 *
5524
+	 * @param int|string    $id
5525
+	 * @param EE_Base_Class $replacing_model_obj
5526
+	 * @return \EE_Base_Class
5527
+	 * @throws EE_Error
5528
+	 */
5529
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5530
+	{
5531
+		$obj_in_map = $this->get_from_entity_map($id);
5532
+		if ($obj_in_map) {
5533
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5534
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
+					$obj_in_map->set($field_name, $value);
5536
+				}
5537
+				// make the model object in the entity map's cache match the $replacing_model_obj
5538
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
+					$obj_in_map->clear_cache($relation_name, null, true);
5540
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
+					}
5543
+				}
5544
+			}
5545
+			return $obj_in_map;
5546
+		}
5547
+		$this->add_to_entity_map($replacing_model_obj);
5548
+		return $replacing_model_obj;
5549
+	}
5550
+
5551
+
5552
+
5553
+	/**
5554
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
+	 * require_once($this->_getClassName().".class.php");
5557
+	 *
5558
+	 * @return string
5559
+	 */
5560
+	private function _get_class_name()
5561
+	{
5562
+		return "EE_" . $this->get_this_model_name();
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5569
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
+	 * it would be 'Events'.
5571
+	 *
5572
+	 * @param int $quantity
5573
+	 * @return string
5574
+	 */
5575
+	public function item_name($quantity = 1)
5576
+	{
5577
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
+	}
5579
+
5580
+
5581
+
5582
+	/**
5583
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
+	 *        return $previousReturnValue.$returnString;
5595
+	 * }
5596
+	 * require('EEM_Answer.model.php');
5597
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5598
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5599
+	 *
5600
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5601
+	 * @param array  $args       array of original arguments passed to the function
5602
+	 * @throws EE_Error
5603
+	 * @return mixed whatever the plugin which calls add_filter decides
5604
+	 */
5605
+	public function __call($methodName, $args)
5606
+	{
5607
+		$className = get_class($this);
5608
+		$tagName = "FHEE__{$className}__{$methodName}";
5609
+		if (! has_filter($tagName)) {
5610
+			throw new EE_Error(
5611
+				sprintf(
5612
+					esc_html__(
5613
+						'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 );',
5614
+						'event_espresso'
5615
+					),
5616
+					$methodName,
5617
+					$className,
5618
+					$tagName,
5619
+					'<br />'
5620
+				)
5621
+			);
5622
+		}
5623
+		return apply_filters($tagName, null, $this, $args);
5624
+	}
5625
+
5626
+
5627
+
5628
+	/**
5629
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5630
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5631
+	 *
5632
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5633
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5634
+	 *                                                       the object's class name
5635
+	 *                                                       or object's ID
5636
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5637
+	 *                                                       exists in the database. If it does not, we add it
5638
+	 * @throws EE_Error
5639
+	 * @return EE_Base_Class
5640
+	 */
5641
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5642
+	{
5643
+		$className = $this->_get_class_name();
5644
+		if ($base_class_obj_or_id instanceof $className) {
5645
+			$model_object = $base_class_obj_or_id;
5646
+		} else {
5647
+			$primary_key_field = $this->get_primary_key_field();
5648
+			if (
5649
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5650
+				&& (
5651
+					is_int($base_class_obj_or_id)
5652
+					|| is_string($base_class_obj_or_id)
5653
+				)
5654
+			) {
5655
+				// assume it's an ID.
5656
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5657
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5658
+			} elseif (
5659
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5660
+				&& is_string($base_class_obj_or_id)
5661
+			) {
5662
+				// assume its a string representation of the object
5663
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5664
+			} else {
5665
+				throw new EE_Error(
5666
+					sprintf(
5667
+						esc_html__(
5668
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5669
+							'event_espresso'
5670
+						),
5671
+						$base_class_obj_or_id,
5672
+						$this->_get_class_name(),
5673
+						print_r($base_class_obj_or_id, true)
5674
+					)
5675
+				);
5676
+			}
5677
+		}
5678
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5679
+			$model_object->save();
5680
+		}
5681
+		return $model_object;
5682
+	}
5683
+
5684
+
5685
+
5686
+	/**
5687
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5688
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5689
+	 * returns it ID.
5690
+	 *
5691
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5692
+	 * @return int|string depending on the type of this model object's ID
5693
+	 * @throws EE_Error
5694
+	 */
5695
+	public function ensure_is_ID($base_class_obj_or_id)
5696
+	{
5697
+		$className = $this->_get_class_name();
5698
+		if ($base_class_obj_or_id instanceof $className) {
5699
+			/** @var $base_class_obj_or_id EE_Base_Class */
5700
+			$id = $base_class_obj_or_id->ID();
5701
+		} elseif (is_int($base_class_obj_or_id)) {
5702
+			// assume it's an ID
5703
+			$id = $base_class_obj_or_id;
5704
+		} elseif (is_string($base_class_obj_or_id)) {
5705
+			// assume its a string representation of the object
5706
+			$id = $base_class_obj_or_id;
5707
+		} else {
5708
+			throw new EE_Error(sprintf(
5709
+				esc_html__(
5710
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5711
+					'event_espresso'
5712
+				),
5713
+				$base_class_obj_or_id,
5714
+				$this->_get_class_name(),
5715
+				print_r($base_class_obj_or_id, true)
5716
+			));
5717
+		}
5718
+		return $id;
5719
+	}
5720
+
5721
+
5722
+
5723
+	/**
5724
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5725
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5726
+	 * been sanitized and converted into the appropriate domain.
5727
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5728
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5729
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5730
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5731
+	 * $EVT = EEM_Event::instance(); $old_setting =
5732
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5733
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5734
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5735
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5736
+	 *
5737
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5738
+	 * @return void
5739
+	 */
5740
+	public function assume_values_already_prepared_by_model_object(
5741
+		$values_already_prepared = self::not_prepared_by_model_object
5742
+	) {
5743
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5744
+	}
5745
+
5746
+
5747
+
5748
+	/**
5749
+	 * Read comments for assume_values_already_prepared_by_model_object()
5750
+	 *
5751
+	 * @return int
5752
+	 */
5753
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5754
+	{
5755
+		return $this->_values_already_prepared_by_model_object;
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * Gets all the indexes on this model
5762
+	 *
5763
+	 * @return EE_Index[]
5764
+	 */
5765
+	public function indexes()
5766
+	{
5767
+		return $this->_indexes;
5768
+	}
5769
+
5770
+
5771
+
5772
+	/**
5773
+	 * Gets all the Unique Indexes on this model
5774
+	 *
5775
+	 * @return EE_Unique_Index[]
5776
+	 */
5777
+	public function unique_indexes()
5778
+	{
5779
+		$unique_indexes = array();
5780
+		foreach ($this->_indexes as $name => $index) {
5781
+			if ($index instanceof EE_Unique_Index) {
5782
+				$unique_indexes [ $name ] = $index;
5783
+			}
5784
+		}
5785
+		return $unique_indexes;
5786
+	}
5787
+
5788
+
5789
+
5790
+	/**
5791
+	 * Gets all the fields which, when combined, make the primary key.
5792
+	 * This is usually just an array with 1 element (the primary key), but in cases
5793
+	 * where there is no primary key, it's a combination of fields as defined
5794
+	 * on a primary index
5795
+	 *
5796
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5797
+	 * @throws EE_Error
5798
+	 */
5799
+	public function get_combined_primary_key_fields()
5800
+	{
5801
+		foreach ($this->indexes() as $index) {
5802
+			if ($index instanceof EE_Primary_Key_Index) {
5803
+				return $index->fields();
5804
+			}
5805
+		}
5806
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5807
+	}
5808
+
5809
+
5810
+
5811
+	/**
5812
+	 * Used to build a primary key string (when the model has no primary key),
5813
+	 * which can be used a unique string to identify this model object.
5814
+	 *
5815
+	 * @param array $fields_n_values keys are field names, values are their values.
5816
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5817
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5818
+	 *                               before passing it to this function (that will convert it from columns-n-values
5819
+	 *                               to field-names-n-values).
5820
+	 * @return string
5821
+	 * @throws EE_Error
5822
+	 */
5823
+	public function get_index_primary_key_string($fields_n_values)
5824
+	{
5825
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5826
+			$fields_n_values,
5827
+			$this->get_combined_primary_key_fields()
5828
+		);
5829
+		return http_build_query($cols_n_values_for_primary_key_index);
5830
+	}
5831
+
5832
+
5833
+
5834
+	/**
5835
+	 * Gets the field values from the primary key string
5836
+	 *
5837
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5838
+	 * @param string $index_primary_key_string
5839
+	 * @return null|array
5840
+	 * @throws EE_Error
5841
+	 */
5842
+	public function parse_index_primary_key_string($index_primary_key_string)
5843
+	{
5844
+		$key_fields = $this->get_combined_primary_key_fields();
5845
+		// check all of them are in the $id
5846
+		$key_vals_in_combined_pk = array();
5847
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848
+		foreach ($key_fields as $key_field_name => $field_obj) {
5849
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5850
+				return null;
5851
+			}
5852
+		}
5853
+		return $key_vals_in_combined_pk;
5854
+	}
5855
+
5856
+
5857
+
5858
+	/**
5859
+	 * verifies that an array of key-value pairs for model fields has a key
5860
+	 * for each field comprising the primary key index
5861
+	 *
5862
+	 * @param array $key_vals
5863
+	 * @return boolean
5864
+	 * @throws EE_Error
5865
+	 */
5866
+	public function has_all_combined_primary_key_fields($key_vals)
5867
+	{
5868
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869
+		foreach ($keys_it_should_have as $key) {
5870
+			if (! isset($key_vals[ $key ])) {
5871
+				return false;
5872
+			}
5873
+		}
5874
+		return true;
5875
+	}
5876
+
5877
+
5878
+
5879
+	/**
5880
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5881
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5882
+	 *
5883
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5884
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5885
+	 * @throws EE_Error
5886
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5887
+	 *                                                              indexed)
5888
+	 */
5889
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5890
+	{
5891
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5892
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5893
+		} elseif (is_array($model_object_or_attributes_array)) {
5894
+			$attributes_array = $model_object_or_attributes_array;
5895
+		} else {
5896
+			throw new EE_Error(sprintf(esc_html__(
5897
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5898
+				"event_espresso"
5899
+			), $model_object_or_attributes_array));
5900
+		}
5901
+		// even copies obviously won't have the same ID, so remove the primary key
5902
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
+			unset($attributes_array[ $this->primary_key_name() ]);
5905
+		}
5906
+		if (isset($query_params[0])) {
5907
+			$query_params[0] = array_merge($attributes_array, $query_params);
5908
+		} else {
5909
+			$query_params[0] = $attributes_array;
5910
+		}
5911
+		return $this->get_all($query_params);
5912
+	}
5913
+
5914
+
5915
+
5916
+	/**
5917
+	 * Gets the first copy we find. See get_all_copies for more details
5918
+	 *
5919
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5920
+	 * @param array $query_params
5921
+	 * @return EE_Base_Class
5922
+	 * @throws EE_Error
5923
+	 */
5924
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925
+	{
5926
+		if (! is_array($query_params)) {
5927
+			EE_Error::doing_it_wrong(
5928
+				'EEM_Base::get_one_copy',
5929
+				sprintf(
5930
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5931
+					gettype($query_params)
5932
+				),
5933
+				'4.6.0'
5934
+			);
5935
+			$query_params = array();
5936
+		}
5937
+		$query_params['limit'] = 1;
5938
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5939
+		if (is_array($copies)) {
5940
+			return array_shift($copies);
5941
+		}
5942
+		return null;
5943
+	}
5944
+
5945
+
5946
+
5947
+	/**
5948
+	 * Updates the item with the specified id. Ignores default query parameters because
5949
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5950
+	 *
5951
+	 * @param array      $fields_n_values keys are field names, values are their new values
5952
+	 * @param int|string $id              the value of the primary key to update
5953
+	 * @return int number of rows updated
5954
+	 * @throws EE_Error
5955
+	 */
5956
+	public function update_by_ID($fields_n_values, $id)
5957
+	{
5958
+		$query_params = array(
5959
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5960
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5961
+		);
5962
+		return $this->update($fields_n_values, $query_params);
5963
+	}
5964
+
5965
+
5966
+
5967
+	/**
5968
+	 * Changes an operator which was supplied to the models into one usable in SQL
5969
+	 *
5970
+	 * @param string $operator_supplied
5971
+	 * @return string an operator which can be used in SQL
5972
+	 * @throws EE_Error
5973
+	 */
5974
+	private function _prepare_operator_for_sql($operator_supplied)
5975
+	{
5976
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5977
+			: null;
5978
+		if ($sql_operator) {
5979
+			return $sql_operator;
5980
+		}
5981
+		throw new EE_Error(
5982
+			sprintf(
5983
+				esc_html__(
5984
+					"The operator '%s' is not in the list of valid operators: %s",
5985
+					"event_espresso"
5986
+				),
5987
+				$operator_supplied,
5988
+				implode(",", array_keys($this->_valid_operators))
5989
+			)
5990
+		);
5991
+	}
5992
+
5993
+
5994
+
5995
+	/**
5996
+	 * Gets the valid operators
5997
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5998
+	 */
5999
+	public function valid_operators()
6000
+	{
6001
+		return $this->_valid_operators;
6002
+	}
6003
+
6004
+
6005
+
6006
+	/**
6007
+	 * Gets the between-style operators (take 2 arguments).
6008
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6009
+	 */
6010
+	public function valid_between_style_operators()
6011
+	{
6012
+		return array_intersect(
6013
+			$this->valid_operators(),
6014
+			$this->_between_style_operators
6015
+		);
6016
+	}
6017
+
6018
+	/**
6019
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6020
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6021
+	 */
6022
+	public function valid_like_style_operators()
6023
+	{
6024
+		return array_intersect(
6025
+			$this->valid_operators(),
6026
+			$this->_like_style_operators
6027
+		);
6028
+	}
6029
+
6030
+	/**
6031
+	 * Gets the "in"-style operators
6032
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6033
+	 */
6034
+	public function valid_in_style_operators()
6035
+	{
6036
+		return array_intersect(
6037
+			$this->valid_operators(),
6038
+			$this->_in_style_operators
6039
+		);
6040
+	}
6041
+
6042
+	/**
6043
+	 * Gets the "null"-style operators (accept no arguments)
6044
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6045
+	 */
6046
+	public function valid_null_style_operators()
6047
+	{
6048
+		return array_intersect(
6049
+			$this->valid_operators(),
6050
+			$this->_null_style_operators
6051
+		);
6052
+	}
6053
+
6054
+	/**
6055
+	 * Gets an array where keys are the primary keys and values are their 'names'
6056
+	 * (as determined by the model object's name() function, which is often overridden)
6057
+	 *
6058
+	 * @param array $query_params like get_all's
6059
+	 * @return string[]
6060
+	 * @throws EE_Error
6061
+	 */
6062
+	public function get_all_names($query_params = array())
6063
+	{
6064
+		$objs = $this->get_all($query_params);
6065
+		$names = array();
6066
+		foreach ($objs as $obj) {
6067
+			$names[ $obj->ID() ] = $obj->name();
6068
+		}
6069
+		return $names;
6070
+	}
6071
+
6072
+
6073
+
6074
+	/**
6075
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6076
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6077
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6078
+	 * array_keys() on $model_objects.
6079
+	 *
6080
+	 * @param \EE_Base_Class[] $model_objects
6081
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6082
+	 *                                               in the returned array
6083
+	 * @return array
6084
+	 * @throws EE_Error
6085
+	 */
6086
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087
+	{
6088
+		if (! $this->has_primary_key_field()) {
6089
+			if (WP_DEBUG) {
6090
+				EE_Error::add_error(
6091
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6092
+					__FILE__,
6093
+					__FUNCTION__,
6094
+					__LINE__
6095
+				);
6096
+			}
6097
+		}
6098
+		$IDs = array();
6099
+		foreach ($model_objects as $model_object) {
6100
+			$id = $model_object->ID();
6101
+			if (! $id) {
6102
+				if ($filter_out_empty_ids) {
6103
+					continue;
6104
+				}
6105
+				if (WP_DEBUG) {
6106
+					EE_Error::add_error(
6107
+						esc_html__(
6108
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6109
+							'event_espresso'
6110
+						),
6111
+						__FILE__,
6112
+						__FUNCTION__,
6113
+						__LINE__
6114
+					);
6115
+				}
6116
+			}
6117
+			$IDs[] = $id;
6118
+		}
6119
+		return $IDs;
6120
+	}
6121
+
6122
+
6123
+
6124
+	/**
6125
+	 * Returns the string used in capabilities relating to this model. If there
6126
+	 * are no capabilities that relate to this model returns false
6127
+	 *
6128
+	 * @return string|false
6129
+	 */
6130
+	public function cap_slug()
6131
+	{
6132
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6133
+	}
6134
+
6135
+
6136
+
6137
+	/**
6138
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6139
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6140
+	 * only returns the cap restrictions array in that context (ie, the array
6141
+	 * at that key)
6142
+	 *
6143
+	 * @param string $context
6144
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6145
+	 * @throws EE_Error
6146
+	 */
6147
+	public function cap_restrictions($context = EEM_Base::caps_read)
6148
+	{
6149
+		EEM_Base::verify_is_valid_cap_context($context);
6150
+		// check if we ought to run the restriction generator first
6151
+		if (
6152
+			isset($this->_cap_restriction_generators[ $context ])
6153
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6155
+		) {
6156
+			$this->_cap_restrictions[ $context ] = array_merge(
6157
+				$this->_cap_restrictions[ $context ],
6158
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6159
+			);
6160
+		}
6161
+		// and make sure we've finalized the construction of each restriction
6162
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6163
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164
+				$where_conditions_obj->_finalize_construct($this);
6165
+			}
6166
+		}
6167
+		return $this->_cap_restrictions[ $context ];
6168
+	}
6169
+
6170
+
6171
+
6172
+	/**
6173
+	 * Indicating whether or not this model thinks its a wp core model
6174
+	 *
6175
+	 * @return boolean
6176
+	 */
6177
+	public function is_wp_core_model()
6178
+	{
6179
+		return $this->_wp_core_model;
6180
+	}
6181
+
6182
+
6183
+
6184
+	/**
6185
+	 * Gets all the caps that are missing which impose a restriction on
6186
+	 * queries made in this context
6187
+	 *
6188
+	 * @param string $context one of EEM_Base::caps_ constants
6189
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6190
+	 * @throws EE_Error
6191
+	 */
6192
+	public function caps_missing($context = EEM_Base::caps_read)
6193
+	{
6194
+		$missing_caps = array();
6195
+		$cap_restrictions = $this->cap_restrictions($context);
6196
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197
+			if (
6198
+				! EE_Capabilities::instance()
6199
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6200
+			) {
6201
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6202
+			}
6203
+		}
6204
+		return $missing_caps;
6205
+	}
6206
+
6207
+
6208
+
6209
+	/**
6210
+	 * Gets the mapping from capability contexts to action strings used in capability names
6211
+	 *
6212
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6213
+	 * one of 'read', 'edit', or 'delete'
6214
+	 */
6215
+	public function cap_contexts_to_cap_action_map()
6216
+	{
6217
+		return apply_filters(
6218
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6219
+			$this->_cap_contexts_to_cap_action_map,
6220
+			$this
6221
+		);
6222
+	}
6223
+
6224
+
6225
+
6226
+	/**
6227
+	 * Gets the action string for the specified capability context
6228
+	 *
6229
+	 * @param string $context
6230
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6231
+	 * @throws EE_Error
6232
+	 */
6233
+	public function cap_action_for_context($context)
6234
+	{
6235
+		$mapping = $this->cap_contexts_to_cap_action_map();
6236
+		if (isset($mapping[ $context ])) {
6237
+			return $mapping[ $context ];
6238
+		}
6239
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240
+			return $action;
6241
+		}
6242
+		throw new EE_Error(
6243
+			sprintf(
6244
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6245
+				$context,
6246
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6247
+			)
6248
+		);
6249
+	}
6250
+
6251
+
6252
+
6253
+	/**
6254
+	 * Returns all the capability contexts which are valid when querying models
6255
+	 *
6256
+	 * @return array
6257
+	 */
6258
+	public static function valid_cap_contexts()
6259
+	{
6260
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6261
+			self::caps_read,
6262
+			self::caps_read_admin,
6263
+			self::caps_edit,
6264
+			self::caps_delete,
6265
+		));
6266
+	}
6267
+
6268
+
6269
+
6270
+	/**
6271
+	 * Returns all valid options for 'default_where_conditions'
6272
+	 *
6273
+	 * @return array
6274
+	 */
6275
+	public static function valid_default_where_conditions()
6276
+	{
6277
+		return array(
6278
+			EEM_Base::default_where_conditions_all,
6279
+			EEM_Base::default_where_conditions_this_only,
6280
+			EEM_Base::default_where_conditions_others_only,
6281
+			EEM_Base::default_where_conditions_minimum_all,
6282
+			EEM_Base::default_where_conditions_minimum_others,
6283
+			EEM_Base::default_where_conditions_none
6284
+		);
6285
+	}
6286
+
6287
+	// public static function default_where_conditions_full
6288
+	/**
6289
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6290
+	 *
6291
+	 * @param string $context
6292
+	 * @return bool
6293
+	 * @throws EE_Error
6294
+	 */
6295
+	public static function verify_is_valid_cap_context($context)
6296
+	{
6297
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6298
+		if (in_array($context, $valid_cap_contexts)) {
6299
+			return true;
6300
+		}
6301
+		throw new EE_Error(
6302
+			sprintf(
6303
+				esc_html__(
6304
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6305
+					'event_espresso'
6306
+				),
6307
+				$context,
6308
+				'EEM_Base',
6309
+				implode(',', $valid_cap_contexts)
6310
+			)
6311
+		);
6312
+	}
6313
+
6314
+
6315
+
6316
+	/**
6317
+	 * Clears all the models field caches. This is only useful when a sub-class
6318
+	 * might have added a field or something and these caches might be invalidated
6319
+	 */
6320
+	protected function _invalidate_field_caches()
6321
+	{
6322
+		$this->_cache_foreign_key_to_fields = array();
6323
+		$this->_cached_fields = null;
6324
+		$this->_cached_fields_non_db_only = null;
6325
+	}
6326
+
6327
+
6328
+
6329
+	/**
6330
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6331
+	 * (eg "and", "or", "not").
6332
+	 *
6333
+	 * @return array
6334
+	 */
6335
+	public function logic_query_param_keys()
6336
+	{
6337
+		return $this->_logic_query_param_keys;
6338
+	}
6339
+
6340
+
6341
+
6342
+	/**
6343
+	 * Determines whether or not the where query param array key is for a logic query param.
6344
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6345
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6346
+	 *
6347
+	 * @param $query_param_key
6348
+	 * @return bool
6349
+	 */
6350
+	public function is_logic_query_param_key($query_param_key)
6351
+	{
6352
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353
+			if (
6354
+				$query_param_key === $logic_query_param_key
6355
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6356
+			) {
6357
+				return true;
6358
+			}
6359
+		}
6360
+		return false;
6361
+	}
6362
+
6363
+	/**
6364
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6365
+	 * @since 4.9.74.p
6366
+	 * @return boolean
6367
+	 */
6368
+	public function hasPassword()
6369
+	{
6370
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6371
+		if ($this->has_password_field === null) {
6372
+			$password_field = $this->getPasswordField();
6373
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6374
+		}
6375
+		return $this->has_password_field;
6376
+	}
6377
+
6378
+	/**
6379
+	 * Returns the password field on this model, if there is one
6380
+	 * @since 4.9.74.p
6381
+	 * @return EE_Password_Field|null
6382
+	 */
6383
+	public function getPasswordField()
6384
+	{
6385
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6386
+		// there's no need to search for it. If we don't know yet, then find out
6387
+		if ($this->has_password_field === null && $this->password_field === null) {
6388
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6389
+		}
6390
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6391
+		return $this->password_field;
6392
+	}
6393
+
6394
+
6395
+	/**
6396
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6397
+	 * @since 4.9.74.p
6398
+	 * @return EE_Model_Field_Base[]
6399
+	 * @throws EE_Error
6400
+	 */
6401
+	public function getPasswordProtectedFields()
6402
+	{
6403
+		$password_field = $this->getPasswordField();
6404
+		$fields = array();
6405
+		if ($password_field instanceof EE_Password_Field) {
6406
+			$field_names = $password_field->protectedFields();
6407
+			foreach ($field_names as $field_name) {
6408
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6409
+			}
6410
+		}
6411
+		return $fields;
6412
+	}
6413
+
6414
+
6415
+	/**
6416
+	 * Checks if the current user can perform the requested action on this model
6417
+	 * @since 4.9.74.p
6418
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6419
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6420
+	 * @return bool
6421
+	 * @throws EE_Error
6422
+	 * @throws InvalidArgumentException
6423
+	 * @throws InvalidDataTypeException
6424
+	 * @throws InvalidInterfaceException
6425
+	 * @throws ReflectionException
6426
+	 * @throws UnexpectedEntityException
6427
+	 */
6428
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6429
+	{
6430
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432
+		}
6433
+		if (!is_array($model_obj_or_fields_n_values)) {
6434
+			throw new UnexpectedEntityException(
6435
+				$model_obj_or_fields_n_values,
6436
+				'EE_Base_Class',
6437
+				sprintf(
6438
+					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'),
6439
+					__FUNCTION__
6440
+				)
6441
+			);
6442
+		}
6443
+		return $this->exists(
6444
+			$this->alter_query_params_to_restrict_by_ID(
6445
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6446
+				array(
6447
+					'default_where_conditions' => 'none',
6448
+					'caps'                     => $cap_to_check,
6449
+				)
6450
+			)
6451
+		);
6452
+	}
6453
+
6454
+	/**
6455
+	 * Returns the query param where conditions key to the password affecting this model.
6456
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6457
+	 * @since 4.9.74.p
6458
+	 * @return null|string
6459
+	 * @throws EE_Error
6460
+	 * @throws InvalidArgumentException
6461
+	 * @throws InvalidDataTypeException
6462
+	 * @throws InvalidInterfaceException
6463
+	 * @throws ModelConfigurationException
6464
+	 * @throws ReflectionException
6465
+	 */
6466
+	public function modelChainAndPassword()
6467
+	{
6468
+		if ($this->model_chain_to_password === null) {
6469
+			throw new ModelConfigurationException(
6470
+				$this,
6471
+				esc_html_x(
6472
+				// @codingStandardsIgnoreStart
6473
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6474
+					// @codingStandardsIgnoreEnd
6475
+					'1: model name',
6476
+					'event_espresso'
6477
+				)
6478
+			);
6479
+		}
6480
+		if ($this->model_chain_to_password === '') {
6481
+			$model_with_password = $this;
6482
+		} else {
6483
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6484
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6485
+			} else {
6486
+				$last_model_in_chain = $this->model_chain_to_password;
6487
+			}
6488
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6489
+		}
6490
+
6491
+		$password_field = $model_with_password->getPasswordField();
6492
+		if ($password_field instanceof EE_Password_Field) {
6493
+			$password_field_name = $password_field->get_name();
6494
+		} else {
6495
+			throw new ModelConfigurationException(
6496
+				$this,
6497
+				sprintf(
6498
+					esc_html_x(
6499
+						'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"',
6500
+						'1: model name, 2: special string',
6501
+						'event_espresso'
6502
+					),
6503
+					$model_with_password->get_this_model_name(),
6504
+					$this->model_chain_to_password
6505
+				)
6506
+			);
6507
+		}
6508
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6509
+	}
6510
+
6511
+	/**
6512
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6513
+	 * or if this model itself has a password affecting access to some of its other fields.
6514
+	 * @since 4.9.74.p
6515
+	 * @return boolean
6516
+	 */
6517
+	public function restrictedByRelatedModelPassword()
6518
+	{
6519
+		return $this->model_chain_to_password !== null;
6520
+	}
6521 6521
 }
Please login to merge, or discard this patch.
Spacing   +227 added lines, -227 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
                     esc_html__(
@@ -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(esc_html__(
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
                             esc_html__(
@@ -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')
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
     {
892 892
         $wp_user_field_name = $this->wp_user_field_name();
893 893
         if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
895 895
         }
896 896
         return $query_params;
897 897
     }
@@ -909,17 +909,17 @@  discard block
 block discarded – undo
909 909
     public function wp_user_field_name()
910 910
     {
911 911
         try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
912
+            if ( ! empty($this->_model_chain_to_wp_user)) {
913 913
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914 914
                 $last_model_name = end($models_to_follow_to_wp_users);
915 915
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
917 917
             } else {
918 918
                 $model_with_fk_to_wp_users = $this;
919 919
                 $model_chain_to_wp_user = '';
920 920
             }
921 921
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
923 923
         } catch (EE_Error $e) {
924 924
             return false;
925 925
         }
@@ -996,11 +996,11 @@  discard block
 block discarded – undo
996 996
         if ($this->_custom_selections instanceof CustomSelects) {
997 997
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998 998
             $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
999
+                ? ', '.$custom_expressions
1000 1000
                 : $custom_expressions;
1001 1001
         }
1002 1002
 
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1004 1004
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005 1005
     }
1006 1006
 
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
      */
1018 1018
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019 1019
     {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021 1021
             return null;
1022 1022
         }
1023 1023
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             esc_html__(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159 1159
     {
1160
-        if (! isset($query_params[0])) {
1160
+        if ( ! isset($query_params[0])) {
1161 1161
             $query_params[0] = array();
1162 1162
         }
1163 1163
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1164 1164
         if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
+            $query_params[0][$this->primary_key_name()] = $id;
1166 1166
         } else {
1167 1167
             // no primary key, so the $id must be from the get_index_primary_key_string()
1168 1168
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function get_one($query_params = array())
1184 1184
     {
1185
-        if (! is_array($query_params)) {
1185
+        if ( ! is_array($query_params)) {
1186 1186
             EE_Error::doing_it_wrong(
1187 1187
                 'EEM_Base::get_one',
1188 1188
                 sprintf(
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
                 return array();
1381 1381
             }
1382 1382
         }
1383
-        if (! is_array($query_params)) {
1383
+        if ( ! is_array($query_params)) {
1384 1384
             EE_Error::doing_it_wrong(
1385 1385
                 'EEM_Base::_get_consecutive',
1386 1386
                 sprintf(
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
             $query_params = array();
1393 1393
         }
1394 1394
         // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1396 1396
         $query_params['limit'] = $limit;
1397 1397
         // set direction
1398 1398
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
     {
1474 1474
         $field_settings = $this->field_settings_for($field_name);
1475 1475
         // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1477 1477
             throw new EE_Error(sprintf(esc_html__(
1478 1478
                 '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.',
1479 1479
                 'event_espresso'
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
      */
1623 1623
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624 1624
     {
1625
-        if (! is_array($query_params)) {
1625
+        if ( ! is_array($query_params)) {
1626 1626
             EE_Error::doing_it_wrong(
1627 1627
                 'EEM_Base::update',
1628 1628
                 sprintf(
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
             $wpdb_result = (array) $wpdb_result;
1671 1671
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672 1672
             if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1674 1674
             } else {
1675 1675
                 // 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)
1676 1676
                 $main_table_pk_value = null;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
                     // in this table, right? so insert a row in the current table, using any fields available
1687 1687
                     if (
1688 1688
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1689
+                           && $wpdb_result[$this_table_pk_column])
1690 1690
                     ) {
1691 1691
                         $success = $this->_insert_into_specific_table(
1692 1692
                             $table_obj,
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                             $main_table_pk_value
1695 1695
                         );
1696 1696
                         // if we died here, report the error
1697
-                        if (! $success) {
1697
+                        if ( ! $success) {
1698 1698
                             return false;
1699 1699
                         }
1700 1700
                     }
@@ -1722,10 +1722,10 @@  discard block
 block discarded – undo
1722 1722
                 $model_objs_affected_ids = array();
1723 1723
                 foreach ($models_affected_key_columns as $row) {
1724 1724
                     $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1726 1726
                 }
1727 1727
             }
1728
-            if (! $model_objs_affected_ids) {
1728
+            if ( ! $model_objs_affected_ids) {
1729 1729
                 // wait wait wait- if nothing was affected let's stop here
1730 1730
                 return 0;
1731 1731
             }
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
                . $model_query_info->get_full_join_sql()
1753 1753
                . " SET "
1754 1754
                . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756 1756
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757 1757
         /**
1758 1758
          * Action called after a model update call has been made.
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
          * @param int      $rows_affected
1764 1764
          */
1765 1765
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1766
+        return $rows_affected; // how many supposedly got updated
1767 1767
     }
1768 1768
 
1769 1769
 
@@ -1794,7 +1794,7 @@  discard block
 block discarded – undo
1794 1794
         }
1795 1795
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1796 1796
         $select_expressions = $field->get_qualified_column();
1797
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1797
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1798 1798
         return $this->_do_wpdb_query('get_col', array($SQL));
1799 1799
     }
1800 1800
 
@@ -1812,7 +1812,7 @@  discard block
 block discarded – undo
1812 1812
     {
1813 1813
         $query_params['limit'] = 1;
1814 1814
         $col = $this->get_col($query_params, $field_to_select);
1815
-        if (! empty($col)) {
1815
+        if ( ! empty($col)) {
1816 1816
             return reset($col);
1817 1817
         }
1818 1818
         return null;
@@ -1843,7 +1843,7 @@  discard block
 block discarded – undo
1843 1843
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844 1844
             $value_sql = $prepared_value === null ? 'NULL'
1845 1845
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1846
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1847 1847
         }
1848 1848
         return implode(",", $cols_n_values);
1849 1849
     }
@@ -1987,12 +1987,12 @@  discard block
 block discarded – undo
1987 1987
         if (
1988 1988
             $this->has_primary_key_field()
1989 1989
             && $rows_deleted !== false
1990
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1990
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1991 1991
         ) {
1992
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1992
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1993 1993
             foreach ($ids_for_removal as $id) {
1994
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1994
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1995
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1996 1996
                 }
1997 1997
             }
1998 1998
 
@@ -2028,7 +2028,7 @@  discard block
 block discarded – undo
2028 2028
          * @param int      $rows_deleted
2029 2029
          */
2030 2030
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
-        return $rows_deleted;// how many supposedly got deleted
2031
+        return $rows_deleted; // how many supposedly got deleted
2032 2032
     }
2033 2033
 
2034 2034
 
@@ -2122,15 +2122,15 @@  discard block
 block discarded – undo
2122 2122
                 if (
2123 2123
                     $allow_blocking
2124 2124
                     && $this->delete_is_blocked_by_related_models(
2125
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2125
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2126 2126
                     )
2127 2127
                 ) {
2128 2128
                     continue;
2129 2129
                 }
2130 2130
                 // primary table deletes
2131
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2132
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2133
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2134 2134
                 }
2135 2135
             }
2136 2136
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2139,8 +2139,8 @@  discard block
 block discarded – undo
2139 2139
                 $ids_to_delete_indexed_by_column_for_row = array();
2140 2140
                 foreach ($fields as $cpk_field) {
2141 2141
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2142
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2143
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2144 2144
                     }
2145 2145
                 }
2146 2146
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
         } elseif ($this->has_primary_key_field()) {
2179 2179
             $query = array();
2180 2180
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2181
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2182 2182
             }
2183 2183
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184 2184
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2186,7 +2186,7 @@  discard block
 block discarded – undo
2186 2186
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187 2187
                 $values_for_each_combined_primary_key_for_a_row = array();
2188 2188
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2189
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2190 2190
                 }
2191 2191
                 $ways_to_identify_a_row[] = '('
2192 2192
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2258,8 +2258,8 @@  discard block
 block discarded – undo
2258 2258
                 $column_to_count = '*';
2259 2259
             }
2260 2260
         }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2262
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2263 2263
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264 2264
     }
2265 2265
 
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             $field_obj = $this->get_primary_key_field();
2283 2283
         }
2284 2284
         $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2285
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2286 2286
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287 2287
         $data_type = $field_obj->get_wpdb_data_type();
2288 2288
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2309,7 +2309,7 @@  discard block
 block discarded – undo
2309 2309
         // if we're in maintenance mode level 2, DON'T run any queries
2310 2310
         // because level 2 indicates the database needs updating and
2311 2311
         // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2312
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2313 2313
             throw new EE_Error(sprintf(esc_html__(
2314 2314
                 "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.",
2315 2315
                 "event_espresso"
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
         }
2318 2318
         /** @type WPDB $wpdb */
2319 2319
         global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2320
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2321 2321
             throw new EE_Error(sprintf(esc_html__(
2322 2322
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2323 2323
                 'event_espresso'
@@ -2331,7 +2331,7 @@  discard block
 block discarded – undo
2331 2331
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2332 2332
         if (WP_DEBUG) {
2333 2333
             $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2334
+            if ( ! empty($wpdb->last_error)) {
2335 2335
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336 2336
             }
2337 2337
             if ($result === false) {
@@ -2397,7 +2397,7 @@  discard block
 block discarded – undo
2397 2397
                     return $result;
2398 2398
                     break;
2399 2399
             }
2400
-            if (! empty($error_message)) {
2400
+            if ( ! empty($error_message)) {
2401 2401
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402 2402
                 trigger_error($error_message);
2403 2403
             }
@@ -2477,11 +2477,11 @@  discard block
 block discarded – undo
2477 2477
      */
2478 2478
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479 2479
     {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2480
+        return " FROM ".$model_query_info->get_full_join_sql().
2481
+               $model_query_info->get_where_sql().
2482
+               $model_query_info->get_group_by_sql().
2483
+               $model_query_info->get_having_sql().
2484
+               $model_query_info->get_order_by_sql().
2485 2485
                $model_query_info->get_limit_sql();
2486 2486
     }
2487 2487
 
@@ -2677,12 +2677,12 @@  discard block
 block discarded – undo
2677 2677
         $related_model = $this->get_related_model_obj($model_name);
2678 2678
         // we're just going to use the query params on the related model's normal get_all query,
2679 2679
         // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2680
+        if ( ! isset($query_params['default_where_conditions'])) {
2681 2681
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682 2682
         }
2683 2683
         $this_model_name = $this->get_this_model_name();
2684 2684
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2685
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2686 2686
         return $related_model->count($query_params, $field_to_count, $distinct);
2687 2687
     }
2688 2688
 
@@ -2702,7 +2702,7 @@  discard block
 block discarded – undo
2702 2702
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703 2703
     {
2704 2704
         $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2705
+        if ( ! is_array($query_params)) {
2706 2706
             EE_Error::doing_it_wrong(
2707 2707
                 'EEM_Base::sum_related',
2708 2708
                 sprintf(
@@ -2715,12 +2715,12 @@  discard block
 block discarded – undo
2715 2715
         }
2716 2716
         // we're just going to use the query params on the related model's normal get_all query,
2717 2717
         // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2718
+        if ( ! isset($query_params['default_where_conditions'])) {
2719 2719
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720 2720
         }
2721 2721
         $this_model_name = $this->get_this_model_name();
2722 2722
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2723
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2724 2724
         return $related_model->sum($query_params, $field_to_sum);
2725 2725
     }
2726 2726
 
@@ -2773,7 +2773,7 @@  discard block
 block discarded – undo
2773 2773
                 $field_with_model_name = $field;
2774 2774
             }
2775 2775
         }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2776
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2777 2777
             throw new EE_Error(sprintf(
2778 2778
                 esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779 2779
                 $this->get_this_model_name()
@@ -2910,13 +2910,13 @@  discard block
 block discarded – undo
2910 2910
                 || $this->get_primary_key_field()
2911 2911
                    instanceof
2912 2912
                    EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2913
+            && isset($fields_n_values[$this->primary_key_name()])
2914 2914
         ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2915
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2916 2916
         }
2917 2917
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918 2918
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2919
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2920 2920
         }
2921 2921
         // if there is nothing to base this search on, then we shouldn't find anything
2922 2922
         if (empty($query_params)) {
@@ -2994,15 +2994,15 @@  discard block
 block discarded – undo
2994 2994
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995 2995
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996 2996
             if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2997
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2998 2998
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999 2999
             }
3000 3000
         }
3001 3001
         if ($table instanceof EE_Secondary_Table && $new_id) {
3002 3002
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3003 3003
             // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3005
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3006 3006
         }
3007 3007
         // insert the new entry
3008 3008
         $result = $this->_do_wpdb_query(
@@ -3019,7 +3019,7 @@  discard block
 block discarded – undo
3019 3019
             }
3020 3020
             // it's not an auto-increment primary key, so
3021 3021
             // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3022
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3023 3023
         }
3024 3024
         // we can't return a  primary key because there is none. instead return
3025 3025
         // a unique string indicating this model
@@ -3044,14 +3044,14 @@  discard block
 block discarded – undo
3044 3044
         if (
3045 3045
             ! $field_obj->is_nullable()
3046 3046
             && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
+                ! isset($fields_n_values[$field_obj->get_name()])
3048
+                || $fields_n_values[$field_obj->get_name()] === null
3049 3049
             )
3050 3050
         ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3051
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3052 3052
         }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3054
+            ? $fields_n_values[$field_obj->get_name()]
3055 3055
             : null;
3056 3056
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057 3057
     }
@@ -3152,7 +3152,7 @@  discard block
 block discarded – undo
3152 3152
      */
3153 3153
     public function get_table_obj_by_alias($table_alias = '')
3154 3154
     {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3155
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156 3156
     }
3157 3157
 
3158 3158
 
@@ -3167,7 +3167,7 @@  discard block
 block discarded – undo
3167 3167
         $other_tables = array();
3168 3168
         foreach ($this->_tables as $table_alias => $table) {
3169 3169
             if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3170
+                $other_tables[$table_alias] = $table;
3171 3171
             }
3172 3172
         }
3173 3173
         return $other_tables;
@@ -3183,7 +3183,7 @@  discard block
 block discarded – undo
3183 3183
      */
3184 3184
     public function _get_fields_for_table($table_alias)
3185 3185
     {
3186
-        return $this->_fields[ $table_alias ];
3186
+        return $this->_fields[$table_alias];
3187 3187
     }
3188 3188
 
3189 3189
 
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
                     $query_info_carrier,
3213 3213
                     'group_by'
3214 3214
                 );
3215
-            } elseif (! empty($query_params['group_by'])) {
3215
+            } elseif ( ! empty($query_params['group_by'])) {
3216 3216
                 $this->_extract_related_model_info_from_query_param(
3217 3217
                     $query_params['group_by'],
3218 3218
                     $query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                     $query_info_carrier,
3235 3235
                     'order_by'
3236 3236
                 );
3237
-            } elseif (! empty($query_params['order_by'])) {
3237
+            } elseif ( ! empty($query_params['order_by'])) {
3238 3238
                 $this->_extract_related_model_info_from_query_param(
3239 3239
                     $query_params['order_by'],
3240 3240
                     $query_info_carrier,
@@ -3269,7 +3269,7 @@  discard block
 block discarded – undo
3269 3269
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270 3270
         $query_param_type
3271 3271
     ) {
3272
-        if (! empty($sub_query_params)) {
3272
+        if ( ! empty($sub_query_params)) {
3273 3273
             $sub_query_params = (array) $sub_query_params;
3274 3274
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275 3275
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                 // of array('Registration.TXN_ID'=>23)
3285 3285
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286 3286
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3287
+                    if ( ! is_array($possibly_array_of_params)) {
3288 3288
                         throw new EE_Error(sprintf(
3289 3289
                             esc_html__(
3290 3290
                                 "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'))",
@@ -3308,7 +3308,7 @@  discard block
 block discarded – undo
3308 3308
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309 3309
                     // indicating that $possible_array_of_params[1] is actually a field name,
3310 3310
                     // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312 3312
                         throw new EE_Error(sprintf(esc_html__(
3313 3313
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314 3314
                             "event_espresso"
@@ -3342,8 +3342,8 @@  discard block
 block discarded – undo
3342 3342
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343 3343
         $query_param_type
3344 3344
     ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3345
+        if ( ! empty($sub_query_params)) {
3346
+            if ( ! is_array($sub_query_params)) {
3347 3347
                 throw new EE_Error(sprintf(
3348 3348
                     esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349 3349
                     $sub_query_params
@@ -3377,7 +3377,7 @@  discard block
 block discarded – undo
3377 3377
      */
3378 3378
     public function _create_model_query_info_carrier($query_params)
3379 3379
     {
3380
-        if (! is_array($query_params)) {
3380
+        if ( ! is_array($query_params)) {
3381 3381
             EE_Error::doing_it_wrong(
3382 3382
                 'EEM_Base::_create_model_query_info_carrier',
3383 3383
                 sprintf(
@@ -3410,7 +3410,7 @@  discard block
 block discarded – undo
3410 3410
             // only include if related to a cpt where no password has been set
3411 3411
             $query_params[0]['OR*nopassword'] = array(
3412 3412
                 $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3413
+                $where_param_key_for_password.'*' => array('IS_NULL')
3414 3414
             );
3415 3415
         }
3416 3416
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3464,7 +3464,7 @@  discard block
 block discarded – undo
3464 3464
         // set limit
3465 3465
         if (array_key_exists('limit', $query_params)) {
3466 3466
             if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468 3468
                     $e = sprintf(
3469 3469
                         esc_html__(
3470 3470
                             "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)",
@@ -3472,12 +3472,12 @@  discard block
 block discarded – undo
3472 3472
                         ),
3473 3473
                         http_build_query($query_params['limit'])
3474 3474
                     );
3475
-                    throw new EE_Error($e . "|" . $e);
3475
+                    throw new EE_Error($e."|".$e);
3476 3476
                 }
3477 3477
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3478
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3479
+            } elseif ( ! empty($query_params['limit'])) {
3480
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3481 3481
             }
3482 3482
         }
3483 3483
         // set order by
@@ -3509,10 +3509,10 @@  discard block
 block discarded – undo
3509 3509
                 $order_array = array();
3510 3510
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511 3511
                     $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3512
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3513 3513
                 }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3514
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3515
+            } elseif ( ! empty($query_params['order_by'])) {
3516 3516
                 $this->_extract_related_model_info_from_query_param(
3517 3517
                     $query_params['order_by'],
3518 3518
                     $query_object,
@@ -3523,7 +3523,7 @@  discard block
 block discarded – undo
3523 3523
                     ? $this->_extract_order($query_params['order'])
3524 3524
                     : 'DESC';
3525 3525
                 $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3526
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3527 3527
                 );
3528 3528
             }
3529 3529
         }
@@ -3535,7 +3535,7 @@  discard block
 block discarded – undo
3535 3535
         ) {
3536 3536
             $pk_field = $this->get_primary_key_field();
3537 3537
             $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3538
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3539 3539
         }
3540 3540
         // set group by
3541 3541
         if (array_key_exists('group_by', $query_params)) {
@@ -3545,10 +3545,10 @@  discard block
 block discarded – undo
3545 3545
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546 3546
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547 3547
                 }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3548
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3549
+            } elseif ( ! empty($query_params['group_by'])) {
3550 3550
                 $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3551
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3552 3552
                 );
3553 3553
             }
3554 3554
         }
@@ -3558,7 +3558,7 @@  discard block
 block discarded – undo
3558 3558
         }
3559 3559
         // now, just verify they didn't pass anything wack
3560 3560
         foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3561
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3562 3562
                 throw new EE_Error(
3563 3563
                     sprintf(
3564 3564
                         esc_html__(
@@ -3666,7 +3666,7 @@  discard block
 block discarded – undo
3666 3666
         $where_query_params = array()
3667 3667
     ) {
3668 3668
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670 3670
             throw new EE_Error(sprintf(
3671 3671
                 esc_html__(
3672 3672
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3798,19 +3798,19 @@  discard block
 block discarded – undo
3798 3798
     ) {
3799 3799
         $null_friendly_where_conditions = array();
3800 3800
         $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3801
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3802 3802
         foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3803
+            if (isset($provided_where_conditions[$key])) {
3804 3804
                 $none_overridden = false;
3805 3805
             } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3806
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3807 3807
             }
3808 3808
         }
3809 3809
         if ($none_overridden && $default_where_conditions) {
3810 3810
             if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3811
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3812 3812
                                                                                 . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3813
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3814 3814
             }/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
@@ -3917,7 +3917,7 @@  discard block
 block discarded – undo
3917 3917
             foreach ($tables as $table_obj) {
3918 3918
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919 3919
                                        . $table_obj->get_fully_qualified_pk_column();
3920
-                if (! in_array($qualified_pk_column, $selects)) {
3920
+                if ( ! in_array($qualified_pk_column, $selects)) {
3921 3921
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922 3922
                 }
3923 3923
             }
@@ -4069,9 +4069,9 @@  discard block
 block discarded – undo
4069 4069
         $query_parameter_type
4070 4070
     ) {
4071 4071
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4072
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4073 4073
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4074
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4075 4075
                 if ($possible_join_string === '') {
4076 4076
                     // nothing left to $query_param
4077 4077
                     // we should actually end in a field name, not a model like this!
@@ -4202,7 +4202,7 @@  discard block
 block discarded – undo
4202 4202
     {
4203 4203
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204 4204
         if ($SQL) {
4205
-            return " WHERE " . $SQL;
4205
+            return " WHERE ".$SQL;
4206 4206
         }
4207 4207
         return '';
4208 4208
     }
@@ -4221,7 +4221,7 @@  discard block
 block discarded – undo
4221 4221
     {
4222 4222
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223 4223
         if ($SQL) {
4224
-            return " HAVING " . $SQL;
4224
+            return " HAVING ".$SQL;
4225 4225
         }
4226 4226
         return '';
4227 4227
     }
@@ -4240,7 +4240,7 @@  discard block
 block discarded – undo
4240 4240
     {
4241 4241
         $where_clauses = array();
4242 4242
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4243
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4244 4244
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4245 4245
                 switch ($query_param) {
4246 4246
                     case 'not':
@@ -4274,7 +4274,7 @@  discard block
 block discarded – undo
4274 4274
             } else {
4275 4275
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4276 4276
                 // if it's not a normal field, maybe it's a custom selection?
4277
-                if (! $field_obj) {
4277
+                if ( ! $field_obj) {
4278 4278
                     if ($this->_custom_selections instanceof CustomSelects) {
4279 4279
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280 4280
                     } else {
@@ -4285,7 +4285,7 @@  discard block
 block discarded – undo
4285 4285
                     }
4286 4286
                 }
4287 4287
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4288
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4289 4289
             }
4290 4290
         }
4291 4291
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4308,7 +4308,7 @@  discard block
 block discarded – undo
4308 4308
                 $field->get_model_name(),
4309 4309
                 $query_param
4310 4310
             );
4311
-            return $table_alias_prefix . $field->get_qualified_column();
4311
+            return $table_alias_prefix.$field->get_qualified_column();
4312 4312
         }
4313 4313
         if (
4314 4314
             $this->_custom_selections instanceof CustomSelects
@@ -4368,7 +4368,7 @@  discard block
 block discarded – undo
4368 4368
     {
4369 4369
         if (is_array($op_and_value)) {
4370 4370
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
-            if (! $operator) {
4371
+            if ( ! $operator) {
4372 4372
                 $php_array_like_string = array();
4373 4373
                 foreach ($op_and_value as $key => $value) {
4374 4374
                     $php_array_like_string[] = "$key=>$value";
@@ -4390,14 +4390,14 @@  discard block
 block discarded – undo
4390 4390
         }
4391 4391
         // check to see if the value is actually another field
4392 4392
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4393
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4394 4394
         }
4395 4395
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396 4396
             // in this case, the value should be an array, or at least a comma-separated list
4397 4397
             // it will need to handle a little differently
4398 4398
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4399 4399
             // note: $cleaned_value has already been run through $wpdb->prepare()
4400
-            return $operator . SP . $cleaned_value;
4400
+            return $operator.SP.$cleaned_value;
4401 4401
         }
4402 4402
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403 4403
             // the value should be an array with count of two.
@@ -4413,7 +4413,7 @@  discard block
 block discarded – undo
4413 4413
                 );
4414 4414
             }
4415 4415
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
-            return $operator . SP . $cleaned_value;
4416
+            return $operator.SP.$cleaned_value;
4417 4417
         }
4418 4418
         if (in_array($operator, $this->valid_null_style_operators())) {
4419 4419
             if ($value !== null) {
@@ -4433,10 +4433,10 @@  discard block
 block discarded – undo
4433 4433
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434 4434
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4435 4435
             // remove other junk. So just treat it as a string.
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4436
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4437 4437
         }
4438
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4440 4440
         }
4441 4441
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442 4442
             throw new EE_Error(
@@ -4450,7 +4450,7 @@  discard block
 block discarded – undo
4450 4450
                 )
4451 4451
             );
4452 4452
         }
4453
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4453
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454 4454
             throw new EE_Error(
4455 4455
                 sprintf(
4456 4456
                     esc_html__(
@@ -4490,7 +4490,7 @@  discard block
 block discarded – undo
4490 4490
         foreach ($values as $value) {
4491 4491
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492 4492
         }
4493
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4493
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4494 4494
     }
4495 4495
 
4496 4496
 
@@ -4524,11 +4524,11 @@  discard block
 block discarded – undo
4524 4524
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525 4525
         if (empty($prepped)) {
4526 4526
             $all_fields = $this->field_settings();
4527
-            $first_field    = reset($all_fields);
4527
+            $first_field = reset($all_fields);
4528 4528
             $main_table = $this->_get_main_table();
4529 4529
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530 4530
         }
4531
-        return '(' . implode(',', $prepped) . ')';
4531
+        return '('.implode(',', $prepped).')';
4532 4532
     }
4533 4533
 
4534 4534
 
@@ -4549,7 +4549,7 @@  discard block
 block discarded – undo
4549 4549
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4550 4550
             );
4551 4551
         } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4552
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553 4553
             throw new EE_Error(
4554 4554
                 sprintf(
4555 4555
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4582,14 +4582,14 @@  discard block
 block discarded – undo
4582 4582
             ), $query_param_name));
4583 4583
         }
4584 4584
         $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4585
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4586 4586
         if ($number_of_parts === 1) {
4587 4587
             $field_name = $last_query_param_part;
4588 4588
             $model_obj = $this;
4589 4589
         } else {// $number_of_parts >= 2
4590 4590
             // the last part is the column name, and there are only 2parts. therefore...
4591 4591
             $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4592
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4593 4593
         }
4594 4594
         try {
4595 4595
             return $model_obj->field_settings_for($field_name);
@@ -4611,7 +4611,7 @@  discard block
 block discarded – undo
4611 4611
     public function _get_qualified_column_for_field($field_name)
4612 4612
     {
4613 4613
         $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4614
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4615 4615
         if ($field) {
4616 4616
             return $field->get_qualified_column();
4617 4617
         }
@@ -4682,10 +4682,10 @@  discard block
 block discarded – undo
4682 4682
      */
4683 4683
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684 4684
     {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4685
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4686 4686
         $qualified_columns = array();
4687 4687
         foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4688
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4689 4689
         }
4690 4690
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691 4691
     }
@@ -4709,11 +4709,11 @@  discard block
 block discarded – undo
4709 4709
             if ($table_obj instanceof EE_Primary_Table) {
4710 4710
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4711 4711
                     ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4712
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4713 4713
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4714 4714
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4715 4715
                     ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4716
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4717 4717
             }
4718 4718
         }
4719 4719
         return $SQL;
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
         foreach ($this->field_settings() as $field_obj) {
4786 4786
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787 4787
             /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4788
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4789 4789
         }
4790 4790
         return $data_types;
4791 4791
     }
@@ -4801,14 +4801,14 @@  discard block
 block discarded – undo
4801 4801
      */
4802 4802
     public function get_related_model_obj($model_name)
4803 4803
     {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4804
+        $model_classname = "EEM_".$model_name;
4805
+        if ( ! class_exists($model_classname)) {
4806 4806
             throw new EE_Error(sprintf(esc_html__(
4807 4807
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808 4808
                 'event_espresso'
4809 4809
             ), $model_name, $model_classname));
4810 4810
         }
4811
-        return call_user_func($model_classname . "::instance");
4811
+        return call_user_func($model_classname."::instance");
4812 4812
     }
4813 4813
 
4814 4814
 
@@ -4837,7 +4837,7 @@  discard block
 block discarded – undo
4837 4837
         $belongs_to_relations = array();
4838 4838
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839 4839
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4840
+                $belongs_to_relations[$model_name] = $relation_obj;
4841 4841
             }
4842 4842
         }
4843 4843
         return $belongs_to_relations;
@@ -4855,7 +4855,7 @@  discard block
 block discarded – undo
4855 4855
     public function related_settings_for($relation_name)
4856 4856
     {
4857 4857
         $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4858
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4859 4859
             throw new EE_Error(
4860 4860
                 sprintf(
4861 4861
                     esc_html__(
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
                 )
4869 4869
             );
4870 4870
         }
4871
-        return $relatedModels[ $relation_name ];
4871
+        return $relatedModels[$relation_name];
4872 4872
     }
4873 4873
 
4874 4874
 
@@ -4885,14 +4885,14 @@  discard block
 block discarded – undo
4885 4885
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4886 4886
     {
4887 4887
         $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4888
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4889 4889
             throw new EE_Error(sprintf(
4890 4890
                 esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891 4891
                 $fieldName,
4892 4892
                 get_class($this)
4893 4893
             ));
4894 4894
         }
4895
-        return $fieldSettings[ $fieldName ];
4895
+        return $fieldSettings[$fieldName];
4896 4896
     }
4897 4897
 
4898 4898
 
@@ -4906,7 +4906,7 @@  discard block
 block discarded – undo
4906 4906
     public function has_field($fieldName)
4907 4907
     {
4908 4908
         $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4909
+        if (isset($fieldSettings[$fieldName])) {
4910 4910
             return true;
4911 4911
         }
4912 4912
         return false;
@@ -4923,7 +4923,7 @@  discard block
 block discarded – undo
4923 4923
     public function has_relation($relation_name)
4924 4924
     {
4925 4925
         $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4926
+        if (isset($relations[$relation_name])) {
4927 4927
             return true;
4928 4928
         }
4929 4929
         return false;
@@ -4961,7 +4961,7 @@  discard block
 block discarded – undo
4961 4961
                     break;
4962 4962
                 }
4963 4963
             }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4964
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965 4965
                 throw new EE_Error(sprintf(
4966 4966
                     esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967 4967
                     get_class($this)
@@ -5022,24 +5022,24 @@  discard block
 block discarded – undo
5022 5022
      */
5023 5023
     public function get_foreign_key_to($model_name)
5024 5024
     {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5025
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5026 5026
             foreach ($this->field_settings() as $field) {
5027 5027
                 if (
5028 5028
                     $field instanceof EE_Foreign_Key_Field_Base
5029 5029
                     && in_array($model_name, $field->get_model_names_pointed_to())
5030 5030
                 ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5031
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5032 5032
                     break;
5033 5033
                 }
5034 5034
             }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5035
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5036 5036
                 throw new EE_Error(sprintf(esc_html__(
5037 5037
                     "There is no foreign key field pointing to model %s on model %s",
5038 5038
                     'event_espresso'
5039 5039
                 ), $model_name, get_class($this)));
5040 5040
             }
5041 5041
         }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5042
+        return $this->_cache_foreign_key_to_fields[$model_name];
5043 5043
     }
5044 5044
 
5045 5045
 
@@ -5055,7 +5055,7 @@  discard block
 block discarded – undo
5055 5055
     public function get_table_for_alias($table_alias)
5056 5056
     {
5057 5057
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5058
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5059 5059
     }
5060 5060
 
5061 5061
 
@@ -5074,7 +5074,7 @@  discard block
 block discarded – undo
5074 5074
                 $this->_cached_fields = array();
5075 5075
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5076 5076
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5077
+                        $this->_cached_fields[$field_name] = $field_obj;
5078 5078
                     }
5079 5079
                 }
5080 5080
             }
@@ -5085,8 +5085,8 @@  discard block
 block discarded – undo
5085 5085
             foreach ($this->_fields as $fields_corresponding_to_table) {
5086 5086
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087 5087
                     /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+                    if ( ! $field_obj->is_db_only_field()) {
5089
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5090 5090
                     }
5091 5091
                 }
5092 5092
             }
@@ -5127,12 +5127,12 @@  discard block
 block discarded – undo
5127 5127
                     $primary_key_field->get_qualified_column(),
5128 5128
                     $primary_key_field->get_table_column()
5129 5129
                 );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5130
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5131 5131
                     continue;
5132 5132
                 }
5133 5133
             }
5134 5134
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5135
+            if ( ! $classInstance) {
5136 5136
                 throw new EE_Error(
5137 5137
                     sprintf(
5138 5138
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5145,7 +5145,7 @@  discard block
 block discarded – undo
5145 5145
             $classInstance->set_timezone($this->_timezone);
5146 5146
             // make sure if there is any timezone setting present that we set the timezone for the object
5147 5147
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5148
+            $array_of_objects[$key] = $classInstance;
5149 5149
             // also, for all the relations of type BelongsTo, see if we can cache
5150 5150
             // those related models
5151 5151
             // (we could do this for other relations too, but if there are conditions
@@ -5189,9 +5189,9 @@  discard block
 block discarded – undo
5189 5189
         $results = array();
5190 5190
         if ($this->_custom_selections instanceof CustomSelects) {
5191 5191
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5192
+                if (isset($db_results_row[$alias])) {
5193
+                    $results[$alias] = $this->convertValueToDataType(
5194
+                        $db_results_row[$alias],
5195 5195
                         $this->_custom_selections->getDataTypeForAlias($alias)
5196 5196
                     );
5197 5197
                 }
@@ -5233,7 +5233,7 @@  discard block
 block discarded – undo
5233 5233
         $this_model_fields_and_values = array();
5234 5234
         // setup the row using default values;
5235 5235
         foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5236
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5237 5237
         }
5238 5238
         $className = $this->_get_class_name();
5239 5239
         $classInstance = EE_Registry::instance()
@@ -5251,20 +5251,20 @@  discard block
 block discarded – undo
5251 5251
      */
5252 5252
     public function instantiate_class_from_array_or_object($cols_n_values)
5253 5253
     {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5254
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5255 5255
             $cols_n_values = get_object_vars($cols_n_values);
5256 5256
         }
5257 5257
         $primary_key = null;
5258 5258
         // make sure the array only has keys that are fields/columns on this model
5259 5259
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5261
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5262 5262
         }
5263 5263
         $className = $this->_get_class_name();
5264 5264
         // check we actually found results that we can use to build our model object
5265 5265
         // if not, return null
5266 5266
         if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5267
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5268 5268
                 return null;
5269 5269
             }
5270 5270
         } elseif ($this->unique_indexes()) {
@@ -5276,7 +5276,7 @@  discard block
 block discarded – undo
5276 5276
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277 5277
         if ($primary_key) {
5278 5278
             $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5279
+            if ( ! $classInstance) {
5280 5280
                 $classInstance = EE_Registry::instance()
5281 5281
                                             ->load_class(
5282 5282
                                                 $className,
@@ -5309,8 +5309,8 @@  discard block
 block discarded – undo
5309 5309
      */
5310 5310
     public function get_from_entity_map($id)
5311 5311
     {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5313
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5314 5314
     }
5315 5315
 
5316 5316
 
@@ -5333,7 +5333,7 @@  discard block
 block discarded – undo
5333 5333
     public function add_to_entity_map(EE_Base_Class $object)
5334 5334
     {
5335 5335
         $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5336
+        if ( ! $object instanceof $className) {
5337 5337
             throw new EE_Error(sprintf(
5338 5338
                 esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339 5339
                 is_object($object) ? get_class($object) : $object,
@@ -5341,7 +5341,7 @@  discard block
 block discarded – undo
5341 5341
             ));
5342 5342
         }
5343 5343
         /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5344
+        if ( ! $object->ID()) {
5345 5345
             throw new EE_Error(sprintf(esc_html__(
5346 5346
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5347 5347
                 "event_espresso"
@@ -5352,7 +5352,7 @@  discard block
 block discarded – undo
5352 5352
         if ($classInstance) {
5353 5353
             return $classInstance;
5354 5354
         }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5355
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5356 5356
         return $object;
5357 5357
     }
5358 5358
 
@@ -5368,11 +5368,11 @@  discard block
 block discarded – undo
5368 5368
     public function clear_entity_map($id = null)
5369 5369
     {
5370 5370
         if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5371
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5372 5372
             return true;
5373 5373
         }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5375
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5376 5376
             return true;
5377 5377
         }
5378 5378
         return false;
@@ -5415,17 +5415,17 @@  discard block
 block discarded – undo
5415 5415
             // there is a primary key on this table and its not set. Use defaults for all its columns
5416 5416
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417 5417
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5418
+                    if ( ! $field_obj->is_db_only_field()) {
5419 5419
                         // prepare field as if its coming from db
5420 5420
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5421
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5422 5422
                     }
5423 5423
                 }
5424 5424
             } else {
5425 5425
                 // the table's rows existed. Use their values
5426 5426
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+                    if ( ! $field_obj->is_db_only_field()) {
5428
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5429 5429
                             $cols_n_values,
5430 5430
                             $field_obj->get_qualified_column(),
5431 5431
                             $field_obj->get_table_column()
@@ -5452,17 +5452,17 @@  discard block
 block discarded – undo
5452 5452
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453 5453
         // does the field on the model relate to this column retrieved from the db?
5454 5454
         // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5455
+        if (isset($cols_n_values[$qualified_column])) {
5456
+            $value = $cols_n_values[$qualified_column];
5457
+        } elseif (isset($cols_n_values[$regular_column])) {
5458
+            $value = $cols_n_values[$regular_column];
5459
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5460 5460
             // no PK?  ok check if there is a foreign key alias set for this table
5461 5461
             // then check if that alias exists in the incoming data
5462 5462
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463 5463
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5464
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5465
+                    $value = $cols_n_values[$FK_alias];
5466 5466
                     [$pk_class] = explode('.', $PK_column);
5467 5467
                     $pk_model_name = "EEM_{$pk_class}";
5468 5468
                     /** @var EEM_Base $pk_model */
@@ -5506,7 +5506,7 @@  discard block
 block discarded – undo
5506 5506
                     $obj_in_map->clear_cache($relation_name, null, true);
5507 5507
                 }
5508 5508
             }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5509
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5510 5510
             return $obj_in_map;
5511 5511
         }
5512 5512
         return $this->get_one_by_ID($id);
@@ -5559,7 +5559,7 @@  discard block
 block discarded – undo
5559 5559
      */
5560 5560
     private function _get_class_name()
5561 5561
     {
5562
-        return "EE_" . $this->get_this_model_name();
5562
+        return "EE_".$this->get_this_model_name();
5563 5563
     }
5564 5564
 
5565 5565
 
@@ -5606,7 +5606,7 @@  discard block
 block discarded – undo
5606 5606
     {
5607 5607
         $className = get_class($this);
5608 5608
         $tagName = "FHEE__{$className}__{$methodName}";
5609
-        if (! has_filter($tagName)) {
5609
+        if ( ! has_filter($tagName)) {
5610 5610
             throw new EE_Error(
5611 5611
                 sprintf(
5612 5612
                     esc_html__(
@@ -5779,7 +5779,7 @@  discard block
 block discarded – undo
5779 5779
         $unique_indexes = array();
5780 5780
         foreach ($this->_indexes as $name => $index) {
5781 5781
             if ($index instanceof EE_Unique_Index) {
5782
-                $unique_indexes [ $name ] = $index;
5782
+                $unique_indexes [$name] = $index;
5783 5783
             }
5784 5784
         }
5785 5785
         return $unique_indexes;
@@ -5846,7 +5846,7 @@  discard block
 block discarded – undo
5846 5846
         $key_vals_in_combined_pk = array();
5847 5847
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848 5848
         foreach ($key_fields as $key_field_name => $field_obj) {
5849
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5849
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5850 5850
                 return null;
5851 5851
             }
5852 5852
         }
@@ -5867,7 +5867,7 @@  discard block
 block discarded – undo
5867 5867
     {
5868 5868
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869 5869
         foreach ($keys_it_should_have as $key) {
5870
-            if (! isset($key_vals[ $key ])) {
5870
+            if ( ! isset($key_vals[$key])) {
5871 5871
                 return false;
5872 5872
             }
5873 5873
         }
@@ -5900,8 +5900,8 @@  discard block
 block discarded – undo
5900 5900
         }
5901 5901
         // even copies obviously won't have the same ID, so remove the primary key
5902 5902
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
-            unset($attributes_array[ $this->primary_key_name() ]);
5903
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5904
+            unset($attributes_array[$this->primary_key_name()]);
5905 5905
         }
5906 5906
         if (isset($query_params[0])) {
5907 5907
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5923,7 +5923,7 @@  discard block
 block discarded – undo
5923 5923
      */
5924 5924
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925 5925
     {
5926
-        if (! is_array($query_params)) {
5926
+        if ( ! is_array($query_params)) {
5927 5927
             EE_Error::doing_it_wrong(
5928 5928
                 'EEM_Base::get_one_copy',
5929 5929
                 sprintf(
@@ -5973,7 +5973,7 @@  discard block
 block discarded – undo
5973 5973
      */
5974 5974
     private function _prepare_operator_for_sql($operator_supplied)
5975 5975
     {
5976
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5976
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5977 5977
             : null;
5978 5978
         if ($sql_operator) {
5979 5979
             return $sql_operator;
@@ -6064,7 +6064,7 @@  discard block
 block discarded – undo
6064 6064
         $objs = $this->get_all($query_params);
6065 6065
         $names = array();
6066 6066
         foreach ($objs as $obj) {
6067
-            $names[ $obj->ID() ] = $obj->name();
6067
+            $names[$obj->ID()] = $obj->name();
6068 6068
         }
6069 6069
         return $names;
6070 6070
     }
@@ -6085,7 +6085,7 @@  discard block
 block discarded – undo
6085 6085
      */
6086 6086
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087 6087
     {
6088
-        if (! $this->has_primary_key_field()) {
6088
+        if ( ! $this->has_primary_key_field()) {
6089 6089
             if (WP_DEBUG) {
6090 6090
                 EE_Error::add_error(
6091 6091
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6098,7 +6098,7 @@  discard block
 block discarded – undo
6098 6098
         $IDs = array();
6099 6099
         foreach ($model_objects as $model_object) {
6100 6100
             $id = $model_object->ID();
6101
-            if (! $id) {
6101
+            if ( ! $id) {
6102 6102
                 if ($filter_out_empty_ids) {
6103 6103
                     continue;
6104 6104
                 }
@@ -6149,22 +6149,22 @@  discard block
 block discarded – undo
6149 6149
         EEM_Base::verify_is_valid_cap_context($context);
6150 6150
         // check if we ought to run the restriction generator first
6151 6151
         if (
6152
-            isset($this->_cap_restriction_generators[ $context ])
6153
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6152
+            isset($this->_cap_restriction_generators[$context])
6153
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6154
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6155 6155
         ) {
6156
-            $this->_cap_restrictions[ $context ] = array_merge(
6157
-                $this->_cap_restrictions[ $context ],
6158
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6156
+            $this->_cap_restrictions[$context] = array_merge(
6157
+                $this->_cap_restrictions[$context],
6158
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6159 6159
             );
6160 6160
         }
6161 6161
         // and make sure we've finalized the construction of each restriction
6162
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6162
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6163 6163
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164 6164
                 $where_conditions_obj->_finalize_construct($this);
6165 6165
             }
6166 6166
         }
6167
-        return $this->_cap_restrictions[ $context ];
6167
+        return $this->_cap_restrictions[$context];
6168 6168
     }
6169 6169
 
6170 6170
 
@@ -6196,9 +6196,9 @@  discard block
 block discarded – undo
6196 6196
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197 6197
             if (
6198 6198
                 ! EE_Capabilities::instance()
6199
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6199
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6200 6200
             ) {
6201
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6201
+                $missing_caps[$cap] = $restriction_if_no_cap;
6202 6202
             }
6203 6203
         }
6204 6204
         return $missing_caps;
@@ -6233,8 +6233,8 @@  discard block
 block discarded – undo
6233 6233
     public function cap_action_for_context($context)
6234 6234
     {
6235 6235
         $mapping = $this->cap_contexts_to_cap_action_map();
6236
-        if (isset($mapping[ $context ])) {
6237
-            return $mapping[ $context ];
6236
+        if (isset($mapping[$context])) {
6237
+            return $mapping[$context];
6238 6238
         }
6239 6239
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240 6240
             return $action;
@@ -6352,7 +6352,7 @@  discard block
 block discarded – undo
6352 6352
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353 6353
             if (
6354 6354
                 $query_param_key === $logic_query_param_key
6355
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6355
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6356 6356
             ) {
6357 6357
                 return true;
6358 6358
             }
@@ -6405,7 +6405,7 @@  discard block
 block discarded – undo
6405 6405
         if ($password_field instanceof EE_Password_Field) {
6406 6406
             $field_names = $password_field->protectedFields();
6407 6407
             foreach ($field_names as $field_name) {
6408
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6408
+                $fields[$field_name] = $this->field_settings_for($field_name);
6409 6409
             }
6410 6410
         }
6411 6411
         return $fields;
@@ -6430,7 +6430,7 @@  discard block
 block discarded – undo
6430 6430
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431 6431
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432 6432
         }
6433
-        if (!is_array($model_obj_or_fields_n_values)) {
6433
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6434 6434
             throw new UnexpectedEntityException(
6435 6435
                 $model_obj_or_fields_n_values,
6436 6436
                 'EE_Base_Class',
@@ -6505,7 +6505,7 @@  discard block
 block discarded – undo
6505 6505
                 )
6506 6506
             );
6507 6507
         }
6508
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6508
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6509 6509
     }
6510 6510
 
6511 6511
     /**
Please login to merge, or discard this patch.
core/db_models/EEM_Soft_Delete_Base.model.php 2 patches
Indentation   +367 added lines, -367 removed lines patch added patch discarded remove patch
@@ -28,371 +28,371 @@
 block discarded – undo
28 28
  */
29 29
 abstract class EEM_Soft_Delete_Base extends EEM_Base
30 30
 {
31
-    /**
32
-     * @param null $timezone
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
-            $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
-        }
40
-        parent::__construct($timezone);
41
-    }
42
-
43
-
44
-    /**
45
-     * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
-     *
47
-     * @return string
48
-     * @throws EE_Error
49
-     */
50
-    public function deleted_field_name()
51
-    {
52
-        $field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
-        if ($field) {
54
-            return $field->get_name();
55
-        } else {
56
-            throw new EE_Error(
57
-                sprintf(
58
-                    esc_html__(
59
-                        'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
60
-                        'event_espresso'
61
-                    ),
62
-                    get_class($this),
63
-                    get_class($this)
64
-                )
65
-            );
66
-        }
67
-    }
68
-
69
-
70
-    /**
71
-     * Gets one item that's been deleted, according to $query_params
72
-     *
73
-     * @param array $query_params
74
-     * @return EE_Soft_Delete_Base_Class
75
-     * @throws EE_Error
76
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
77
-     */
78
-    public function get_one_deleted($query_params = [])
79
-    {
80
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
81
-        return $this->get_one($query_params);
82
-    }
83
-
84
-
85
-    /**
86
-     * Gets one item from the DB, regardless of whether it's been soft-deleted or not
87
-     *
88
-     * @param array $query_params like EEM_base::get_all's $query_params
89
-     * @return EE_Soft_Delete_Base_Class
90
-     * @throws EE_Error
91
-     */
92
-    public function get_one_deleted_or_undeleted($query_params = [])
93
-    {
94
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
95
-        return $this->get_one($query_params);
96
-    }
97
-
98
-
99
-    /**
100
-     * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
101
-     *
102
-     * @param int|string $id
103
-     * @return EE_Soft_Delete_Base_Class
104
-     * @throws EE_Error
105
-     */
106
-    public function get_one_by_ID_but_ignore_deleted($id)
107
-    {
108
-        return $this->get_one(
109
-            $this->alter_query_params_to_restrict_by_ID(
110
-                $id,
111
-                ['default_where_conditions' => 'default']
112
-            )
113
-        );
114
-    }
115
-
116
-
117
-    /**
118
-     * Counts all the deleted/trashed items
119
-     *
120
-     * @param array  $query_params
121
-     * @param string $field_to_count
122
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
123
-     *                             that by the setting $distinct to TRUE;
124
-     * @return int
125
-     * @throws EE_Error
126
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
127
-     */
128
-    public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
129
-    {
130
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
131
-        return $this->count($query_params, $field_to_count, $distinct);
132
-    }
133
-
134
-
135
-    /**
136
-     * Alters the query params so that only trashed/soft-deleted items are considered
137
-     *
138
-     * @param array $query_params
139
-     * @return array
140
-     * @throws EE_Error
141
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
-     */
143
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
144
-    {
145
-        $deletedFlagFieldName                     = $this->deleted_field_name();
146
-        $query_params[0][ $deletedFlagFieldName ] = true;
147
-        return $query_params;
148
-    }
149
-
150
-
151
-    /**
152
-     * Alters the query params so that only trashed/soft-deleted items are considered
153
-     *
154
-     * @param array $query_params
155
-     * @return array
156
-     * @throws EE_Error
157
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
-     */
159
-    public function alter_query_params_so_only_trashed_items_included($query_params)
160
-    {
161
-        return $this->_alter_query_params_so_only_trashed_items_included($query_params);
162
-    }
163
-
164
-
165
-    /**
166
-     * Alters the query params so each item's deleted status is ignored.
167
-     *
168
-     * @param array $query_params
169
-     * @return array
170
-     */
171
-    public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = [])
172
-    {
173
-        return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
174
-    }
175
-
176
-
177
-    /**
178
-     * Alters the query params so each item's deleted status is ignored.
179
-     *
180
-     * @param array $query_params
181
-     * @return array
182
-     */
183
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184
-    {
185
-        if (! isset($query_params['default_where_conditions'])) {
186
-            $query_params['default_where_conditions'] = 'minimum';
187
-        }
188
-        return $query_params;
189
-    }
190
-
191
-
192
-    /**
193
-     * Counts all deleted and undeleted items
194
-     *
195
-     * @param array  $query_params
196
-     * @param string $field_to_count
197
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
198
-     *                             that by the setting $distinct to TRUE;
199
-     * @return int
200
-     * @throws EE_Error
201
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
202
-     */
203
-    public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
204
-    {
205
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
206
-        return $this->count($query_params, $field_to_count, $distinct);
207
-    }
208
-
209
-
210
-    /**
211
-     * Sum all the deleted items.
212
-     *
213
-     * @param array  $query_params
214
-     * @param string $field_to_sum
215
-     * @return float
216
-     * @throws EE_Error
217
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
-     */
219
-    public function sum_deleted($query_params = null, $field_to_sum = null)
220
-    {
221
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
222
-        return $this->sum($query_params, $field_to_sum);
223
-    }
224
-
225
-
226
-    /**
227
-     * Sums all the deleted and undeleted items.
228
-     *
229
-     * @param array  $query_params
230
-     * @param string $field_to_sum
231
-     * @return float
232
-     * @throws EE_Error
233
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
-     */
235
-    public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
236
-    {
237
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
238
-        return $this->sum($query_params, $field_to_sum);
239
-    }
240
-
241
-
242
-    /**
243
-     * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
244
-     * whether they've been soft-deleted or not
245
-     *
246
-     * @param array $query_params
247
-     * @return EE_Soft_Delete_Base_Class[]
248
-     * @throws EE_Error
249
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
250
-     */
251
-    public function get_all_deleted_and_undeleted($query_params = [])
252
-    {
253
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
254
-        return $this->get_all($query_params);
255
-    }
256
-
257
-
258
-    /**
259
-     * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
260
-     *
261
-     * @param array $query_params
262
-     * @return EE_Soft_Delete_Base_Class[]
263
-     * @throws EE_Error
264
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
265
-     */
266
-    public function get_all_deleted($query_params = [])
267
-    {
268
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
269
-        return $this->get_all($query_params);
270
-    }
271
-
272
-
273
-    /**
274
-     * Permanently deletes the selected rows. When selecting rows for deletion, ignores
275
-     * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
276
-     * before you can permanently delete them).
277
-     * Because this will cause a real deletion, related models may block this deletion (ie, add an error
278
-     * and abort the delete)
279
-     *
280
-     * @param array   $query_params
281
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
282
-     *                                that blocks it (ie, there' sno other data that depends on this data);
283
-     *                                if false, deletes regardless of other objects which may depend on it.
284
-     *                                Its generally advisable to always leave this as TRUE,
285
-     *                                otherwise you could easily corrupt your DB
286
-     * @return int                    number of rows deleted
287
-     * @throws EE_Error
288
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
289
-     */
290
-    public function delete_permanently($query_params, $allow_blocking = true)
291
-    {
292
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
293
-        return parent::delete_permanently($query_params, $allow_blocking);
294
-    }
295
-
296
-
297
-    /**
298
-     * Restores a particular item by its ID (primary key). Ignores the fact whether the item
299
-     * has been soft-deleted or not.
300
-     *
301
-     * @param mixed $ID int if primary key is an int, string otherwise
302
-     * @return boolean success
303
-     * @throws EE_Error
304
-     */
305
-    public function restore_by_ID($ID = false)
306
-    {
307
-        return $this->delete_or_restore_by_ID(false, $ID);
308
-    }
309
-
310
-
311
-    /**
312
-     * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
313
-     * this function will ignore whether the items have been soft-deleted or not.
314
-     *
315
-     * @param boolean $delete true for delete, false for restore
316
-     * @param mixed   $ID     int if primary key is an int, string otherwise
317
-     * @return bool
318
-     * @throws EE_Error
319
-     */
320
-    public function delete_or_restore_by_ID($delete = true, $ID = false)
321
-    {
322
-        // returns false if entity doesn't have an ID or if delete/restore action failed
323
-        return $ID && $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID));
324
-    }
325
-
326
-
327
-    /**
328
-     * Overrides parent's 'delete' method to instead do a soft delete on all rows that
329
-     * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
330
-     * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
331
-     * dependencies
332
-     *
333
-     * @param array $query_params
334
-     * @param bool  $block_deletes
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
338
-     */
339
-    public function delete($query_params = [], $block_deletes = false)
340
-    {
341
-        // no matter what, we WON'T block soft deletes.
342
-        return $this->delete_or_restore(true, $query_params);
343
-    }
344
-
345
-
346
-    /**
347
-     * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
348
-     * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
349
-     * have been soft-deleted or not.
350
-     *
351
-     * @param array $query_params
352
-     * @return bool
353
-     * @throws EE_Error
354
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
355
-     */
356
-    public function restore($query_params = [])
357
-    {
358
-        return $this->delete_or_restore(false, $query_params);
359
-    }
360
-
361
-
362
-    /**
363
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
364
-     *
365
-     * @param boolean $delete true to indicate deletion, false to indicate restoration
366
-     * @param array   $query_params
367
-     * @return boolean
368
-     * @throws EE_Error
369
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
370
-     */
371
-    public function delete_or_restore($delete = true, $query_params = [])
372
-    {
373
-        $deletedFlagFieldName = $this->deleted_field_name();
374
-        $query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
375
-        return (bool) $this->update([$deletedFlagFieldName => $delete], $query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Updates all the items of this model which match the $query params, regardless of whether
381
-     * they've been soft-deleted or not
382
-     *
383
-     * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
384
-     * @param array   $query_params            like EEM_base::get_all's $query_params
385
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
386
-     *                                         in this model's entity map according to $fields_n_values that match
387
-     *                                         $query_params. This obviously has some overhead, so you can disable it
388
-     *                                         by setting this to FALSE, but be aware that model objects being used
389
-     *                                         could get out-of-sync with the database
390
-     * @return int number of items updated
391
-     * @throws EE_Error
392
-     */
393
-    public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
394
-    {
395
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
396
-        return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
397
-    }
31
+	/**
32
+	 * @param null $timezone
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
+			$this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
+		}
40
+		parent::__construct($timezone);
41
+	}
42
+
43
+
44
+	/**
45
+	 * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
+	 *
47
+	 * @return string
48
+	 * @throws EE_Error
49
+	 */
50
+	public function deleted_field_name()
51
+	{
52
+		$field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
+		if ($field) {
54
+			return $field->get_name();
55
+		} else {
56
+			throw new EE_Error(
57
+				sprintf(
58
+					esc_html__(
59
+						'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
60
+						'event_espresso'
61
+					),
62
+					get_class($this),
63
+					get_class($this)
64
+				)
65
+			);
66
+		}
67
+	}
68
+
69
+
70
+	/**
71
+	 * Gets one item that's been deleted, according to $query_params
72
+	 *
73
+	 * @param array $query_params
74
+	 * @return EE_Soft_Delete_Base_Class
75
+	 * @throws EE_Error
76
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
77
+	 */
78
+	public function get_one_deleted($query_params = [])
79
+	{
80
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
81
+		return $this->get_one($query_params);
82
+	}
83
+
84
+
85
+	/**
86
+	 * Gets one item from the DB, regardless of whether it's been soft-deleted or not
87
+	 *
88
+	 * @param array $query_params like EEM_base::get_all's $query_params
89
+	 * @return EE_Soft_Delete_Base_Class
90
+	 * @throws EE_Error
91
+	 */
92
+	public function get_one_deleted_or_undeleted($query_params = [])
93
+	{
94
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
95
+		return $this->get_one($query_params);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
101
+	 *
102
+	 * @param int|string $id
103
+	 * @return EE_Soft_Delete_Base_Class
104
+	 * @throws EE_Error
105
+	 */
106
+	public function get_one_by_ID_but_ignore_deleted($id)
107
+	{
108
+		return $this->get_one(
109
+			$this->alter_query_params_to_restrict_by_ID(
110
+				$id,
111
+				['default_where_conditions' => 'default']
112
+			)
113
+		);
114
+	}
115
+
116
+
117
+	/**
118
+	 * Counts all the deleted/trashed items
119
+	 *
120
+	 * @param array  $query_params
121
+	 * @param string $field_to_count
122
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
123
+	 *                             that by the setting $distinct to TRUE;
124
+	 * @return int
125
+	 * @throws EE_Error
126
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
127
+	 */
128
+	public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
129
+	{
130
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
131
+		return $this->count($query_params, $field_to_count, $distinct);
132
+	}
133
+
134
+
135
+	/**
136
+	 * Alters the query params so that only trashed/soft-deleted items are considered
137
+	 *
138
+	 * @param array $query_params
139
+	 * @return array
140
+	 * @throws EE_Error
141
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
+	 */
143
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
144
+	{
145
+		$deletedFlagFieldName                     = $this->deleted_field_name();
146
+		$query_params[0][ $deletedFlagFieldName ] = true;
147
+		return $query_params;
148
+	}
149
+
150
+
151
+	/**
152
+	 * Alters the query params so that only trashed/soft-deleted items are considered
153
+	 *
154
+	 * @param array $query_params
155
+	 * @return array
156
+	 * @throws EE_Error
157
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
+	 */
159
+	public function alter_query_params_so_only_trashed_items_included($query_params)
160
+	{
161
+		return $this->_alter_query_params_so_only_trashed_items_included($query_params);
162
+	}
163
+
164
+
165
+	/**
166
+	 * Alters the query params so each item's deleted status is ignored.
167
+	 *
168
+	 * @param array $query_params
169
+	 * @return array
170
+	 */
171
+	public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = [])
172
+	{
173
+		return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
174
+	}
175
+
176
+
177
+	/**
178
+	 * Alters the query params so each item's deleted status is ignored.
179
+	 *
180
+	 * @param array $query_params
181
+	 * @return array
182
+	 */
183
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184
+	{
185
+		if (! isset($query_params['default_where_conditions'])) {
186
+			$query_params['default_where_conditions'] = 'minimum';
187
+		}
188
+		return $query_params;
189
+	}
190
+
191
+
192
+	/**
193
+	 * Counts all deleted and undeleted items
194
+	 *
195
+	 * @param array  $query_params
196
+	 * @param string $field_to_count
197
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
198
+	 *                             that by the setting $distinct to TRUE;
199
+	 * @return int
200
+	 * @throws EE_Error
201
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
202
+	 */
203
+	public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
204
+	{
205
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
206
+		return $this->count($query_params, $field_to_count, $distinct);
207
+	}
208
+
209
+
210
+	/**
211
+	 * Sum all the deleted items.
212
+	 *
213
+	 * @param array  $query_params
214
+	 * @param string $field_to_sum
215
+	 * @return float
216
+	 * @throws EE_Error
217
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
+	 */
219
+	public function sum_deleted($query_params = null, $field_to_sum = null)
220
+	{
221
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
222
+		return $this->sum($query_params, $field_to_sum);
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sums all the deleted and undeleted items.
228
+	 *
229
+	 * @param array  $query_params
230
+	 * @param string $field_to_sum
231
+	 * @return float
232
+	 * @throws EE_Error
233
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
+	 */
235
+	public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
236
+	{
237
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
238
+		return $this->sum($query_params, $field_to_sum);
239
+	}
240
+
241
+
242
+	/**
243
+	 * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
244
+	 * whether they've been soft-deleted or not
245
+	 *
246
+	 * @param array $query_params
247
+	 * @return EE_Soft_Delete_Base_Class[]
248
+	 * @throws EE_Error
249
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
250
+	 */
251
+	public function get_all_deleted_and_undeleted($query_params = [])
252
+	{
253
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
254
+		return $this->get_all($query_params);
255
+	}
256
+
257
+
258
+	/**
259
+	 * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
260
+	 *
261
+	 * @param array $query_params
262
+	 * @return EE_Soft_Delete_Base_Class[]
263
+	 * @throws EE_Error
264
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
265
+	 */
266
+	public function get_all_deleted($query_params = [])
267
+	{
268
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
269
+		return $this->get_all($query_params);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Permanently deletes the selected rows. When selecting rows for deletion, ignores
275
+	 * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
276
+	 * before you can permanently delete them).
277
+	 * Because this will cause a real deletion, related models may block this deletion (ie, add an error
278
+	 * and abort the delete)
279
+	 *
280
+	 * @param array   $query_params
281
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
282
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
283
+	 *                                if false, deletes regardless of other objects which may depend on it.
284
+	 *                                Its generally advisable to always leave this as TRUE,
285
+	 *                                otherwise you could easily corrupt your DB
286
+	 * @return int                    number of rows deleted
287
+	 * @throws EE_Error
288
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
289
+	 */
290
+	public function delete_permanently($query_params, $allow_blocking = true)
291
+	{
292
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
293
+		return parent::delete_permanently($query_params, $allow_blocking);
294
+	}
295
+
296
+
297
+	/**
298
+	 * Restores a particular item by its ID (primary key). Ignores the fact whether the item
299
+	 * has been soft-deleted or not.
300
+	 *
301
+	 * @param mixed $ID int if primary key is an int, string otherwise
302
+	 * @return boolean success
303
+	 * @throws EE_Error
304
+	 */
305
+	public function restore_by_ID($ID = false)
306
+	{
307
+		return $this->delete_or_restore_by_ID(false, $ID);
308
+	}
309
+
310
+
311
+	/**
312
+	 * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
313
+	 * this function will ignore whether the items have been soft-deleted or not.
314
+	 *
315
+	 * @param boolean $delete true for delete, false for restore
316
+	 * @param mixed   $ID     int if primary key is an int, string otherwise
317
+	 * @return bool
318
+	 * @throws EE_Error
319
+	 */
320
+	public function delete_or_restore_by_ID($delete = true, $ID = false)
321
+	{
322
+		// returns false if entity doesn't have an ID or if delete/restore action failed
323
+		return $ID && $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID));
324
+	}
325
+
326
+
327
+	/**
328
+	 * Overrides parent's 'delete' method to instead do a soft delete on all rows that
329
+	 * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
330
+	 * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
331
+	 * dependencies
332
+	 *
333
+	 * @param array $query_params
334
+	 * @param bool  $block_deletes
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
338
+	 */
339
+	public function delete($query_params = [], $block_deletes = false)
340
+	{
341
+		// no matter what, we WON'T block soft deletes.
342
+		return $this->delete_or_restore(true, $query_params);
343
+	}
344
+
345
+
346
+	/**
347
+	 * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
348
+	 * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
349
+	 * have been soft-deleted or not.
350
+	 *
351
+	 * @param array $query_params
352
+	 * @return bool
353
+	 * @throws EE_Error
354
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
355
+	 */
356
+	public function restore($query_params = [])
357
+	{
358
+		return $this->delete_or_restore(false, $query_params);
359
+	}
360
+
361
+
362
+	/**
363
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
364
+	 *
365
+	 * @param boolean $delete true to indicate deletion, false to indicate restoration
366
+	 * @param array   $query_params
367
+	 * @return boolean
368
+	 * @throws EE_Error
369
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
370
+	 */
371
+	public function delete_or_restore($delete = true, $query_params = [])
372
+	{
373
+		$deletedFlagFieldName = $this->deleted_field_name();
374
+		$query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
375
+		return (bool) $this->update([$deletedFlagFieldName => $delete], $query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Updates all the items of this model which match the $query params, regardless of whether
381
+	 * they've been soft-deleted or not
382
+	 *
383
+	 * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
384
+	 * @param array   $query_params            like EEM_base::get_all's $query_params
385
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
386
+	 *                                         in this model's entity map according to $fields_n_values that match
387
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
388
+	 *                                         by setting this to FALSE, but be aware that model objects being used
389
+	 *                                         could get out-of-sync with the database
390
+	 * @return int number of items updated
391
+	 * @throws EE_Error
392
+	 */
393
+	public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
394
+	{
395
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
396
+		return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
397
+	}
398 398
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
      */
35 35
     protected function __construct($timezone = null)
36 36
     {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
37
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38 38
             $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39 39
         }
40 40
         parent::__construct($timezone);
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
     protected function _alter_query_params_so_only_trashed_items_included($query_params)
144 144
     {
145 145
         $deletedFlagFieldName                     = $this->deleted_field_name();
146
-        $query_params[0][ $deletedFlagFieldName ] = true;
146
+        $query_params[0][$deletedFlagFieldName] = true;
147 147
         return $query_params;
148 148
     }
149 149
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
      */
183 183
     protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184 184
     {
185
-        if (! isset($query_params['default_where_conditions'])) {
185
+        if ( ! isset($query_params['default_where_conditions'])) {
186 186
             $query_params['default_where_conditions'] = 'minimum';
187 187
         }
188 188
         return $query_params;
Please login to merge, or discard this patch.
core/db_models/EEM_Change_Log.model.php 2 patches
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -9,97 +9,97 @@  discard block
 block discarded – undo
9 9
  */
10 10
 class EEM_Change_Log extends EEM_Base
11 11
 {
12
-    /**
13
-     * the related object was created log type
14
-     */
15
-    const type_create = 'create';
12
+	/**
13
+	 * the related object was created log type
14
+	 */
15
+	const type_create = 'create';
16 16
 
17
-    /**
18
-     * the related object was updated (changed, or soft-deleted)
19
-     */
20
-    const type_update = 'update';
17
+	/**
18
+	 * the related object was updated (changed, or soft-deleted)
19
+	 */
20
+	const type_update = 'update';
21 21
 
22
-    /**
23
-     * the related object was trashed/restored/deleted
24
-     */
25
-    const type_delete = 'delete';
22
+	/**
23
+	 * the related object was trashed/restored/deleted
24
+	 */
25
+	const type_delete = 'delete';
26 26
 
27
-    /**
28
-     * the related item had something worth noting happen on it, but
29
-     * only for the purposes of debugging problems
30
-     */
31
-    const type_debug = 'debug';
27
+	/**
28
+	 * the related item had something worth noting happen on it, but
29
+	 * only for the purposes of debugging problems
30
+	 */
31
+	const type_debug = 'debug';
32 32
 
33
-    /**
34
-     * the related item had an error occur on it
35
-     */
36
-    const type_error = 'error';
33
+	/**
34
+	 * the related item had an error occur on it
35
+	 */
36
+	const type_error = 'error';
37 37
 
38
-    /**
39
-     * the related item is regarding some gateway interaction, like an IPN
40
-     * or request to process a payment
41
-     */
42
-    const type_gateway = 'gateway';
38
+	/**
39
+	 * the related item is regarding some gateway interaction, like an IPN
40
+	 * or request to process a payment
41
+	 */
42
+	const type_gateway = 'gateway';
43 43
 
44
-    /**
45
-     * private instance of the EEM_Change_Log object
46
-     *
47
-     * @access private
48
-     * @var EEM_Change_Log $_instance
49
-     */
50
-    protected static $_instance = null;
44
+	/**
45
+	 * private instance of the EEM_Change_Log object
46
+	 *
47
+	 * @access private
48
+	 * @var EEM_Change_Log $_instance
49
+	 */
50
+	protected static $_instance = null;
51 51
 
52 52
 
53
-    /**
54
-     * constructor
55
-     *
56
-     * @access protected
57
-     * @param null $timezone
58
-     * @throws EE_Error
59
-     */
60
-    protected function __construct($timezone = null)
61
-    {
62
-        $this->singular_item       = esc_html__('Log', 'event_espresso');
63
-        $this->plural_item         = esc_html__('Logs', 'event_espresso');
64
-        $this->_tables             = [
65
-            'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
-        ];
67
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
-        $this->_fields             = [
69
-            'Log' => [
70
-                'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
-                'LOG_time'    => new EE_Datetime_Field(
72
-                    'LOG_time',
73
-                    esc_html__("Log Time", 'event_espresso'),
74
-                    false,
75
-                    EE_Datetime_Field::now
76
-                ),
77
-                'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
-                    'OBJ_ID',
79
-                    esc_html__("Object ID (int or string)", 'event_espresso'),
80
-                    true,
81
-                    null,
82
-                    $models_this_can_attach_to
83
-                ),
84
-                'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
-                    'OBJ_type',
86
-                    esc_html__("Object Type", 'event_espresso'),
87
-                    true,
88
-                    null,
89
-                    $models_this_can_attach_to
90
-                ),
91
-                'LOG_type'    => new EE_Plain_Text_Field(
92
-                    'LOG_type',
93
-                    esc_html__("Type of log entry", "event_espresso"),
94
-                    false,
95
-                    self::type_debug
96
-                ),
97
-                'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
-                    'LOG_message',
99
-                    esc_html__("Log Message (body)", 'event_espresso'),
100
-                    true
101
-                ),
102
-                /*
53
+	/**
54
+	 * constructor
55
+	 *
56
+	 * @access protected
57
+	 * @param null $timezone
58
+	 * @throws EE_Error
59
+	 */
60
+	protected function __construct($timezone = null)
61
+	{
62
+		$this->singular_item       = esc_html__('Log', 'event_espresso');
63
+		$this->plural_item         = esc_html__('Logs', 'event_espresso');
64
+		$this->_tables             = [
65
+			'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
+		];
67
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
+		$this->_fields             = [
69
+			'Log' => [
70
+				'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
+				'LOG_time'    => new EE_Datetime_Field(
72
+					'LOG_time',
73
+					esc_html__("Log Time", 'event_espresso'),
74
+					false,
75
+					EE_Datetime_Field::now
76
+				),
77
+				'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
+					'OBJ_ID',
79
+					esc_html__("Object ID (int or string)", 'event_espresso'),
80
+					true,
81
+					null,
82
+					$models_this_can_attach_to
83
+				),
84
+				'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
+					'OBJ_type',
86
+					esc_html__("Object Type", 'event_espresso'),
87
+					true,
88
+					null,
89
+					$models_this_can_attach_to
90
+				),
91
+				'LOG_type'    => new EE_Plain_Text_Field(
92
+					'LOG_type',
93
+					esc_html__("Type of log entry", "event_espresso"),
94
+					false,
95
+					self::type_debug
96
+				),
97
+				'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
+					'LOG_message',
99
+					esc_html__("Log Message (body)", 'event_espresso'),
100
+					true
101
+				),
102
+				/*
103 103
                  * Note: when querying for a change log's user, the OBJ_ID and OBJ_type fields are used,
104 104
                  * not the LOG_wp_user field. E.g.,
105 105
                  * `EEM_Change_Log::instance()->get_all(array(array('WP_User.ID'=>1)))` will actually return
@@ -108,165 +108,165 @@  discard block
 block discarded – undo
108 108
                  *  If you want the latter, you can't use the model's magic joining. E.g, you would need to do
109 109
                  * `EEM_Change_Log::instance()->get_all(array(array('LOG_wp_user' => 1)))`.
110 110
                  */
111
-                'LOG_wp_user' => new EE_WP_User_Field(
112
-                    'LOG_wp_user',
113
-                    esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
-                    true
115
-                ),
116
-            ],
117
-        ];
118
-        $this->_model_relations    = [];
119
-        foreach ($models_this_can_attach_to as $model) {
120
-            if ($model != 'Change_Log') {
121
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
122
-            }
123
-        }
124
-        // use completely custom caps for this
125
-        $this->_cap_restriction_generators = false;
126
-        // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
-        foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
129
-                = new EE_Return_None_Where_Conditions();
130
-        }
131
-        parent::__construct($timezone);
132
-    }
111
+				'LOG_wp_user' => new EE_WP_User_Field(
112
+					'LOG_wp_user',
113
+					esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
+					true
115
+				),
116
+			],
117
+		];
118
+		$this->_model_relations    = [];
119
+		foreach ($models_this_can_attach_to as $model) {
120
+			if ($model != 'Change_Log') {
121
+				$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
122
+			}
123
+		}
124
+		// use completely custom caps for this
125
+		$this->_cap_restriction_generators = false;
126
+		// caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
+		foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
+			$this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
129
+				= new EE_Return_None_Where_Conditions();
130
+		}
131
+		parent::__construct($timezone);
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
137
-     * @param mixed         $message  array|string of the message you want to record
138
-     * @param EE_Base_Class $related_model_obj
139
-     * @return EE_Change_Log
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     */
143
-    public function log($log_type, $message, $related_model_obj)
144
-    {
145
-        if ($related_model_obj instanceof EE_Base_Class) {
146
-            $obj_id   = $related_model_obj->ID();
147
-            $obj_type = $related_model_obj->get_model()->get_this_model_name();
148
-        } else {
149
-            $obj_id   = null;
150
-            $obj_type = null;
151
-        }
152
-        $log = EE_Change_Log::new_instance(
153
-            [
154
-                'LOG_type'    => $log_type,
155
-                'LOG_message' => $message,
156
-                'OBJ_ID'      => $obj_id,
157
-                'OBJ_type'    => $obj_type,
158
-            ]
159
-        );
160
-        $log->save();
161
-        return $log;
162
-    }
135
+	/**
136
+	 * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
137
+	 * @param mixed         $message  array|string of the message you want to record
138
+	 * @param EE_Base_Class $related_model_obj
139
+	 * @return EE_Change_Log
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 */
143
+	public function log($log_type, $message, $related_model_obj)
144
+	{
145
+		if ($related_model_obj instanceof EE_Base_Class) {
146
+			$obj_id   = $related_model_obj->ID();
147
+			$obj_type = $related_model_obj->get_model()->get_this_model_name();
148
+		} else {
149
+			$obj_id   = null;
150
+			$obj_type = null;
151
+		}
152
+		$log = EE_Change_Log::new_instance(
153
+			[
154
+				'LOG_type'    => $log_type,
155
+				'LOG_message' => $message,
156
+				'OBJ_ID'      => $obj_id,
157
+				'OBJ_type'    => $obj_type,
158
+			]
159
+		);
160
+		$log->save();
161
+		return $log;
162
+	}
163 163
 
164 164
 
165
-    /**
166
-     * Adds a gateway log for the specified object, given its ID and type
167
-     *
168
-     * @param string $message
169
-     * @param mixed  $related_obj_id
170
-     * @param string $related_obj_type
171
-     * @return EE_Change_Log
172
-     * @throws ReflectionException
173
-     * @throws EE_Error
174
-     */
175
-    public function gateway_log($message, $related_obj_id, $related_obj_type)
176
-    {
177
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
178
-            throw new EE_Error(
179
-                sprintf(
180
-                    esc_html__(
181
-                        "'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
182
-                        "event_espresso"
183
-                    ),
184
-                    $related_obj_type
185
-                )
186
-            );
187
-        }
188
-        $log = EE_Change_Log::new_instance(
189
-            [
190
-                'LOG_type'    => EEM_Change_Log::type_gateway,
191
-                'LOG_message' => $message,
192
-                'OBJ_ID'      => $related_obj_id,
193
-                'OBJ_type'    => $related_obj_type,
194
-            ]
195
-        );
196
-        $log->save();
197
-        return $log;
198
-    }
165
+	/**
166
+	 * Adds a gateway log for the specified object, given its ID and type
167
+	 *
168
+	 * @param string $message
169
+	 * @param mixed  $related_obj_id
170
+	 * @param string $related_obj_type
171
+	 * @return EE_Change_Log
172
+	 * @throws ReflectionException
173
+	 * @throws EE_Error
174
+	 */
175
+	public function gateway_log($message, $related_obj_id, $related_obj_type)
176
+	{
177
+		if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
178
+			throw new EE_Error(
179
+				sprintf(
180
+					esc_html__(
181
+						"'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
182
+						"event_espresso"
183
+					),
184
+					$related_obj_type
185
+				)
186
+			);
187
+		}
188
+		$log = EE_Change_Log::new_instance(
189
+			[
190
+				'LOG_type'    => EEM_Change_Log::type_gateway,
191
+				'LOG_message' => $message,
192
+				'OBJ_ID'      => $related_obj_id,
193
+				'OBJ_type'    => $related_obj_type,
194
+			]
195
+		);
196
+		$log->save();
197
+		return $log;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
203
-     *
204
-     * @param array $query_params
205
-     * @return array of arrays
206
-     * @throws EE_Error
207
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
208
-     */
209
-    public function get_all_efficiently($query_params)
210
-    {
211
-        return $this->_get_all_wpdb_results($query_params);
212
-    }
201
+	/**
202
+	 * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
203
+	 *
204
+	 * @param array $query_params
205
+	 * @return array of arrays
206
+	 * @throws EE_Error
207
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
208
+	 */
209
+	public function get_all_efficiently($query_params)
210
+	{
211
+		return $this->_get_all_wpdb_results($query_params);
212
+	}
213 213
 
214 214
 
215
-    /**
216
-     * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
217
-     * models after this, they may be out-of-sync with the database
218
-     *
219
-     * @param DateTime $datetime
220
-     * @return false|int
221
-     * @throws EE_Error
222
-     */
223
-    public function delete_gateway_logs_older_than(DateTime $datetime)
224
-    {
225
-        global $wpdb;
226
-        return $wpdb->query(
227
-            $wpdb->prepare(
228
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
229
-                EEM_Change_Log::type_gateway,
230
-                $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231
-            )
232
-        );
233
-    }
215
+	/**
216
+	 * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
217
+	 * models after this, they may be out-of-sync with the database
218
+	 *
219
+	 * @param DateTime $datetime
220
+	 * @return false|int
221
+	 * @throws EE_Error
222
+	 */
223
+	public function delete_gateway_logs_older_than(DateTime $datetime)
224
+	{
225
+		global $wpdb;
226
+		return $wpdb->query(
227
+			$wpdb->prepare(
228
+				'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
229
+				EEM_Change_Log::type_gateway,
230
+				$datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231
+			)
232
+		);
233
+	}
234 234
 
235 235
 
236
-    /**
237
-     * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
238
-     * map vai the given filter.
239
-     *
240
-     * @return array
241
-     */
242
-    public static function get_pretty_label_map_for_registered_types()
243
-    {
244
-        return apply_filters(
245
-            'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
246
-            [
247
-                self::type_create  => esc_html__("Create", "event_espresso"),
248
-                self::type_update  => esc_html__("Update", "event_espresso"),
249
-                self::type_delete  => esc_html__("Delete", "event_espresso"),
250
-                self::type_debug   => esc_html__("Debug", "event_espresso"),
251
-                self::type_error   => esc_html__("Error", "event_espresso"),
252
-                self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso'),
253
-            ]
254
-        );
255
-    }
236
+	/**
237
+	 * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
238
+	 * map vai the given filter.
239
+	 *
240
+	 * @return array
241
+	 */
242
+	public static function get_pretty_label_map_for_registered_types()
243
+	{
244
+		return apply_filters(
245
+			'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
246
+			[
247
+				self::type_create  => esc_html__("Create", "event_espresso"),
248
+				self::type_update  => esc_html__("Update", "event_espresso"),
249
+				self::type_delete  => esc_html__("Delete", "event_espresso"),
250
+				self::type_debug   => esc_html__("Debug", "event_espresso"),
251
+				self::type_error   => esc_html__("Error", "event_espresso"),
252
+				self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso'),
253
+			]
254
+		);
255
+	}
256 256
 
257 257
 
258
-    /**
259
-     * Return the pretty (localized) label for the given log type identifier.
260
-     *
261
-     * @param string $type_identifier
262
-     * @return string
263
-     */
264
-    public static function get_pretty_label_for_type($type_identifier)
265
-    {
266
-        $type_identifier_map = self::get_pretty_label_map_for_registered_types();
267
-        // we fallback to the incoming type identifier if there is no localized label for it.
268
-        return isset($type_identifier_map[ $type_identifier ])
269
-            ? $type_identifier_map[ $type_identifier ]
270
-            : $type_identifier;
271
-    }
258
+	/**
259
+	 * Return the pretty (localized) label for the given log type identifier.
260
+	 *
261
+	 * @param string $type_identifier
262
+	 * @return string
263
+	 */
264
+	public static function get_pretty_label_for_type($type_identifier)
265
+	{
266
+		$type_identifier_map = self::get_pretty_label_map_for_registered_types();
267
+		// we fallback to the incoming type identifier if there is no localized label for it.
268
+		return isset($type_identifier_map[ $type_identifier ])
269
+			? $type_identifier_map[ $type_identifier ]
270
+			: $type_identifier;
271
+	}
272 272
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -115,17 +115,17 @@  discard block
 block discarded – undo
115 115
                 ),
116 116
             ],
117 117
         ];
118
-        $this->_model_relations    = [];
118
+        $this->_model_relations = [];
119 119
         foreach ($models_this_can_attach_to as $model) {
120 120
             if ($model != 'Change_Log') {
121
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
121
+                $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
122 122
             }
123 123
         }
124 124
         // use completely custom caps for this
125 125
         $this->_cap_restriction_generators = false;
126 126
         // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127 127
         foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
128
+            $this->_cap_restrictions[$cap_context][EE_Restriction_Generator_Base::get_default_restrictions_cap()]
129 129
                 = new EE_Return_None_Where_Conditions();
130 130
         }
131 131
         parent::__construct($timezone);
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
      */
175 175
     public function gateway_log($message, $related_obj_id, $related_obj_type)
176 176
     {
177
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
177
+        if ( ! EE_Registry::instance()->is_model_name($related_obj_type)) {
178 178
             throw new EE_Error(
179 179
                 sprintf(
180 180
                     esc_html__(
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
         global $wpdb;
226 226
         return $wpdb->query(
227 227
             $wpdb->prepare(
228
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
228
+                'DELETE FROM '.$this->table().' WHERE LOG_type = %s AND LOG_time < %s',
229 229
                 EEM_Change_Log::type_gateway,
230 230
                 $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231 231
             )
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
     {
266 266
         $type_identifier_map = self::get_pretty_label_map_for_registered_types();
267 267
         // we fallback to the incoming type identifier if there is no localized label for it.
268
-        return isset($type_identifier_map[ $type_identifier ])
269
-            ? $type_identifier_map[ $type_identifier ]
268
+        return isset($type_identifier_map[$type_identifier])
269
+            ? $type_identifier_map[$type_identifier]
270 270
             : $type_identifier;
271 271
     }
272 272
 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/ExecuteBatchDeletion.php 2 patches
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -25,172 +25,172 @@
 block discarded – undo
25 25
  */
26 26
 class ExecuteBatchDeletion extends JobHandler
27 27
 {
28
-    /**
29
-     * @var NodeGroupDao
30
-     */
31
-    protected $model_obj_node_group_persister;
28
+	/**
29
+	 * @var NodeGroupDao
30
+	 */
31
+	protected $model_obj_node_group_persister;
32 32
 
33 33
 
34
-    public function __construct(NodeGroupDao $model_obj_node_group_persister)
35
-    {
36
-        $this->model_obj_node_group_persister = $model_obj_node_group_persister;
37
-    }
34
+	public function __construct(NodeGroupDao $model_obj_node_group_persister)
35
+	{
36
+		$this->model_obj_node_group_persister = $model_obj_node_group_persister;
37
+	}
38 38
 
39 39
 
40
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
40
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
41 41
 
42 42
 
43
-    /**
44
-     *
45
-     * @param JobParameters $job_parameters
46
-     * @return JobStepResponse
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public function create_job(JobParameters $job_parameters)
51
-    {
52
-        $deletion_job_code = $job_parameters->request_datum('deletion_job_code', null);
53
-        $roots             = $this->model_obj_node_group_persister->getModelObjNodesInGroup($deletion_job_code);
54
-        if ($roots === null) {
55
-            throw new UnexpectedEntityException(
56
-                $roots,
57
-                'array',
58
-                esc_html__(
59
-                    'The job seems to be stale. Please press the back button in your browser twice.',
60
-                    'event_espresso'
61
-                )
62
-            );
63
-        }
64
-        $models_and_ids_to_delete = [];
65
-        foreach ($roots as $root) {
66
-            if (! $root instanceof ModelObjNode) {
67
-                throw new UnexpectedEntityException($root, 'ModelObjNode');
68
-            }
69
-            $models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
70
-        }
71
-        $job_parameters->set_extra_data(
72
-            [
73
-                'models_and_ids_to_delete' => $models_and_ids_to_delete,
74
-            ]
75
-        );
76
-        // Find the job's actual size.
77
-        $job_size = 0;
78
-        foreach ($models_and_ids_to_delete as $ids) {
79
-            $job_size += count($ids);
80
-        }
81
-        $job_parameters->set_job_size($job_size);
82
-        return new JobStepResponse(
83
-            $job_parameters,
84
-            esc_html__('Beginning to delete items...', 'event_espresso')
85
-        );
86
-    }
43
+	/**
44
+	 *
45
+	 * @param JobParameters $job_parameters
46
+	 * @return JobStepResponse
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public function create_job(JobParameters $job_parameters)
51
+	{
52
+		$deletion_job_code = $job_parameters->request_datum('deletion_job_code', null);
53
+		$roots             = $this->model_obj_node_group_persister->getModelObjNodesInGroup($deletion_job_code);
54
+		if ($roots === null) {
55
+			throw new UnexpectedEntityException(
56
+				$roots,
57
+				'array',
58
+				esc_html__(
59
+					'The job seems to be stale. Please press the back button in your browser twice.',
60
+					'event_espresso'
61
+				)
62
+			);
63
+		}
64
+		$models_and_ids_to_delete = [];
65
+		foreach ($roots as $root) {
66
+			if (! $root instanceof ModelObjNode) {
67
+				throw new UnexpectedEntityException($root, 'ModelObjNode');
68
+			}
69
+			$models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
70
+		}
71
+		$job_parameters->set_extra_data(
72
+			[
73
+				'models_and_ids_to_delete' => $models_and_ids_to_delete,
74
+			]
75
+		);
76
+		// Find the job's actual size.
77
+		$job_size = 0;
78
+		foreach ($models_and_ids_to_delete as $ids) {
79
+			$job_size += count($ids);
80
+		}
81
+		$job_parameters->set_job_size($job_size);
82
+		return new JobStepResponse(
83
+			$job_parameters,
84
+			esc_html__('Beginning to delete items...', 'event_espresso')
85
+		);
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * Performs another step of the job
91
-     *
92
-     * @param JobParameters $job_parameters
93
-     * @param int           $batch_size
94
-     * @return JobStepResponse
95
-     * @throws EE_Error
96
-     * @throws ReflectionException
97
-     */
98
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
-    {
100
-        // We already have the items IDs. So deleting is really fast. Let's speed it up.
101
-        $batch_size               *= 10;
102
-        $units_processed          = 0;
103
-        $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104
-        // Build a new list of everything leftover after this request's of deletions.
105
-        $models_and_ids_remaining = [];
106
-        foreach ($models_and_ids_to_delete as $model_name => $ids_to_delete) {
107
-            // don't delete logs
108
-            if ($model_name === 'Change_Log') {
109
-                continue;
110
-            }
111
-            if ($units_processed < $batch_size) {
112
-                /** @var EEM_Base $model */
113
-                $model                    = EE_Registry::instance()->load_model($model_name);
114
-                $ids_to_delete_this_query = array_slice($ids_to_delete, 0, $batch_size - $units_processed, true);
115
-                if ($model->has_primary_key_field()) {
116
-                    $where_conditions = [
117
-                        $model->primary_key_name() => [
118
-                            'IN',
119
-                            $ids_to_delete_this_query,
120
-                        ],
121
-                    ];
122
-                } else {
123
-                    $where_conditions = [
124
-                        'OR' => [],
125
-                    ];
126
-                    foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127
-                        $keys_n_values                                                =
128
-                            $model->parse_index_primary_key_string($index_primary_key_string);
129
-                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
130
-                    }
131
-                }
132
-                // Deleting time!
133
-                // The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134
-                // two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
-                $model->delete_permanently([ $where_conditions ], false);
136
-                $units_processed += count($ids_to_delete_this_query);
137
-                $remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138
-                // If there's any more from this model, we'll do them next time.
139
-                if (count($remaining_ids) > 0) {
140
-                    $models_and_ids_remaining[ $model_name ] = $remaining_ids;
141
-                }
142
-            } else {
143
-                $models_and_ids_remaining[ $model_name ] = $ids_to_delete;
144
-            }
145
-        }
146
-        $job_parameters->mark_processed($units_processed);
147
-        // All done deleting for this request. Is there anything to do next time?
148
-        if (empty($models_and_ids_remaining)) {
149
-            $job_parameters->set_status(JobParameters::status_complete);
150
-            return new JobStepResponse(
151
-                $job_parameters,
152
-                esc_html__('Deletion complete.', 'event_espresso')
153
-            );
154
-        }
155
-        $job_parameters->add_extra_data('models_and_ids_to_delete', $models_and_ids_remaining);
156
-        return new JobStepResponse(
157
-            $job_parameters,
158
-            sprintf(
159
-                esc_html__('Deleted %d items.', 'event_espresso'),
160
-                $units_processed
161
-            )
162
-        );
163
-    }
89
+	/**
90
+	 * Performs another step of the job
91
+	 *
92
+	 * @param JobParameters $job_parameters
93
+	 * @param int           $batch_size
94
+	 * @return JobStepResponse
95
+	 * @throws EE_Error
96
+	 * @throws ReflectionException
97
+	 */
98
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
+	{
100
+		// We already have the items IDs. So deleting is really fast. Let's speed it up.
101
+		$batch_size               *= 10;
102
+		$units_processed          = 0;
103
+		$models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104
+		// Build a new list of everything leftover after this request's of deletions.
105
+		$models_and_ids_remaining = [];
106
+		foreach ($models_and_ids_to_delete as $model_name => $ids_to_delete) {
107
+			// don't delete logs
108
+			if ($model_name === 'Change_Log') {
109
+				continue;
110
+			}
111
+			if ($units_processed < $batch_size) {
112
+				/** @var EEM_Base $model */
113
+				$model                    = EE_Registry::instance()->load_model($model_name);
114
+				$ids_to_delete_this_query = array_slice($ids_to_delete, 0, $batch_size - $units_processed, true);
115
+				if ($model->has_primary_key_field()) {
116
+					$where_conditions = [
117
+						$model->primary_key_name() => [
118
+							'IN',
119
+							$ids_to_delete_this_query,
120
+						],
121
+					];
122
+				} else {
123
+					$where_conditions = [
124
+						'OR' => [],
125
+					];
126
+					foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127
+						$keys_n_values                                                =
128
+							$model->parse_index_primary_key_string($index_primary_key_string);
129
+						$where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
130
+					}
131
+				}
132
+				// Deleting time!
133
+				// The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134
+				// two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
+				$model->delete_permanently([ $where_conditions ], false);
136
+				$units_processed += count($ids_to_delete_this_query);
137
+				$remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138
+				// If there's any more from this model, we'll do them next time.
139
+				if (count($remaining_ids) > 0) {
140
+					$models_and_ids_remaining[ $model_name ] = $remaining_ids;
141
+				}
142
+			} else {
143
+				$models_and_ids_remaining[ $model_name ] = $ids_to_delete;
144
+			}
145
+		}
146
+		$job_parameters->mark_processed($units_processed);
147
+		// All done deleting for this request. Is there anything to do next time?
148
+		if (empty($models_and_ids_remaining)) {
149
+			$job_parameters->set_status(JobParameters::status_complete);
150
+			return new JobStepResponse(
151
+				$job_parameters,
152
+				esc_html__('Deletion complete.', 'event_espresso')
153
+			);
154
+		}
155
+		$job_parameters->add_extra_data('models_and_ids_to_delete', $models_and_ids_remaining);
156
+		return new JobStepResponse(
157
+			$job_parameters,
158
+			sprintf(
159
+				esc_html__('Deleted %d items.', 'event_espresso'),
160
+				$units_processed
161
+			)
162
+		);
163
+	}
164 164
 
165 165
 
166
-    /**
167
-     * Performs any clean-up logic when we know the job is completed
168
-     *
169
-     * @param JobParameters $job_parameters
170
-     * @return JobStepResponse
171
-     */
172
-    public function cleanup_job(JobParameters $job_parameters)
173
-    {
174
-        $this->model_obj_node_group_persister->deleteModelObjNodesInGroup(
175
-            $job_parameters->request_datum('deletion_job_code')
176
-        );
177
-        // For backwards compatibility with how we used to delete events, make sure we still trigger the old action.
178
-        $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
179
-        foreach ($models_and_ids_to_delete['Event'] as $event_id) {
180
-            // TrashLogger hooks into the following to create a log entry
181
-            // so we know when and who permanently deleted this event.
182
-            do_action(
183
-                'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
184
-                $event_id,
185
-                'Event',
186
-                $job_parameters
187
-            );
188
-        }
189
-        return new JobStepResponse(
190
-            $job_parameters,
191
-            esc_html__('All done', 'event_espresso')
192
-        );
193
-    }
166
+	/**
167
+	 * Performs any clean-up logic when we know the job is completed
168
+	 *
169
+	 * @param JobParameters $job_parameters
170
+	 * @return JobStepResponse
171
+	 */
172
+	public function cleanup_job(JobParameters $job_parameters)
173
+	{
174
+		$this->model_obj_node_group_persister->deleteModelObjNodesInGroup(
175
+			$job_parameters->request_datum('deletion_job_code')
176
+		);
177
+		// For backwards compatibility with how we used to delete events, make sure we still trigger the old action.
178
+		$models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
179
+		foreach ($models_and_ids_to_delete['Event'] as $event_id) {
180
+			// TrashLogger hooks into the following to create a log entry
181
+			// so we know when and who permanently deleted this event.
182
+			do_action(
183
+				'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
184
+				$event_id,
185
+				'Event',
186
+				$job_parameters
187
+			);
188
+		}
189
+		return new JobStepResponse(
190
+			$job_parameters,
191
+			esc_html__('All done', 'event_espresso')
192
+		);
193
+	}
194 194
 }
195 195
 // End of file EventDeletion.php
196 196
 // Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
         }
64 64
         $models_and_ids_to_delete = [];
65 65
         foreach ($roots as $root) {
66
-            if (! $root instanceof ModelObjNode) {
66
+            if ( ! $root instanceof ModelObjNode) {
67 67
                 throw new UnexpectedEntityException($root, 'ModelObjNode');
68 68
             }
69 69
             $models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
     public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99 99
     {
100 100
         // We already have the items IDs. So deleting is really fast. Let's speed it up.
101
-        $batch_size               *= 10;
101
+        $batch_size *= 10;
102 102
         $units_processed          = 0;
103 103
         $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104 104
         // Build a new list of everything leftover after this request's of deletions.
@@ -126,21 +126,21 @@  discard block
 block discarded – undo
126 126
                     foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127 127
                         $keys_n_values                                                =
128 128
                             $model->parse_index_primary_key_string($index_primary_key_string);
129
-                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
129
+                        $where_conditions['OR']['AND*'.$index_primary_key_string] = $keys_n_values;
130 130
                     }
131 131
                 }
132 132
                 // Deleting time!
133 133
                 // The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134 134
                 // two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
-                $model->delete_permanently([ $where_conditions ], false);
135
+                $model->delete_permanently([$where_conditions], false);
136 136
                 $units_processed += count($ids_to_delete_this_query);
137
-                $remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
137
+                $remaining_ids = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138 138
                 // If there's any more from this model, we'll do them next time.
139 139
                 if (count($remaining_ids) > 0) {
140
-                    $models_and_ids_remaining[ $model_name ] = $remaining_ids;
140
+                    $models_and_ids_remaining[$model_name] = $remaining_ids;
141 141
                 }
142 142
             } else {
143
-                $models_and_ids_remaining[ $model_name ] = $ids_to_delete;
143
+                $models_and_ids_remaining[$model_name] = $ids_to_delete;
144 144
             }
145 145
         }
146 146
         $job_parameters->mark_processed($units_processed);
Please login to merge, or discard this patch.
core/services/orm/TrashLogger.php 2 patches
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -18,127 +18,127 @@
 block discarded – undo
18 18
  */
19 19
 class TrashLogger
20 20
 {
21
-    /**
22
-     * extra meta key for tracking when entities are trashed and by who
23
-     *
24
-     * @type string
25
-     */
26
-    const EXTRA_META_KEY_ENTITY_TRASHED = 'entity-trashed';
27
-
28
-    /**
29
-     * extra meta key for tracking when entities are restored and by who
30
-     *
31
-     * @type string
32
-     */
33
-    const EXTRA_META_KEY_ENTITY_RESTORED = 'entity-restored';
34
-
35
-    /**
36
-     * extra meta key for tracking when entities are deleted and by who
37
-     *
38
-     * @type string
39
-     */
40
-    const EXTRA_META_KEY_ENTITY_DELETED = 'entity-deleted';
41
-
42
-
43
-    public function __construct()
44
-    {
45
-        add_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', [$this, 'logSoftDelete'], 10, 3);
46
-        add_action('AHEE__EE_Base_Class__delete_permanently__end', [$this, 'logHardDelete'], 10, 2);
47
-        add_action(
48
-            'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
49
-            [$this, 'logBatchDelete'],
50
-            10,
51
-            2
52
-        );
53
-    }
54
-
55
-
56
-    /**
57
-     * @param EE_Soft_Delete_Base_Class $entity
58
-     * @param bool                      $delete
59
-     * @param bool                      $result
60
-     * @throws EE_Error
61
-     * @throws ReflectionException
62
-     */
63
-    public function logSoftDelete(EE_Soft_Delete_Base_Class $entity, $delete, $result)
64
-    {
65
-        // which base meta key to use... trashed or restored?
66
-        $action = $delete
67
-            ? TrashLogger::EXTRA_META_KEY_ENTITY_TRASHED
68
-            : TrashLogger::EXTRA_META_KEY_ENTITY_RESTORED;
69
-
70
-        $entity_class = $this->getEntityClass($entity);
71
-        $this->logDelete($entity->ID(), $entity_class, $action, $result);
72
-    }
73
-
74
-
75
-    /**
76
-     * @param EE_Base_Class $entity
77
-     * @param bool          $result
78
-     * @throws EE_Error
79
-     * @throws ReflectionException
80
-     */
81
-    public function logHardDelete(EE_Base_Class $entity, $result)
82
-    {
83
-        $entity_class = $this->getEntityClass($entity);
84
-        $this->logDelete($entity->ID(), $entity_class, TrashLogger::EXTRA_META_KEY_ENTITY_DELETED, $result);
85
-    }
86
-
87
-
88
-    /**
89
-     * @param int|string $entity_ID
90
-     * @param string     $entity_type
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function logBatchDelete($entity_ID, $entity_type)
95
-    {
96
-        $entity_type = str_replace(['EE_', 'EEM_'], '', $entity_type);
97
-        $this->logDelete($entity_ID, $entity_type, TrashLogger::EXTRA_META_KEY_ENTITY_DELETED, true);
98
-    }
99
-
100
-
101
-    /**
102
-     * converts entity class like 'EE_Registration' to 'registration'
103
-     *
104
-     * @param EE_Base_Class $entity
105
-     * @return string
106
-     */
107
-    private function getEntityClass(EE_Base_Class $entity)
108
-    {
109
-        return str_replace('EE_', '', get_class($entity));
110
-    }
111
-
112
-
113
-    /**
114
-     * @param string $entity_ID
115
-     * @param string $entity_type
116
-     * @param string $action
117
-     * @param bool   $result
118
-     * @throws EE_Error
119
-     * @throws ReflectionException
120
-     */
121
-    private function logDelete($entity_ID, $entity_type, $action, $result)
122
-    {
123
-        // if trash/restore/delete was not successful, then get out
124
-        if (! $result) {
125
-            return;
126
-        }
127
-
128
-        // convert 'entity-deleted' to just 'deleted'
129
-        $action       = str_replace('entity-', '', $action);
130
-        $current_user = wp_get_current_user();
131
-        $user_name    = $current_user->ID ? $current_user->display_name : 'unknown user';
132
-        $timestamp    = date("D M j, Y @ g:i:s a", current_time('timestamp'));
133
-
134
-        $log = EE_Change_Log::new_instance(
135
-            [
136
-                'OBJ_ID'      => $entity_ID,
137
-                'OBJ_type'    => $entity_type,
138
-                'LOG_type'    => EEM_Change_Log::type_delete,
139
-                'LOG_message' => "$action by $user_name on $timestamp",
140
-            ]
141
-        );
142
-        $log->save();
143
-    }
21
+	/**
22
+	 * extra meta key for tracking when entities are trashed and by who
23
+	 *
24
+	 * @type string
25
+	 */
26
+	const EXTRA_META_KEY_ENTITY_TRASHED = 'entity-trashed';
27
+
28
+	/**
29
+	 * extra meta key for tracking when entities are restored and by who
30
+	 *
31
+	 * @type string
32
+	 */
33
+	const EXTRA_META_KEY_ENTITY_RESTORED = 'entity-restored';
34
+
35
+	/**
36
+	 * extra meta key for tracking when entities are deleted and by who
37
+	 *
38
+	 * @type string
39
+	 */
40
+	const EXTRA_META_KEY_ENTITY_DELETED = 'entity-deleted';
41
+
42
+
43
+	public function __construct()
44
+	{
45
+		add_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', [$this, 'logSoftDelete'], 10, 3);
46
+		add_action('AHEE__EE_Base_Class__delete_permanently__end', [$this, 'logHardDelete'], 10, 2);
47
+		add_action(
48
+			'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
49
+			[$this, 'logBatchDelete'],
50
+			10,
51
+			2
52
+		);
53
+	}
54
+
55
+
56
+	/**
57
+	 * @param EE_Soft_Delete_Base_Class $entity
58
+	 * @param bool                      $delete
59
+	 * @param bool                      $result
60
+	 * @throws EE_Error
61
+	 * @throws ReflectionException
62
+	 */
63
+	public function logSoftDelete(EE_Soft_Delete_Base_Class $entity, $delete, $result)
64
+	{
65
+		// which base meta key to use... trashed or restored?
66
+		$action = $delete
67
+			? TrashLogger::EXTRA_META_KEY_ENTITY_TRASHED
68
+			: TrashLogger::EXTRA_META_KEY_ENTITY_RESTORED;
69
+
70
+		$entity_class = $this->getEntityClass($entity);
71
+		$this->logDelete($entity->ID(), $entity_class, $action, $result);
72
+	}
73
+
74
+
75
+	/**
76
+	 * @param EE_Base_Class $entity
77
+	 * @param bool          $result
78
+	 * @throws EE_Error
79
+	 * @throws ReflectionException
80
+	 */
81
+	public function logHardDelete(EE_Base_Class $entity, $result)
82
+	{
83
+		$entity_class = $this->getEntityClass($entity);
84
+		$this->logDelete($entity->ID(), $entity_class, TrashLogger::EXTRA_META_KEY_ENTITY_DELETED, $result);
85
+	}
86
+
87
+
88
+	/**
89
+	 * @param int|string $entity_ID
90
+	 * @param string     $entity_type
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function logBatchDelete($entity_ID, $entity_type)
95
+	{
96
+		$entity_type = str_replace(['EE_', 'EEM_'], '', $entity_type);
97
+		$this->logDelete($entity_ID, $entity_type, TrashLogger::EXTRA_META_KEY_ENTITY_DELETED, true);
98
+	}
99
+
100
+
101
+	/**
102
+	 * converts entity class like 'EE_Registration' to 'registration'
103
+	 *
104
+	 * @param EE_Base_Class $entity
105
+	 * @return string
106
+	 */
107
+	private function getEntityClass(EE_Base_Class $entity)
108
+	{
109
+		return str_replace('EE_', '', get_class($entity));
110
+	}
111
+
112
+
113
+	/**
114
+	 * @param string $entity_ID
115
+	 * @param string $entity_type
116
+	 * @param string $action
117
+	 * @param bool   $result
118
+	 * @throws EE_Error
119
+	 * @throws ReflectionException
120
+	 */
121
+	private function logDelete($entity_ID, $entity_type, $action, $result)
122
+	{
123
+		// if trash/restore/delete was not successful, then get out
124
+		if (! $result) {
125
+			return;
126
+		}
127
+
128
+		// convert 'entity-deleted' to just 'deleted'
129
+		$action       = str_replace('entity-', '', $action);
130
+		$current_user = wp_get_current_user();
131
+		$user_name    = $current_user->ID ? $current_user->display_name : 'unknown user';
132
+		$timestamp    = date("D M j, Y @ g:i:s a", current_time('timestamp'));
133
+
134
+		$log = EE_Change_Log::new_instance(
135
+			[
136
+				'OBJ_ID'      => $entity_ID,
137
+				'OBJ_type'    => $entity_type,
138
+				'LOG_type'    => EEM_Change_Log::type_delete,
139
+				'LOG_message' => "$action by $user_name on $timestamp",
140
+			]
141
+		);
142
+		$log->save();
143
+	}
144 144
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@
 block discarded – undo
121 121
     private function logDelete($entity_ID, $entity_type, $action, $result)
122 122
     {
123 123
         // if trash/restore/delete was not successful, then get out
124
-        if (! $result) {
124
+        if ( ! $result) {
125 125
             return;
126 126
         }
127 127
 
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_Page.core.php 2 patches
Indentation   +2809 added lines, -2809 removed lines patch added patch discarded remove patch
@@ -15,2816 +15,2816 @@
 block discarded – undo
15 15
  */
16 16
 class Events_Admin_Page extends EE_Admin_Page_CPT
17 17
 {
18
-    /**
19
-     * This will hold the event object for event_details screen.
18
+	/**
19
+	 * This will hold the event object for event_details screen.
20
+	 *
21
+	 * @var EE_Event $_event
22
+	 */
23
+	protected $_event;
24
+
25
+
26
+	/**
27
+	 * This will hold the category object for category_details screen.
28
+	 *
29
+	 * @var stdClass $_category
30
+	 */
31
+	protected $_category;
32
+
33
+
34
+	/**
35
+	 * This will hold the event model instance
36
+	 *
37
+	 * @var EEM_Event $_event_model
38
+	 */
39
+	protected $_event_model;
40
+
41
+
42
+	/**
43
+	 * @var EE_Event
44
+	 */
45
+	protected $_cpt_model_obj = false;
46
+
47
+
48
+	/**
49
+	 * @var NodeGroupDao
50
+	 */
51
+	protected $model_obj_node_group_persister;
52
+
53
+
54
+	/**
55
+	 * Initialize page props for this admin page group.
56
+	 */
57
+	protected function _init_page_props()
58
+	{
59
+		$this->page_slug        = EVENTS_PG_SLUG;
60
+		$this->page_label       = EVENTS_LABEL;
61
+		$this->_admin_base_url  = EVENTS_ADMIN_URL;
62
+		$this->_admin_base_path = EVENTS_ADMIN;
63
+		$this->_cpt_model_names = [
64
+			'create_new' => 'EEM_Event',
65
+			'edit'       => 'EEM_Event',
66
+		];
67
+		$this->_cpt_edit_routes = [
68
+			'espresso_events' => 'edit',
69
+		];
70
+		add_action(
71
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
72
+			[$this, 'verify_event_edit'],
73
+			10,
74
+			2
75
+		);
76
+	}
77
+
78
+
79
+	/**
80
+	 * Sets the ajax hooks used for this admin page group.
81
+	 */
82
+	protected function _ajax_hooks()
83
+	{
84
+		add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
85
+	}
86
+
87
+
88
+	/**
89
+	 * Sets the page properties for this admin page group.
90
+	 */
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = EVENTS_LABEL;
94
+		$this->_labels           = [
95
+			'buttons'      => [
96
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
97
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
98
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
99
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
100
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
101
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
102
+			],
103
+			'editor_title' => [
104
+				'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
105
+			],
106
+			'publishbox'   => [
107
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
108
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
109
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
110
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
111
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
112
+			],
113
+		];
114
+	}
115
+
116
+
117
+	/**
118
+	 * Sets the page routes property for this admin page group.
119
+	 */
120
+	protected function _set_page_routes()
121
+	{
122
+		// load formatter helper
123
+		// load field generator helper
124
+		// is there a evt_id in the request?
125
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
126
+		$EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
127
+
128
+		$this->_page_routes = [
129
+			'default'                       => [
130
+				'func'       => [$this, '_events_overview_list_table'],
131
+				'capability' => 'ee_read_events',
132
+			],
133
+			'create_new'                    => [
134
+				'func'       => [$this, '_create_new_cpt_item'],
135
+				'capability' => 'ee_edit_events',
136
+			],
137
+			'edit'                          => [
138
+				'func'       => [$this, '_edit_cpt_item'],
139
+				'capability' => 'ee_edit_event',
140
+				'obj_id'     => $EVT_ID,
141
+			],
142
+			'copy_event'                    => [
143
+				'func'       => [$this, '_copy_events'],
144
+				'capability' => 'ee_edit_event',
145
+				'obj_id'     => $EVT_ID,
146
+				'noheader'   => true,
147
+			],
148
+			'trash_event'                   => [
149
+				'func'       => [$this, '_trash_or_restore_event'],
150
+				'args'       => ['event_status' => 'trash'],
151
+				'capability' => 'ee_delete_event',
152
+				'obj_id'     => $EVT_ID,
153
+				'noheader'   => true,
154
+			],
155
+			'trash_events'                  => [
156
+				'func'       => [$this, '_trash_or_restore_events'],
157
+				'args'       => ['event_status' => 'trash'],
158
+				'capability' => 'ee_delete_events',
159
+				'noheader'   => true,
160
+			],
161
+			'restore_event'                 => [
162
+				'func'       => [$this, '_trash_or_restore_event'],
163
+				'args'       => ['event_status' => 'draft'],
164
+				'capability' => 'ee_delete_event',
165
+				'obj_id'     => $EVT_ID,
166
+				'noheader'   => true,
167
+			],
168
+			'restore_events'                => [
169
+				'func'       => [$this, '_trash_or_restore_events'],
170
+				'args'       => ['event_status' => 'draft'],
171
+				'capability' => 'ee_delete_events',
172
+				'noheader'   => true,
173
+			],
174
+			'delete_event'                  => [
175
+				'func'       => [$this, '_delete_event'],
176
+				'capability' => 'ee_delete_event',
177
+				'obj_id'     => $EVT_ID,
178
+				'noheader'   => true,
179
+			],
180
+			'delete_events'                 => [
181
+				'func'       => [$this, '_delete_events'],
182
+				'capability' => 'ee_delete_events',
183
+				'noheader'   => true,
184
+			],
185
+			'view_report'                   => [
186
+				'func'       => [$this, '_view_report'],
187
+				'capability' => 'ee_edit_events',
188
+			],
189
+			'default_event_settings'        => [
190
+				'func'       => [$this, '_default_event_settings'],
191
+				'capability' => 'manage_options',
192
+			],
193
+			'update_default_event_settings' => [
194
+				'func'       => [$this, '_update_default_event_settings'],
195
+				'capability' => 'manage_options',
196
+				'noheader'   => true,
197
+			],
198
+			'template_settings'             => [
199
+				'func'       => [$this, '_template_settings'],
200
+				'capability' => 'manage_options',
201
+			],
202
+			// event category tab related
203
+			'add_category'                  => [
204
+				'func'       => [$this, '_category_details'],
205
+				'capability' => 'ee_edit_event_category',
206
+				'args'       => ['add'],
207
+			],
208
+			'edit_category'                 => [
209
+				'func'       => [$this, '_category_details'],
210
+				'capability' => 'ee_edit_event_category',
211
+				'args'       => ['edit'],
212
+			],
213
+			'delete_categories'             => [
214
+				'func'       => [$this, '_delete_categories'],
215
+				'capability' => 'ee_delete_event_category',
216
+				'noheader'   => true,
217
+			],
218
+			'delete_category'               => [
219
+				'func'       => [$this, '_delete_categories'],
220
+				'capability' => 'ee_delete_event_category',
221
+				'noheader'   => true,
222
+			],
223
+			'insert_category'               => [
224
+				'func'       => [$this, '_insert_or_update_category'],
225
+				'args'       => ['new_category' => true],
226
+				'capability' => 'ee_edit_event_category',
227
+				'noheader'   => true,
228
+			],
229
+			'update_category'               => [
230
+				'func'       => [$this, '_insert_or_update_category'],
231
+				'args'       => ['new_category' => false],
232
+				'capability' => 'ee_edit_event_category',
233
+				'noheader'   => true,
234
+			],
235
+			'category_list'                 => [
236
+				'func'       => [$this, '_category_list_table'],
237
+				'capability' => 'ee_manage_event_categories',
238
+			],
239
+			'preview_deletion'              => [
240
+				'func'       => [$this, 'previewDeletion'],
241
+				'capability' => 'ee_delete_events',
242
+			],
243
+			'confirm_deletion'              => [
244
+				'func'       => [$this, 'confirmDeletion'],
245
+				'capability' => 'ee_delete_events',
246
+				'noheader'   => true,
247
+			],
248
+		];
249
+	}
250
+
251
+
252
+	/**
253
+	 * Set the _page_config property for this admin page group.
254
+	 */
255
+	protected function _set_page_config()
256
+	{
257
+		$post_id            = $this->request->getRequestParam('post', 0, 'int');
258
+		$EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
259
+		$this->_page_config = [
260
+			'default'                => [
261
+				'nav'           => [
262
+					'label' => esc_html__('Overview', 'event_espresso'),
263
+					'order' => 10,
264
+				],
265
+				'list_table'    => 'Events_Admin_List_Table',
266
+				'help_tabs'     => [
267
+					'events_overview_help_tab'                       => [
268
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
269
+						'filename' => 'events_overview',
270
+					],
271
+					'events_overview_table_column_headings_help_tab' => [
272
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
273
+						'filename' => 'events_overview_table_column_headings',
274
+					],
275
+					'events_overview_filters_help_tab'               => [
276
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
277
+						'filename' => 'events_overview_filters',
278
+					],
279
+					'events_overview_view_help_tab'                  => [
280
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
281
+						'filename' => 'events_overview_views',
282
+					],
283
+					'events_overview_other_help_tab'                 => [
284
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
285
+						'filename' => 'events_overview_other',
286
+					],
287
+				],
288
+				'qtips'         => [
289
+					'EE_Event_List_Table_Tips',
290
+				],
291
+				'require_nonce' => false,
292
+			],
293
+			'create_new'             => [
294
+				'nav'           => [
295
+					'label'      => esc_html__('Add Event', 'event_espresso'),
296
+					'order'      => 5,
297
+					'persistent' => false,
298
+				],
299
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
300
+				'help_tabs'     => [
301
+					'event_editor_help_tab'                            => [
302
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
303
+						'filename' => 'event_editor',
304
+					],
305
+					'event_editor_title_richtexteditor_help_tab'       => [
306
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
307
+						'filename' => 'event_editor_title_richtexteditor',
308
+					],
309
+					'event_editor_venue_details_help_tab'              => [
310
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
311
+						'filename' => 'event_editor_venue_details',
312
+					],
313
+					'event_editor_event_datetimes_help_tab'            => [
314
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
315
+						'filename' => 'event_editor_event_datetimes',
316
+					],
317
+					'event_editor_event_tickets_help_tab'              => [
318
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
319
+						'filename' => 'event_editor_event_tickets',
320
+					],
321
+					'event_editor_event_registration_options_help_tab' => [
322
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
323
+						'filename' => 'event_editor_event_registration_options',
324
+					],
325
+					'event_editor_tags_categories_help_tab'            => [
326
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
327
+						'filename' => 'event_editor_tags_categories',
328
+					],
329
+					'event_editor_questions_registrants_help_tab'      => [
330
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
331
+						'filename' => 'event_editor_questions_registrants',
332
+					],
333
+					'event_editor_save_new_event_help_tab'             => [
334
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
335
+						'filename' => 'event_editor_save_new_event',
336
+					],
337
+					'event_editor_other_help_tab'                      => [
338
+						'title'    => esc_html__('Event Other', 'event_espresso'),
339
+						'filename' => 'event_editor_other',
340
+					],
341
+				],
342
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
343
+				'require_nonce' => false,
344
+			],
345
+			'edit'                   => [
346
+				'nav'           => [
347
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
348
+					'order'      => 5,
349
+					'persistent' => false,
350
+					'url'        => $post_id
351
+						? EE_Admin_Page::add_query_args_and_nonce(
352
+							['post' => $post_id, 'action' => 'edit'],
353
+							$this->_current_page_view_url
354
+						)
355
+						: $this->_admin_base_url,
356
+				],
357
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
358
+				'help_tabs'     => [
359
+					'event_editor_help_tab'                            => [
360
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
361
+						'filename' => 'event_editor',
362
+					],
363
+					'event_editor_title_richtexteditor_help_tab'       => [
364
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
365
+						'filename' => 'event_editor_title_richtexteditor',
366
+					],
367
+					'event_editor_venue_details_help_tab'              => [
368
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
369
+						'filename' => 'event_editor_venue_details',
370
+					],
371
+					'event_editor_event_datetimes_help_tab'            => [
372
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
373
+						'filename' => 'event_editor_event_datetimes',
374
+					],
375
+					'event_editor_event_tickets_help_tab'              => [
376
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
377
+						'filename' => 'event_editor_event_tickets',
378
+					],
379
+					'event_editor_event_registration_options_help_tab' => [
380
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
381
+						'filename' => 'event_editor_event_registration_options',
382
+					],
383
+					'event_editor_tags_categories_help_tab'            => [
384
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
385
+						'filename' => 'event_editor_tags_categories',
386
+					],
387
+					'event_editor_questions_registrants_help_tab'      => [
388
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
389
+						'filename' => 'event_editor_questions_registrants',
390
+					],
391
+					'event_editor_save_new_event_help_tab'             => [
392
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
393
+						'filename' => 'event_editor_save_new_event',
394
+					],
395
+					'event_editor_other_help_tab'                      => [
396
+						'title'    => esc_html__('Event Other', 'event_espresso'),
397
+						'filename' => 'event_editor_other',
398
+					],
399
+				],
400
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
401
+				'require_nonce' => false,
402
+			],
403
+			'default_event_settings' => [
404
+				'nav'           => [
405
+					'label' => esc_html__('Default Settings', 'event_espresso'),
406
+					'order' => 40,
407
+				],
408
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
409
+				'labels'        => [
410
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
411
+				],
412
+				'help_tabs'     => [
413
+					'default_settings_help_tab'        => [
414
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
415
+						'filename' => 'events_default_settings',
416
+					],
417
+					'default_settings_status_help_tab' => [
418
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
419
+						'filename' => 'events_default_settings_status',
420
+					],
421
+					'default_maximum_tickets_help_tab' => [
422
+						'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
423
+						'filename' => 'events_default_settings_max_tickets',
424
+					],
425
+				],
426
+				'require_nonce' => false,
427
+			],
428
+			// template settings
429
+			'template_settings'      => [
430
+				'nav'           => [
431
+					'label' => esc_html__('Templates', 'event_espresso'),
432
+					'order' => 30,
433
+				],
434
+				'metaboxes'     => $this->_default_espresso_metaboxes,
435
+				'help_tabs'     => [
436
+					'general_settings_templates_help_tab' => [
437
+						'title'    => esc_html__('Templates', 'event_espresso'),
438
+						'filename' => 'general_settings_templates',
439
+					],
440
+				],
441
+				'require_nonce' => false,
442
+			],
443
+			// event category stuff
444
+			'add_category'           => [
445
+				'nav'           => [
446
+					'label'      => esc_html__('Add Category', 'event_espresso'),
447
+					'order'      => 15,
448
+					'persistent' => false,
449
+				],
450
+				'help_tabs'     => [
451
+					'add_category_help_tab' => [
452
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
453
+						'filename' => 'events_add_category',
454
+					],
455
+				],
456
+				'metaboxes'     => ['_publish_post_box'],
457
+				'require_nonce' => false,
458
+			],
459
+			'edit_category'          => [
460
+				'nav'           => [
461
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
462
+					'order'      => 15,
463
+					'persistent' => false,
464
+					'url'        => $EVT_CAT_ID
465
+						? add_query_arg(
466
+							['EVT_CAT_ID' => $EVT_CAT_ID],
467
+							$this->_current_page_view_url
468
+						)
469
+						: $this->_admin_base_url,
470
+				],
471
+				'help_tabs'     => [
472
+					'edit_category_help_tab' => [
473
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
474
+						'filename' => 'events_edit_category',
475
+					],
476
+				],
477
+				'metaboxes'     => ['_publish_post_box'],
478
+				'require_nonce' => false,
479
+			],
480
+			'category_list'          => [
481
+				'nav'           => [
482
+					'label' => esc_html__('Categories', 'event_espresso'),
483
+					'order' => 20,
484
+				],
485
+				'list_table'    => 'Event_Categories_Admin_List_Table',
486
+				'help_tabs'     => [
487
+					'events_categories_help_tab'                       => [
488
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
489
+						'filename' => 'events_categories',
490
+					],
491
+					'events_categories_table_column_headings_help_tab' => [
492
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
493
+						'filename' => 'events_categories_table_column_headings',
494
+					],
495
+					'events_categories_view_help_tab'                  => [
496
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
497
+						'filename' => 'events_categories_views',
498
+					],
499
+					'events_categories_other_help_tab'                 => [
500
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
501
+						'filename' => 'events_categories_other',
502
+					],
503
+				],
504
+				'metaboxes'     => $this->_default_espresso_metaboxes,
505
+				'require_nonce' => false,
506
+			],
507
+			'preview_deletion'       => [
508
+				'nav'           => [
509
+					'label'      => esc_html__('Preview Deletion', 'event_espresso'),
510
+					'order'      => 15,
511
+					'persistent' => false,
512
+					'url'        => '',
513
+				],
514
+				'require_nonce' => false,
515
+			],
516
+		];
517
+	}
518
+
519
+
520
+	/**
521
+	 * Used to register any global screen options if necessary for every route in this admin page group.
522
+	 */
523
+	protected function _add_screen_options()
524
+	{
525
+	}
526
+
527
+
528
+	/**
529
+	 * Implementing the screen options for the 'default' route.
530
+	 */
531
+	protected function _add_screen_options_default()
532
+	{
533
+		$this->_per_page_screen_option();
534
+	}
535
+
536
+
537
+	/**
538
+	 * Implementing screen options for the category list route.
539
+	 */
540
+	protected function _add_screen_options_category_list()
541
+	{
542
+		$page_title              = $this->_admin_page_title;
543
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
544
+		$this->_per_page_screen_option();
545
+		$this->_admin_page_title = $page_title;
546
+	}
547
+
548
+
549
+	/**
550
+	 * Used to register any global feature pointers for the admin page group.
551
+	 */
552
+	protected function _add_feature_pointers()
553
+	{
554
+	}
555
+
556
+
557
+	/**
558
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
559
+	 */
560
+	public function load_scripts_styles()
561
+	{
562
+		wp_register_style(
563
+			'events-admin-css',
564
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
565
+			[],
566
+			EVENT_ESPRESSO_VERSION
567
+		);
568
+		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
569
+		wp_enqueue_style('events-admin-css');
570
+		wp_enqueue_style('ee-cat-admin');
571
+		// todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
572
+		// registers for all views
573
+		// scripts
574
+		wp_register_script(
575
+			'event_editor_js',
576
+			EVENTS_ASSETS_URL . 'event_editor.js',
577
+			['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
578
+			EVENT_ESPRESSO_VERSION,
579
+			true
580
+		);
581
+	}
582
+
583
+
584
+	/**
585
+	 * Enqueuing scripts and styles specific to this view
586
+	 */
587
+	public function load_scripts_styles_create_new()
588
+	{
589
+		$this->load_scripts_styles_edit();
590
+	}
591
+
592
+
593
+	/**
594
+	 * Enqueuing scripts and styles specific to this view
595
+	 */
596
+	public function load_scripts_styles_edit()
597
+	{
598
+		// styles
599
+		wp_enqueue_style('espresso-ui-theme');
600
+		wp_register_style(
601
+			'event-editor-css',
602
+			EVENTS_ASSETS_URL . 'event-editor.css',
603
+			['ee-admin-css'],
604
+			EVENT_ESPRESSO_VERSION
605
+		);
606
+		wp_enqueue_style('event-editor-css');
607
+		// scripts
608
+		wp_register_script(
609
+			'event-datetime-metabox',
610
+			EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
611
+			['event_editor_js', 'ee-datepicker'],
612
+			EVENT_ESPRESSO_VERSION
613
+		);
614
+		wp_enqueue_script('event-datetime-metabox');
615
+	}
616
+
617
+
618
+	/**
619
+	 * Populating the _views property for the category list table view.
620
+	 */
621
+	protected function _set_list_table_views_category_list()
622
+	{
623
+		$this->_views = [
624
+			'all' => [
625
+				'slug'        => 'all',
626
+				'label'       => esc_html__('All', 'event_espresso'),
627
+				'count'       => 0,
628
+				'bulk_action' => [
629
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
630
+				],
631
+			],
632
+		];
633
+	}
634
+
635
+
636
+	/**
637
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
638
+	 */
639
+	public function admin_init()
640
+	{
641
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
642
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
643
+			'event_espresso'
644
+		);
645
+	}
646
+
647
+
648
+	/**
649
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
650
+	 * group.
651
+	 */
652
+	public function admin_notices()
653
+	{
654
+	}
655
+
656
+
657
+	/**
658
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
659
+	 * this admin page group.
660
+	 */
661
+	public function admin_footer_scripts()
662
+	{
663
+	}
664
+
665
+
666
+	/**
667
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
668
+	 * warning (via EE_Error::add_error());
669
+	 *
670
+	 * @param EE_Event $event Event object
671
+	 * @param string   $req_type
672
+	 * @return void
673
+	 * @throws EE_Error
674
+	 * @throws ReflectionException
675
+	 */
676
+	public function verify_event_edit($event = null, $req_type = '')
677
+	{
678
+		// don't need to do this when processing
679
+		if (! empty($req_type)) {
680
+			return;
681
+		}
682
+		// no event?
683
+		if (empty($event)) {
684
+			// set event
685
+			$event = $this->_cpt_model_obj;
686
+		}
687
+		// STILL no event?
688
+		if (! $event instanceof EE_Event) {
689
+			return;
690
+		}
691
+		$orig_status = $event->status();
692
+		// first check if event is active.
693
+		if (
694
+			$orig_status === EEM_Event::cancelled
695
+			|| $orig_status === EEM_Event::postponed
696
+			|| $event->is_expired()
697
+			|| $event->is_inactive()
698
+		) {
699
+			return;
700
+		}
701
+		// made it here so it IS active... next check that any of the tickets are sold.
702
+		if ($event->is_sold_out(true)) {
703
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
704
+				EE_Error::add_attention(
705
+					sprintf(
706
+						esc_html__(
707
+							'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.',
708
+							'event_espresso'
709
+						),
710
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
711
+					)
712
+				);
713
+			}
714
+			return;
715
+		} elseif ($orig_status === EEM_Event::sold_out) {
716
+			EE_Error::add_attention(
717
+				sprintf(
718
+					esc_html__(
719
+						'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.',
720
+						'event_espresso'
721
+					),
722
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
723
+				)
724
+			);
725
+		}
726
+		// now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
727
+		if (! $event->tickets_on_sale()) {
728
+			return;
729
+		}
730
+		// made it here so show warning
731
+		$this->_edit_event_warning();
732
+	}
733
+
734
+
735
+	/**
736
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
737
+	 * When needed, hook this into a EE_Error::add_error() notice.
738
+	 *
739
+	 * @access protected
740
+	 * @return void
741
+	 */
742
+	protected function _edit_event_warning()
743
+	{
744
+		// we don't want to add warnings during these requests
745
+		if ($this->request->getRequestParam('action') === 'editpost') {
746
+			return;
747
+		}
748
+		EE_Error::add_attention(
749
+			sprintf(
750
+				esc_html__(
751
+					'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
752
+					'event_espresso'
753
+				),
754
+				'<a class="espresso-help-tab-lnk">',
755
+				'</a>'
756
+			)
757
+		);
758
+	}
759
+
760
+
761
+	/**
762
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
763
+	 * Otherwise, do the normal logic
764
+	 *
765
+	 * @return void
766
+	 * @throws EE_Error
767
+	 */
768
+	protected function _create_new_cpt_item()
769
+	{
770
+		$has_timezone_string = get_option('timezone_string');
771
+		// only nag them about setting their timezone if it's their first event, and they haven't already done it
772
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
773
+			EE_Error::add_attention(
774
+				sprintf(
775
+					esc_html__(
776
+						'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',
777
+						'event_espresso'
778
+					),
779
+					'<br>',
780
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
781
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
782
+					. '</select>',
783
+					'<button class="button button-secondary timezone-submit">',
784
+					'</button><span class="spinner"></span>'
785
+				),
786
+				__FILE__,
787
+				__FUNCTION__,
788
+				__LINE__
789
+			);
790
+		}
791
+		parent::_create_new_cpt_item();
792
+	}
793
+
794
+
795
+	/**
796
+	 * Sets the _views property for the default route in this admin page group.
797
+	 */
798
+	protected function _set_list_table_views_default()
799
+	{
800
+		$this->_views = [
801
+			'all'   => [
802
+				'slug'        => 'all',
803
+				'label'       => esc_html__('View All Events', 'event_espresso'),
804
+				'count'       => 0,
805
+				'bulk_action' => [
806
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
807
+				],
808
+			],
809
+			'draft' => [
810
+				'slug'        => 'draft',
811
+				'label'       => esc_html__('Draft', 'event_espresso'),
812
+				'count'       => 0,
813
+				'bulk_action' => [
814
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
815
+				],
816
+			],
817
+		];
818
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
819
+			$this->_views['trash'] = [
820
+				'slug'        => 'trash',
821
+				'label'       => esc_html__('Trash', 'event_espresso'),
822
+				'count'       => 0,
823
+				'bulk_action' => [
824
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
825
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
826
+				],
827
+			];
828
+		}
829
+	}
830
+
831
+
832
+	/**
833
+	 * Provides the legend item array for the default list table view.
834
+	 *
835
+	 * @return array
836
+	 * @throws EE_Error
837
+	 * @throws EE_Error
838
+	 */
839
+	protected function _event_legend_items()
840
+	{
841
+		$items    = [
842
+			'view_details'   => [
843
+				'class' => 'dashicons dashicons-search',
844
+				'desc'  => esc_html__('View Event', 'event_espresso'),
845
+			],
846
+			'edit_event'     => [
847
+				'class' => 'ee-icon ee-icon-calendar-edit',
848
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
849
+			],
850
+			'view_attendees' => [
851
+				'class' => 'dashicons dashicons-groups',
852
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
853
+			],
854
+		];
855
+		$items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
856
+		$statuses = [
857
+			'sold_out_status'  => [
858
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
859
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
860
+			],
861
+			'active_status'    => [
862
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
863
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
864
+			],
865
+			'upcoming_status'  => [
866
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
867
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
868
+			],
869
+			'postponed_status' => [
870
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
871
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
872
+			],
873
+			'cancelled_status' => [
874
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
875
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
876
+			],
877
+			'expired_status'   => [
878
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
879
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
880
+			],
881
+			'inactive_status'  => [
882
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
883
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
884
+			],
885
+		];
886
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
887
+		return array_merge($items, $statuses);
888
+	}
889
+
890
+
891
+	/**
892
+	 * @return EEM_Event
893
+	 * @throws EE_Error
894
+	 * @throws ReflectionException
895
+	 */
896
+	private function _event_model()
897
+	{
898
+		if (! $this->_event_model instanceof EEM_Event) {
899
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
900
+		}
901
+		return $this->_event_model;
902
+	}
903
+
904
+
905
+	/**
906
+	 * Adds extra buttons to the WP CPT permalink field row.
907
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
908
+	 *
909
+	 * @param string $return    the current html
910
+	 * @param int    $id        the post id for the page
911
+	 * @param string $new_title What the title is
912
+	 * @param string $new_slug  what the slug is
913
+	 * @return string            The new html string for the permalink area
914
+	 */
915
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
916
+	{
917
+		// make sure this is only when editing
918
+		if (! empty($id)) {
919
+			$post   = get_post($id);
920
+			$return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
921
+					   . esc_html__('Shortcode', 'event_espresso')
922
+					   . '</a> ';
923
+			$return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
924
+					   . $post->ID
925
+					   . ']">';
926
+		}
927
+		return $return;
928
+	}
929
+
930
+
931
+	/**
932
+	 * _events_overview_list_table
933
+	 * This contains the logic for showing the events_overview list
934
+	 *
935
+	 * @access protected
936
+	 * @return void
937
+	 * @throws EE_Error
938
+	 */
939
+	protected function _events_overview_list_table()
940
+	{
941
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
942
+		$this->_template_args['after_list_table']                           =
943
+			! empty($this->_template_args['after_list_table'])
944
+				? (array) $this->_template_args['after_list_table']
945
+				: [];
946
+		$this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
947
+			. EEH_Template::get_button_or_link(
948
+				get_post_type_archive_link('espresso_events'),
949
+				esc_html__("View Event Archive Page", "event_espresso"),
950
+				'button'
951
+			);
952
+		$this->_template_args['after_list_table']['legend']                 = $this->_display_legend(
953
+			$this->_event_legend_items()
954
+		);
955
+		$this->_admin_page_title                                            .= ' ' . $this->get_action_link_or_button(
956
+			'create_new',
957
+			'add',
958
+			[],
959
+			'add-new-h2'
960
+		);
961
+		$this->display_admin_list_table_page_with_no_sidebar();
962
+	}
963
+
964
+
965
+	/**
966
+	 * this allows for extra misc actions in the default WP publish box
967
+	 *
968
+	 * @return void
969
+	 * @throws EE_Error
970
+	 * @throws ReflectionException
971
+	 */
972
+	public function extra_misc_actions_publish_box()
973
+	{
974
+		$this->_generate_publish_box_extra_content();
975
+	}
976
+
977
+
978
+	/**
979
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
980
+	 * saved.
981
+	 * Typically you would use this to save any additional data.
982
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
983
+	 * ALSO very important.  When a post transitions from scheduled to published,
984
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
985
+	 * other meta saves. So MAKE sure that you handle this accordingly.
986
+	 *
987
+	 * @access protected
988
+	 * @abstract
989
+	 * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
990
+	 * @param WP_Post $post    The post object of the cpt that was saved.
991
+	 * @return void
992
+	 * @throws EE_Error
993
+	 * @throws ReflectionException
994
+	 */
995
+	protected function _insert_update_cpt_item($post_id, $post)
996
+	{
997
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
998
+			// get out we're not processing an event save.
999
+			return;
1000
+		}
1001
+
1002
+		$event_values = [
1003
+			'EVT_display_desc'                => $this->request->getRequestParam('display_desc', false, 'bool'),
1004
+			'EVT_display_ticket_selector'     => $this->request->getRequestParam(
1005
+				'display_ticket_selector',
1006
+				false,
1007
+				'bool'
1008
+			),
1009
+			'EVT_additional_limit'            => min(
1010
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1011
+				$this->request->getRequestParam('additional_limit', null, 'int')
1012
+			),
1013
+			'EVT_default_registration_status' => $this->request->getRequestParam(
1014
+				'EVT_default_registration_status',
1015
+				EE_Registry::instance()->CFG->registration->default_STS_ID
1016
+			),
1017
+
1018
+			'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1019
+			'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1020
+			'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1021
+			'EVT_external_URL'    => $this->request->getRequestParam('externalURL'),
1022
+			'EVT_phone'           => $this->request->getRequestParam('event_phone'),
1023
+		];
1024
+		// update event
1025
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1026
+		// get event_object for other metaboxes...
1027
+		// though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1028
+		// i have to setup where conditions to override the filters in the model
1029
+		// that filter out auto-draft and inherit statuses so we GET the inherit id!
1030
+		$event = $this->_event_model()->get_one(
1031
+			[
1032
+				[
1033
+					$this->_event_model()->primary_key_name() => $post_id,
1034
+					'OR'                                      => [
1035
+						'status'   => $post->post_status,
1036
+						// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1037
+						// but the returned object here has a status of "publish", so use the original post status as well
1038
+						'status*1' => $this->request->getRequestParam('original_post_status'),
1039
+					],
1040
+				],
1041
+			]
1042
+		);
1043
+		// the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1044
+		$event_update_callbacks = apply_filters(
1045
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1046
+			[
1047
+				[$this, '_default_venue_update'],
1048
+				[$this, '_default_tickets_update'],
1049
+			]
1050
+		);
1051
+		$att_success            = true;
1052
+		foreach ($event_update_callbacks as $e_callback) {
1053
+			$_success = is_callable($e_callback)
1054
+				? call_user_func($e_callback, $event, $this->request->requestParams())
1055
+				: false;
1056
+			// if ANY of these updates fail then we want the appropriate global error message
1057
+			$att_success = ! $att_success ? $att_success : $_success;
1058
+		}
1059
+		// any errors?
1060
+		if ($success && false === $att_success) {
1061
+			EE_Error::add_error(
1062
+				esc_html__(
1063
+					'Event Details saved successfully but something went wrong with saving attachments.',
1064
+					'event_espresso'
1065
+				),
1066
+				__FILE__,
1067
+				__FUNCTION__,
1068
+				__LINE__
1069
+			);
1070
+		} elseif ($success === false) {
1071
+			EE_Error::add_error(
1072
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1073
+				__FILE__,
1074
+				__FUNCTION__,
1075
+				__LINE__
1076
+			);
1077
+		}
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * @param int $post_id
1083
+	 * @param int $revision_id
1084
+	 * @throws EE_Error
1085
+	 * @throws EE_Error
1086
+	 * @throws ReflectionException
1087
+	 * @see parent::restore_item()
1088
+	 */
1089
+	protected function _restore_cpt_item($post_id, $revision_id)
1090
+	{
1091
+		// copy existing event meta to new post
1092
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1093
+		if ($post_evt instanceof EE_Event) {
1094
+			// meta revision restore
1095
+			$post_evt->restore_revision($revision_id);
1096
+			// related objs restore
1097
+			$post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1098
+		}
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * Attach the venue to the Event
1104
+	 *
1105
+	 * @param EE_Event $event Event Object to add the venue to
1106
+	 * @param array    $data  The request data from the form
1107
+	 * @return bool           Success or fail.
1108
+	 * @throws EE_Error
1109
+	 * @throws ReflectionException
1110
+	 */
1111
+	protected function _default_venue_update(EE_Event $event, $data)
1112
+	{
1113
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1114
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1115
+		$venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1116
+		// very important.  If we don't have a venue name...
1117
+		// then we'll get out because not necessary to create empty venue
1118
+		if (empty($data['venue_title'])) {
1119
+			return false;
1120
+		}
1121
+		$venue_array = [
1122
+			'VNU_wp_user'         => $event->get('EVT_wp_user'),
1123
+			'VNU_name'            => $data['venue_title'],
1124
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1125
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1126
+			'VNU_short_desc'      => ! empty($data['venue_short_description'])
1127
+				? $data['venue_short_description']
1128
+				: null,
1129
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1130
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1131
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1132
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1133
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1134
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1135
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1136
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1137
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1138
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1139
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1140
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1141
+			'status'              => 'publish',
1142
+		];
1143
+		// if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1144
+		if (! empty($venue_id)) {
1145
+			$update_where  = [$venue_model->primary_key_name() => $venue_id];
1146
+			$rows_affected = $venue_model->update($venue_array, [$update_where]);
1147
+			// 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.
1148
+			$event->_add_relation_to($venue_id, 'Venue');
1149
+			return $rows_affected > 0;
1150
+		}
1151
+		// we insert the venue
1152
+		$venue_id = $venue_model->insert($venue_array);
1153
+		$event->_add_relation_to($venue_id, 'Venue');
1154
+		return ! empty($venue_id);
1155
+		// when we have the ancestor come in it's already been handled by the revision save.
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1161
+	 *
1162
+	 * @param EE_Event $event The Event object we're attaching data to
1163
+	 * @param array    $data  The request data from the form
1164
+	 * @return array
1165
+	 * @throws EE_Error
1166
+	 * @throws ReflectionException
1167
+	 * @throws Exception
1168
+	 */
1169
+	protected function _default_tickets_update(EE_Event $event, $data)
1170
+	{
1171
+		$datetime       = null;
1172
+		$saved_tickets  = [];
1173
+		$event_timezone = $event->get_timezone();
1174
+		$date_formats   = ['Y-m-d', 'h:i a'];
1175
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1176
+			// trim all values to ensure any excess whitespace is removed.
1177
+			$datetime_data                = array_map('trim', $datetime_data);
1178
+			$datetime_data['DTT_EVT_end'] =
1179
+				isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1180
+					? $datetime_data['DTT_EVT_end']
1181
+					: $datetime_data['DTT_EVT_start'];
1182
+			$datetime_values              = [
1183
+				'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1184
+				'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1185
+				'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1186
+				'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1187
+				'DTT_order'     => $row,
1188
+			];
1189
+			// if we have an id then let's get existing object first and then set the new values.
1190
+			//  Otherwise we instantiate a new object for save.
1191
+			if (! empty($datetime_data['DTT_ID'])) {
1192
+				$datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1193
+				if (! $datetime instanceof EE_Datetime) {
1194
+					throw new RuntimeException(
1195
+						sprintf(
1196
+							esc_html__(
1197
+								'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1198
+								'event_espresso'
1199
+							),
1200
+							$datetime_data['DTT_ID']
1201
+						)
1202
+					);
1203
+				}
1204
+				$datetime->set_date_format($date_formats[0]);
1205
+				$datetime->set_time_format($date_formats[1]);
1206
+				foreach ($datetime_values as $field => $value) {
1207
+					$datetime->set($field, $value);
1208
+				}
1209
+			} else {
1210
+				$datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1211
+			}
1212
+			if (! $datetime instanceof EE_Datetime) {
1213
+				throw new RuntimeException(
1214
+					sprintf(
1215
+						esc_html__(
1216
+							'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1217
+							'event_espresso'
1218
+						),
1219
+						print_r($datetime_values, true)
1220
+					)
1221
+				);
1222
+			}
1223
+			// before going any further make sure our dates are setup correctly
1224
+			// so that the end date is always equal or greater than the start date.
1225
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1226
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1227
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1228
+			}
1229
+			$datetime->save();
1230
+			$event->_add_relation_to($datetime, 'Datetime');
1231
+		}
1232
+		// no datetimes get deleted so we don't do any of that logic here.
1233
+		// update tickets next
1234
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1235
+
1236
+		// set up some default start and end dates in case those are not present in the incoming data
1237
+		$default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1238
+		$default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1239
+		// use the start date of the first datetime for the end date
1240
+		$first_datetime   = $event->first_datetime();
1241
+		$default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1242
+
1243
+		// now process the incoming data
1244
+		foreach ($data['edit_tickets'] as $row => $ticket_data) {
1245
+			$update_prices = false;
1246
+			$ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1247
+				? $data['edit_prices'][ $row ][1]['PRC_amount']
1248
+				: 0;
1249
+			// trim inputs to ensure any excess whitespace is removed.
1250
+			$ticket_data   = array_map('trim', $ticket_data);
1251
+			$ticket_values = [
1252
+				'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1253
+				'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1254
+				'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1255
+				'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1256
+				'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1257
+					? $ticket_data['TKT_start_date']
1258
+					: $default_start_date,
1259
+				'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1260
+					? $ticket_data['TKT_end_date']
1261
+					: $default_end_date,
1262
+				'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1263
+									 || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1264
+					? $ticket_data['TKT_qty']
1265
+					: EE_INF,
1266
+				'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1267
+									 || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1268
+					? $ticket_data['TKT_uses']
1269
+					: EE_INF,
1270
+				'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1271
+				'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1272
+				'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1273
+				'TKT_price'       => $ticket_price,
1274
+				'TKT_row'         => $row,
1275
+			];
1276
+			// if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1277
+			// which means in turn that the prices will become new prices as well.
1278
+			if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1279
+				$ticket_values['TKT_ID']         = 0;
1280
+				$ticket_values['TKT_is_default'] = 0;
1281
+				$update_prices                   = true;
1282
+			}
1283
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
1284
+			// we actually do our saves ahead of adding any relations because its entirely possible that this
1285
+			// ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1286
+			// keep in mind that if the ticket has been sold (and we have changed pricing information),
1287
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1288
+			if (! empty($ticket_data['TKT_ID'])) {
1289
+				$existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1290
+				if (! $existing_ticket instanceof EE_Ticket) {
1291
+					throw new RuntimeException(
1292
+						sprintf(
1293
+							esc_html__(
1294
+								'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1295
+								'event_espresso'
1296
+							),
1297
+							$ticket_data['TKT_ID']
1298
+						)
1299
+					);
1300
+				}
1301
+				$ticket_sold = $existing_ticket->count_related(
1302
+					'Registration',
1303
+					[
1304
+						[
1305
+							'STS_ID' => [
1306
+								'NOT IN',
1307
+								[EEM_Registration::status_id_incomplete],
1308
+							],
1309
+						],
1310
+					]
1311
+				) > 0;
1312
+				// let's just check the total price for the existing ticket and determine if it matches the new total price.
1313
+				// if they are different then we create a new ticket (if $ticket_sold)
1314
+				// if they aren't different then we go ahead and modify existing ticket.
1315
+				$create_new_ticket = $ticket_sold
1316
+									 && $ticket_price !== $existing_ticket->price()
1317
+									 && ! $existing_ticket->deleted();
1318
+				$existing_ticket->set_date_format($date_formats[0]);
1319
+				$existing_ticket->set_time_format($date_formats[1]);
1320
+				// set new values
1321
+				foreach ($ticket_values as $field => $value) {
1322
+					if ($field == 'TKT_qty') {
1323
+						$existing_ticket->set_qty($value);
1324
+					} elseif ($field == 'TKT_price') {
1325
+						$existing_ticket->set('TKT_price', $ticket_price);
1326
+					} else {
1327
+						$existing_ticket->set($field, $value);
1328
+					}
1329
+				}
1330
+				$ticket = $existing_ticket;
1331
+				// if $create_new_ticket is false then we can safely update the existing ticket.
1332
+				//  Otherwise we have to create a new ticket.
1333
+				if ($create_new_ticket) {
1334
+					// archive the old ticket first
1335
+					$existing_ticket->set('TKT_deleted', 1);
1336
+					$existing_ticket->save();
1337
+					// make sure this ticket is still recorded in our $saved_tickets
1338
+					// so we don't run it through the regular trash routine.
1339
+					$saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1340
+					// create new ticket that's a copy of the existing except,
1341
+					// (a new id of course and not archived) AND has the new TKT_price associated with it.
1342
+					$new_ticket = clone $existing_ticket;
1343
+					$new_ticket->set('TKT_ID', 0);
1344
+					$new_ticket->set('TKT_deleted', 0);
1345
+					$new_ticket->set('TKT_sold', 0);
1346
+					// now we need to make sure that $new prices are created as well and attached to new ticket.
1347
+					$update_prices = true;
1348
+					$ticket        = $new_ticket;
1349
+				}
1350
+			} else {
1351
+				// no TKT_id so a new ticket
1352
+				$ticket_values['TKT_price'] = $ticket_price;
1353
+				$ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1354
+				$update_prices              = true;
1355
+			}
1356
+			if (! $ticket instanceof EE_Ticket) {
1357
+				throw new RuntimeException(
1358
+					sprintf(
1359
+						esc_html__(
1360
+							'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1361
+							'event_espresso'
1362
+						),
1363
+						print_r($ticket_values, true)
1364
+					)
1365
+				);
1366
+			}
1367
+			// cap ticket qty by datetime reg limits
1368
+			$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1369
+			// update ticket.
1370
+			$ticket->save();
1371
+			// before going any further make sure our dates are setup correctly
1372
+			// so that the end date is always equal or greater than the start date.
1373
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1374
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1375
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1376
+				$ticket->save();
1377
+			}
1378
+			// initially let's add the ticket to the datetime
1379
+			$datetime->_add_relation_to($ticket, 'Ticket');
1380
+			$saved_tickets[ $ticket->ID() ] = $ticket;
1381
+			// add prices to ticket
1382
+			$prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1383
+				? $data['edit_prices'][ $row ]
1384
+				: [];
1385
+			$this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1386
+		}
1387
+		// however now we need to handle permanently deleting tickets via the ui.
1388
+		// Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1389
+		// However, it does allow for deleting tickets that have no tickets sold,
1390
+		// in which case we want to get rid of permanently because there is no need to save in db.
1391
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? [] : $old_tickets;
1392
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1393
+		foreach ($tickets_removed as $id) {
1394
+			$id = absint($id);
1395
+			// get the ticket for this id
1396
+			$ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1397
+			if (! $ticket_to_remove instanceof EE_Ticket) {
1398
+				continue;
1399
+			}
1400
+			// need to get all the related datetimes on this ticket and remove from every single one of them
1401
+			// (remember this process can ONLY kick off if there are NO tickets sold)
1402
+			$related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1403
+			foreach ($related_datetimes as $related_datetime) {
1404
+				$ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1405
+			}
1406
+			// need to do the same for prices (except these prices can also be deleted because again,
1407
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1408
+			$ticket_to_remove->delete_related_permanently('Price');
1409
+			// finally let's delete this ticket
1410
+			// (which should not be blocked at this point b/c we've removed all our relationships)
1411
+			$ticket_to_remove->delete_permanently();
1412
+		}
1413
+		return [$datetime, $saved_tickets];
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * This attaches a list of given prices to a ticket.
1419
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1420
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1421
+	 * price info and prices are automatically "archived" via the ticket.
1422
+	 *
1423
+	 * @access  private
1424
+	 * @param array     $prices_data Array of prices from the form.
1425
+	 * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1426
+	 * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1427
+	 * @return  void
1428
+	 * @throws EE_Error
1429
+	 * @throws ReflectionException
1430
+	 */
1431
+	private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1432
+	{
1433
+		$timezone = $ticket->get_timezone();
1434
+		foreach ($prices_data as $row => $price_data) {
1435
+			$price_values = [
1436
+				'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1437
+				'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1438
+				'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1439
+				'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1440
+				'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1441
+				'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1442
+				'PRC_order'      => $row,
1443
+			];
1444
+			if ($new_prices || empty($price_values['PRC_ID'])) {
1445
+				$price_values['PRC_ID'] = 0;
1446
+				$price                  = EE_Price::new_instance($price_values, $timezone);
1447
+			} else {
1448
+				$price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1449
+				// update this price with new values
1450
+				foreach ($price_values as $field => $new_price) {
1451
+					$price->set($field, $new_price);
1452
+				}
1453
+			}
1454
+			if (! $price instanceof EE_Price) {
1455
+				throw new RuntimeException(
1456
+					sprintf(
1457
+						esc_html__(
1458
+							'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1459
+							'event_espresso'
1460
+						),
1461
+						print_r($price_values, true)
1462
+					)
1463
+				);
1464
+			}
1465
+			$price->save();
1466
+			$ticket->_add_relation_to($price, 'Price');
1467
+		}
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Add in our autosave ajax handlers
1473
+	 *
1474
+	 */
1475
+	protected function _ee_autosave_create_new()
1476
+	{
1477
+	}
1478
+
1479
+
1480
+	/**
1481
+	 * More autosave handlers.
1482
+	 */
1483
+	protected function _ee_autosave_edit()
1484
+	{
1485
+		// TEMPORARILY EXITING CAUSE THIS IS A TODO
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * @throws EE_Error
1491
+	 * @throws ReflectionException
1492
+	 */
1493
+	private function _generate_publish_box_extra_content()
1494
+	{
1495
+		// load formatter helper
1496
+		// args for getting related registrations
1497
+		$approved_query_args        = [
1498
+			[
1499
+				'REG_deleted' => 0,
1500
+				'STS_ID'      => EEM_Registration::status_id_approved,
1501
+			],
1502
+		];
1503
+		$not_approved_query_args    = [
1504
+			[
1505
+				'REG_deleted' => 0,
1506
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1507
+			],
1508
+		];
1509
+		$pending_payment_query_args = [
1510
+			[
1511
+				'REG_deleted' => 0,
1512
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1513
+			],
1514
+		];
1515
+		// publish box
1516
+		$publish_box_extra_args = [
1517
+			'view_approved_reg_url'        => add_query_arg(
1518
+				[
1519
+					'action'      => 'default',
1520
+					'event_id'    => $this->_cpt_model_obj->ID(),
1521
+					'_reg_status' => EEM_Registration::status_id_approved,
1522
+					'use_filters' => true,
1523
+				],
1524
+				REG_ADMIN_URL
1525
+			),
1526
+			'view_not_approved_reg_url'    => add_query_arg(
1527
+				[
1528
+					'action'      => 'default',
1529
+					'event_id'    => $this->_cpt_model_obj->ID(),
1530
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1531
+					'use_filters' => true,
1532
+				],
1533
+				REG_ADMIN_URL
1534
+			),
1535
+			'view_pending_payment_reg_url' => add_query_arg(
1536
+				[
1537
+					'action'      => 'default',
1538
+					'event_id'    => $this->_cpt_model_obj->ID(),
1539
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1540
+					'use_filters' => true,
1541
+				],
1542
+				REG_ADMIN_URL
1543
+			),
1544
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1545
+				'Registration',
1546
+				$approved_query_args
1547
+			),
1548
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1549
+				'Registration',
1550
+				$not_approved_query_args
1551
+			),
1552
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1553
+				'Registration',
1554
+				$pending_payment_query_args
1555
+			),
1556
+			'misc_pub_section_class'       => apply_filters(
1557
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1558
+				'misc-pub-section'
1559
+			),
1560
+		];
1561
+		ob_start();
1562
+		do_action(
1563
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1564
+			$this->_cpt_model_obj
1565
+		);
1566
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1567
+		// load template
1568
+		EEH_Template::display_template(
1569
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1570
+			$publish_box_extra_args
1571
+		);
1572
+	}
1573
+
1574
+
1575
+	/**
1576
+	 * @return EE_Event
1577
+	 */
1578
+	public function get_event_object()
1579
+	{
1580
+		return $this->_cpt_model_obj;
1581
+	}
1582
+
1583
+
1584
+
1585
+
1586
+	/** METABOXES * */
1587
+	/**
1588
+	 * _register_event_editor_meta_boxes
1589
+	 * add all metaboxes related to the event_editor
1590
+	 *
1591
+	 * @return void
1592
+	 * @throws EE_Error
1593
+	 * @throws ReflectionException
1594
+	 */
1595
+	protected function _register_event_editor_meta_boxes()
1596
+	{
1597
+		$this->verify_cpt_object();
1598
+		add_meta_box(
1599
+			'espresso_event_editor_tickets',
1600
+			esc_html__('Event Datetime & Ticket', 'event_espresso'),
1601
+			[$this, 'ticket_metabox'],
1602
+			$this->page_slug,
1603
+			'normal',
1604
+			'high'
1605
+		);
1606
+		add_meta_box(
1607
+			'espresso_event_editor_event_options',
1608
+			esc_html__('Event Registration Options', 'event_espresso'),
1609
+			[$this, 'registration_options_meta_box'],
1610
+			$this->page_slug,
1611
+			'side'
1612
+		);
1613
+		// NOTE: if you're looking for other metaboxes in here,
1614
+		// where a metabox has a related management page in the admin
1615
+		// you will find it setup in the related management page's "_Hooks" file.
1616
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1617
+	}
1618
+
1619
+
1620
+	/**
1621
+	 * @throws DomainException
1622
+	 * @throws EE_Error
1623
+	 * @throws ReflectionException
1624
+	 */
1625
+	public function ticket_metabox()
1626
+	{
1627
+		$existing_datetime_ids = $existing_ticket_ids = [];
1628
+		// defaults for template args
1629
+		$template_args = [
1630
+			'ticket_rows'              => '',
1631
+			'total_ticket_rows'        => 1,
1632
+			'trash_icon'               => 'ee-lock-icon',
1633
+			'disabled'                 => '',
1634
+		];
1635
+		$event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1636
+		/**
1637
+		 * 1. Start with retrieving Datetimes
1638
+		 * 2. Fore each datetime get related tickets
1639
+		 * 3. For each ticket get related prices
1640
+		 */
1641
+		$times          = EEM_Datetime::instance()->get_all_event_dates($event_id);
1642
+		$first_datetime = reset($times);
1643
+		// do we get related tickets?
1644
+		if (
1645
+			$first_datetime instanceof EE_Datetime
1646
+			&& $first_datetime->ID() !== 0
1647
+		) {
1648
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1649
+			$template_args['time']   = $first_datetime;
1650
+			$related_tickets         = $first_datetime->tickets(
1651
+				[
1652
+					['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1653
+					'default_where_conditions' => 'none',
1654
+				]
1655
+			);
1656
+			if (! empty($related_tickets)) {
1657
+				$template_args['total_ticket_rows'] = count($related_tickets);
1658
+				$row                                = 0;
1659
+				foreach ($related_tickets as $ticket) {
1660
+					$existing_ticket_ids[]        = $ticket->get('TKT_ID');
1661
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1662
+					$row++;
1663
+				}
1664
+			} else {
1665
+				$template_args['total_ticket_rows'] = 1;
1666
+				$ticket                       = EEM_Ticket::instance()->create_default_object();
1667
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1668
+			}
1669
+		} else {
1670
+			$template_args['time']        = $times[0];
1671
+			$tickets                      = EEM_Ticket::instance()->get_all_default_tickets();
1672
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1673
+			// NOTE: we're just sending the first default row
1674
+			// (decaf can't manage default tickets so this should be sufficient);
1675
+		}
1676
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1677
+			'event_editor_event_datetimes_help_tab'
1678
+		);
1679
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1680
+		$template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1681
+		$template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1682
+		$template_args['ticket_js_structure']      = $this->_get_ticket_row(
1683
+			EEM_Ticket::instance()->create_default_object(),
1684
+			true
1685
+		);
1686
+		$template                                  = apply_filters(
1687
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1688
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1689
+		);
1690
+		EEH_Template::display_template($template, $template_args);
1691
+	}
1692
+
1693
+
1694
+	/**
1695
+	 * Setup an individual ticket form for the decaf event editor page
1696
+	 *
1697
+	 * @access private
1698
+	 * @param EE_Ticket $ticket   the ticket object
1699
+	 * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1700
+	 * @param int       $row
1701
+	 * @return string generated html for the ticket row.
1702
+	 * @throws EE_Error
1703
+	 * @throws ReflectionException
1704
+	 */
1705
+	private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1706
+	{
1707
+		$template_args = [
1708
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1709
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1710
+				: '',
1711
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1712
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1713
+			'TKT_name'            => $ticket->get('TKT_name'),
1714
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1715
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1716
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1717
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1718
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1719
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1720
+			'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1721
+									 && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1722
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1723
+			'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1724
+				: ' disabled=disabled',
1725
+		];
1726
+		$price         = $ticket->ID() !== 0
1727
+			? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1728
+			: null;
1729
+		$price         = $price instanceof EE_Price
1730
+			? $price
1731
+			: EEM_Price::instance()->create_default_object();
1732
+		$price_args    = [
1733
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1734
+			'PRC_amount'            => $price->get('PRC_amount'),
1735
+			'PRT_ID'                => $price->get('PRT_ID'),
1736
+			'PRC_ID'                => $price->get('PRC_ID'),
1737
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1738
+		];
1739
+		// make sure we have default start and end dates if skeleton
1740
+		// handle rows that should NOT be empty
1741
+		if (empty($template_args['TKT_start_date'])) {
1742
+			// if empty then the start date will be now.
1743
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1744
+		}
1745
+		if (empty($template_args['TKT_end_date'])) {
1746
+			// get the earliest datetime (if present);
1747
+			$earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1748
+				? $this->_cpt_model_obj->get_first_related(
1749
+					'Datetime',
1750
+					['order_by' => ['DTT_EVT_start' => 'ASC']]
1751
+				)
1752
+				: null;
1753
+			$template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1754
+				? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1755
+				: date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1756
+		}
1757
+		$template_args = array_merge($template_args, $price_args);
1758
+		$template      = apply_filters(
1759
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1760
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1761
+			$ticket
1762
+		);
1763
+		return EEH_Template::display_template($template, $template_args, true);
1764
+	}
1765
+
1766
+
1767
+	/**
1768
+	 * @throws EE_Error
1769
+	 * @throws ReflectionException
1770
+	 */
1771
+	public function registration_options_meta_box()
1772
+	{
1773
+		$yes_no_values             = [
1774
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1775
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1776
+		];
1777
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1778
+			[
1779
+				EEM_Registration::status_id_cancelled,
1780
+				EEM_Registration::status_id_declined,
1781
+				EEM_Registration::status_id_incomplete,
1782
+			],
1783
+			true
1784
+		);
1785
+		// $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1786
+		$template_args['_event']                          = $this->_cpt_model_obj;
1787
+		$template_args['event']                           = $this->_cpt_model_obj;
1788
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1789
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1790
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1791
+			'default_reg_status',
1792
+			$default_reg_status_values,
1793
+			$this->_cpt_model_obj->default_registration_status()
1794
+		);
1795
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
1796
+			'display_desc',
1797
+			$yes_no_values,
1798
+			$this->_cpt_model_obj->display_description()
1799
+		);
1800
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1801
+			'display_ticket_selector',
1802
+			$yes_no_values,
1803
+			$this->_cpt_model_obj->display_ticket_selector(),
1804
+			'',
1805
+			'',
1806
+			false
1807
+		);
1808
+		$template_args['additional_registration_options'] = apply_filters(
1809
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1810
+			'',
1811
+			$template_args,
1812
+			$yes_no_values,
1813
+			$default_reg_status_values
1814
+		);
1815
+		EEH_Template::display_template(
1816
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1817
+			$template_args
1818
+		);
1819
+	}
1820
+
1821
+
1822
+	/**
1823
+	 * _get_events()
1824
+	 * This method simply returns all the events (for the given _view and paging)
1825
+	 *
1826
+	 * @access public
1827
+	 * @param int  $per_page     count of items per page (20 default);
1828
+	 * @param int  $current_page what is the current page being viewed.
1829
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1830
+	 *                           If FALSE then we return an array of event objects
1831
+	 *                           that match the given _view and paging parameters.
1832
+	 * @return array|int         an array of event objects or a count of them.
1833
+	 * @throws Exception
1834
+	 */
1835
+	public function get_events($per_page = 10, $current_page = 1, $count = false)
1836
+	{
1837
+		$EEM_Event   = $this->_event_model();
1838
+		$offset      = ($current_page - 1) * $per_page;
1839
+		$limit       = $count ? null : $offset . ',' . $per_page;
1840
+		$orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1841
+		$order       = $this->request->getRequestParam('order', 'DESC');
1842
+		$month_range = $this->request->getRequestParam('month_range');
1843
+		if ($month_range) {
1844
+			$pieces = explode(' ', $month_range, 3);
1845
+			// simulate the FIRST day of the month, that fixes issues for months like February
1846
+			// where PHP doesn't know what to assume for date.
1847
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1848
+			$month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1849
+			$year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1850
+		}
1851
+		$where  = [];
1852
+		$status = $this->request->getRequestParam('status');
1853
+		// determine what post_status our condition will have for the query.
1854
+		switch ($status) {
1855
+			case 'month':
1856
+			case 'today':
1857
+			case null:
1858
+			case 'all':
1859
+				break;
1860
+			case 'draft':
1861
+				$where['status'] = ['IN', ['draft', 'auto-draft']];
1862
+				break;
1863
+			default:
1864
+				$where['status'] = $status;
1865
+		}
1866
+		// categories? The default for all categories is -1
1867
+		$category = $this->request->getRequestParam('EVT_CAT', -1, 'int');
1868
+		if ($category !== -1) {
1869
+			$where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1870
+			$where['Term_Taxonomy.term_id']  = $category;
1871
+		}
1872
+		// date where conditions
1873
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1874
+		if ($month_range) {
1875
+			$DateTime = new DateTime(
1876
+				$year_r . '-' . $month_r . '-01 00:00:00',
1877
+				new DateTimeZone('UTC')
1878
+			);
1879
+			$start    = $DateTime->getTimestamp();
1880
+			// set the datetime to be the end of the month
1881
+			$DateTime->setDate(
1882
+				$year_r,
1883
+				$month_r,
1884
+				$DateTime->format('t')
1885
+			)->setTime(23, 59, 59);
1886
+			$end                             = $DateTime->getTimestamp();
1887
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1888
+		} elseif ($status === 'today') {
1889
+			$DateTime                        =
1890
+				new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1891
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1892
+			$end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1893
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1894
+		} elseif ($status === 'month') {
1895
+			$now                             = date('Y-m-01');
1896
+			$DateTime                        =
1897
+				new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1898
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1899
+			$end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1900
+														->setTime(23, 59, 59)
1901
+														->format(implode(' ', $start_formats));
1902
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1903
+		}
1904
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1905
+			$where['EVT_wp_user'] = get_current_user_id();
1906
+		} else {
1907
+			if (! isset($where['status'])) {
1908
+				if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1909
+					$where['OR'] = [
1910
+						'status*restrict_private' => ['!=', 'private'],
1911
+						'AND'                     => [
1912
+							'status*inclusive' => ['=', 'private'],
1913
+							'EVT_wp_user'      => get_current_user_id(),
1914
+						],
1915
+					];
1916
+				}
1917
+			}
1918
+		}
1919
+		$wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
1920
+		if (
1921
+			$wp_user
1922
+			&& $wp_user !== get_current_user_id()
1923
+			&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1924
+		) {
1925
+			$where['EVT_wp_user'] = $wp_user;
1926
+		}
1927
+		// search query handling
1928
+		$search_term = $this->request->getRequestParam('s');
1929
+		if ($search_term) {
1930
+			$search_term = '%' . $search_term . '%';
1931
+			$where['OR'] = [
1932
+				'EVT_name'       => ['LIKE', $search_term],
1933
+				'EVT_desc'       => ['LIKE', $search_term],
1934
+				'EVT_short_desc' => ['LIKE', $search_term],
1935
+			];
1936
+		}
1937
+		// filter events by venue.
1938
+		$venue = $this->request->getRequestParam('venue', 0, 'int');
1939
+		if ($venue) {
1940
+			$where['Venue.VNU_ID'] = $venue;
1941
+		}
1942
+		$request_params = $this->request->requestParams();
1943
+		$where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
1944
+		$query_params   = apply_filters(
1945
+			'FHEE__Events_Admin_Page__get_events__query_params',
1946
+			[
1947
+				$where,
1948
+				'limit'    => $limit,
1949
+				'order_by' => $orderby,
1950
+				'order'    => $order,
1951
+				'group_by' => 'EVT_ID',
1952
+			],
1953
+			$request_params
1954
+		);
1955
+
1956
+		// let's first check if we have special requests coming in.
1957
+		$active_status = $this->request->getRequestParam('active_status');
1958
+		if ($active_status) {
1959
+			switch ($active_status) {
1960
+				case 'upcoming':
1961
+					return $EEM_Event->get_upcoming_events($query_params, $count);
1962
+				case 'expired':
1963
+					return $EEM_Event->get_expired_events($query_params, $count);
1964
+				case 'active':
1965
+					return $EEM_Event->get_active_events($query_params, $count);
1966
+				case 'inactive':
1967
+					return $EEM_Event->get_inactive_events($query_params, $count);
1968
+			}
1969
+		}
1970
+
1971
+		return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * handling for WordPress CPT actions (trash, restore, delete)
1977
+	 *
1978
+	 * @param string $post_id
1979
+	 * @throws EE_Error
1980
+	 * @throws ReflectionException
1981
+	 */
1982
+	public function trash_cpt_item($post_id)
1983
+	{
1984
+		$this->request->setRequestParam('EVT_ID', $post_id);
1985
+		$this->_trash_or_restore_event('trash', false);
1986
+	}
1987
+
1988
+
1989
+	/**
1990
+	 * @param string $post_id
1991
+	 * @throws EE_Error
1992
+	 * @throws ReflectionException
1993
+	 */
1994
+	public function restore_cpt_item($post_id)
1995
+	{
1996
+		$this->request->setRequestParam('EVT_ID', $post_id);
1997
+		$this->_trash_or_restore_event('draft', false);
1998
+	}
1999
+
2000
+
2001
+	/**
2002
+	 * @param string $post_id
2003
+	 * @throws EE_Error
2004
+	 * @throws EE_Error
2005
+	 */
2006
+	public function delete_cpt_item($post_id)
2007
+	{
2008
+		throw new EE_Error(
2009
+			esc_html__(
2010
+				'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2011
+				'event_espresso'
2012
+			)
2013
+		);
2014
+		// $this->request->setRequestParam('EVT_ID', $post_id);
2015
+		// $this->_delete_event();
2016
+	}
2017
+
2018
+
2019
+	/**
2020
+	 * _trash_or_restore_event
2021
+	 *
2022
+	 * @access protected
2023
+	 * @param string $event_status
2024
+	 * @param bool   $redirect_after
2025
+	 * @throws EE_Error
2026
+	 * @throws EE_Error
2027
+	 * @throws ReflectionException
2028
+	 */
2029
+	protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2030
+	{
2031
+		// determine the event id and set to array.
2032
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2033
+		// loop thru events
2034
+		if ($EVT_ID) {
2035
+			// clean status
2036
+			$event_status = sanitize_key($event_status);
2037
+			// grab status
2038
+			if (! empty($event_status)) {
2039
+				$success = $this->_change_event_status($EVT_ID, $event_status);
2040
+			} else {
2041
+				$success = false;
2042
+				$msg     = esc_html__(
2043
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2044
+					'event_espresso'
2045
+				);
2046
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2047
+			}
2048
+		} else {
2049
+			$success = false;
2050
+			$msg     = esc_html__(
2051
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2052
+				'event_espresso'
2053
+			);
2054
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2055
+		}
2056
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2057
+		if ($redirect_after) {
2058
+			$this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2059
+		}
2060
+	}
2061
+
2062
+
2063
+	/**
2064
+	 * _trash_or_restore_events
2065
+	 *
2066
+	 * @access protected
2067
+	 * @param string $event_status
2068
+	 * @return void
2069
+	 * @throws EE_Error
2070
+	 * @throws EE_Error
2071
+	 * @throws ReflectionException
2072
+	 */
2073
+	protected function _trash_or_restore_events($event_status = 'trash')
2074
+	{
2075
+		// clean status
2076
+		$event_status = sanitize_key($event_status);
2077
+		// grab status
2078
+		if (! empty($event_status)) {
2079
+			$success = true;
2080
+			// determine the event id and set to array.
2081
+			$EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2082
+			// loop thru events
2083
+			foreach ($EVT_IDs as $EVT_ID) {
2084
+				if ($EVT_ID = absint($EVT_ID)) {
2085
+					$results = $this->_change_event_status($EVT_ID, $event_status);
2086
+					$success = $results !== false ? $success : false;
2087
+				} else {
2088
+					$msg = sprintf(
2089
+						esc_html__(
2090
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2091
+							'event_espresso'
2092
+						),
2093
+						$EVT_ID
2094
+					);
2095
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2096
+					$success = false;
2097
+				}
2098
+			}
2099
+		} else {
2100
+			$success = false;
2101
+			$msg     = esc_html__(
2102
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2103
+				'event_espresso'
2104
+			);
2105
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2106
+		}
2107
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2108
+		$success = $success ? 2 : false;
2109
+		$action  = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2110
+		$this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2111
+	}
2112
+
2113
+
2114
+	/**
2115
+	 * @param int    $EVT_ID
2116
+	 * @param string $event_status
2117
+	 * @return bool
2118
+	 * @throws EE_Error
2119
+	 * @throws ReflectionException
2120
+	 */
2121
+	private function _change_event_status($EVT_ID = 0, $event_status = '')
2122
+	{
2123
+		// grab event id
2124
+		if (! $EVT_ID) {
2125
+			$msg = esc_html__(
2126
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2127
+				'event_espresso'
2128
+			);
2129
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2130
+			return false;
2131
+		}
2132
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2133
+		// clean status
2134
+		$event_status = sanitize_key($event_status);
2135
+		// grab status
2136
+		if (empty($event_status)) {
2137
+			$msg = esc_html__(
2138
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2139
+				'event_espresso'
2140
+			);
2141
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2142
+			return false;
2143
+		}
2144
+		// was event trashed or restored ?
2145
+		switch ($event_status) {
2146
+			case 'draft':
2147
+				$action = 'restored from the trash';
2148
+				$hook   = 'AHEE_event_restored_from_trash';
2149
+				break;
2150
+			case 'trash':
2151
+				$action = 'moved to the trash';
2152
+				$hook   = 'AHEE_event_moved_to_trash';
2153
+				break;
2154
+			default:
2155
+				$action = 'updated';
2156
+				$hook   = false;
2157
+		}
2158
+		// use class to change status
2159
+		$this->_cpt_model_obj->set_status($event_status);
2160
+		$success = $this->_cpt_model_obj->save();
2161
+		if (! $success) {
2162
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2163
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2164
+			return false;
2165
+		}
2166
+		if ($hook) {
2167
+			do_action($hook);
2168
+			// fake the action hook in EE_Soft_Delete_Base_Class::delete_or_restore()
2169
+			// because events side step that and it otherwise won't get called
2170
+			do_action(
2171
+				'AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after',
2172
+				$this->_cpt_model_obj,
2173
+				$hook === 'AHEE_event_moved_to_trash',
2174
+				$success
2175
+			);
2176
+		}
2177
+		return true;
2178
+	}
2179
+
2180
+
2181
+	/**
2182
+	 * @param array $event_ids
2183
+	 * @return array
2184
+	 * @since   4.10.23.p
2185
+	 */
2186
+	private function cleanEventIds(array $event_ids)
2187
+	{
2188
+		return array_map('absint', $event_ids);
2189
+	}
2190
+
2191
+
2192
+	/**
2193
+	 * @return array
2194
+	 * @since   4.10.23.p
2195
+	 */
2196
+	private function getEventIdsFromRequest()
2197
+	{
2198
+		if ($this->request->requestParamIsSet('EVT_IDs')) {
2199
+			return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2200
+		} else {
2201
+			return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2202
+		}
2203
+	}
2204
+
2205
+
2206
+	/**
2207
+	 * @param bool $preview_delete
2208
+	 * @throws EE_Error
2209
+	 * @throws ReflectionException
2210
+	 */
2211
+	protected function _delete_event($preview_delete = true)
2212
+	{
2213
+		$this->_delete_events($preview_delete);
2214
+	}
2215
+
2216
+
2217
+	/**
2218
+	 * Gets the tree traversal batch persister.
2219
+	 *
2220
+	 * @return NodeGroupDao
2221
+	 * @throws InvalidArgumentException
2222
+	 * @throws InvalidDataTypeException
2223
+	 * @throws InvalidInterfaceException
2224
+	 * @since 4.10.12.p
2225
+	 */
2226
+	protected function getModelObjNodeGroupPersister()
2227
+	{
2228
+		if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2229
+			$this->model_obj_node_group_persister =
2230
+				$this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2231
+		}
2232
+		return $this->model_obj_node_group_persister;
2233
+	}
2234
+
2235
+
2236
+	/**
2237
+	 * @param bool $preview_delete
2238
+	 * @return void
2239
+	 * @throws EE_Error
2240
+	 * @throws ReflectionException
2241
+	 */
2242
+	protected function _delete_events($preview_delete = true)
2243
+	{
2244
+		$event_ids = $this->getEventIdsFromRequest();
2245
+		if ($preview_delete) {
2246
+			$this->generateDeletionPreview($event_ids);
2247
+		} else {
2248
+			foreach ($event_ids as $event_id) {
2249
+				$event = EEM_Event::instance()->get_one_by_ID($event_id);
2250
+				if ($event instanceof EE_Event) {
2251
+					$event->delete_permanently();
2252
+				}
2253
+			}
2254
+		}
2255
+	}
2256
+
2257
+
2258
+	/**
2259
+	 * @param array $event_ids
2260
+	 */
2261
+	protected function generateDeletionPreview(array $event_ids)
2262
+	{
2263
+		$event_ids = $this->cleanEventIds($event_ids);
2264
+		// Set a code we can use to reference this deletion task in the batch jobs and preview page.
2265
+		$deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2266
+		$return_url        = EE_Admin_Page::add_query_args_and_nonce(
2267
+			[
2268
+				'action'            => 'preview_deletion',
2269
+				'deletion_job_code' => $deletion_job_code,
2270
+			],
2271
+			$this->_admin_base_url
2272
+		);
2273
+		EEH_URL::safeRedirectAndExit(
2274
+			EE_Admin_Page::add_query_args_and_nonce(
2275
+				[
2276
+					'page'              => 'espresso_batch',
2277
+					'batch'             => EED_Batch::batch_job,
2278
+					'EVT_IDs'           => $event_ids,
2279
+					'deletion_job_code' => $deletion_job_code,
2280
+					'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2281
+					'return_url'        => urlencode($return_url),
2282
+				],
2283
+				admin_url()
2284
+			)
2285
+		);
2286
+	}
2287
+
2288
+
2289
+	/**
2290
+	 * Checks for a POST submission
2291
+	 *
2292
+	 * @since 4.10.12.p
2293
+	 */
2294
+	protected function confirmDeletion()
2295
+	{
2296
+		$deletion_redirect_logic = $this->getLoader()->getShared(
2297
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'
2298
+		);
2299
+		$deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2300
+	}
2301
+
2302
+
2303
+	/**
2304
+	 * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2305
+	 *
2306
+	 * @throws EE_Error
2307
+	 * @since 4.10.12.p
2308
+	 */
2309
+	protected function previewDeletion()
2310
+	{
2311
+		$preview_deletion_logic = $this->getLoader()->getShared(
2312
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'
2313
+		);
2314
+		$this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2315
+		$this->display_admin_page_with_no_sidebar();
2316
+	}
2317
+
2318
+
2319
+	/**
2320
+	 * get total number of events
2321
+	 *
2322
+	 * @access public
2323
+	 * @return int
2324
+	 * @throws EE_Error
2325
+	 * @throws EE_Error
2326
+	 */
2327
+	public function total_events()
2328
+	{
2329
+		return EEM_Event::instance()->count(
2330
+			['caps' => 'read_admin'],
2331
+			'EVT_ID',
2332
+			true
2333
+		);
2334
+	}
2335
+
2336
+
2337
+	/**
2338
+	 * get total number of draft events
2339
+	 *
2340
+	 * @access public
2341
+	 * @return int
2342
+	 * @throws EE_Error
2343
+	 * @throws EE_Error
2344
+	 */
2345
+	public function total_events_draft()
2346
+	{
2347
+		return EEM_Event::instance()->count(
2348
+			[
2349
+				['status' => ['IN', ['draft', 'auto-draft']]],
2350
+				'caps' => 'read_admin',
2351
+			],
2352
+			'EVT_ID',
2353
+			true
2354
+		);
2355
+	}
2356
+
2357
+
2358
+	/**
2359
+	 * get total number of trashed events
2360
+	 *
2361
+	 * @access public
2362
+	 * @return int
2363
+	 * @throws EE_Error
2364
+	 * @throws EE_Error
2365
+	 */
2366
+	public function total_trashed_events()
2367
+	{
2368
+		return EEM_Event::instance()->count(
2369
+			[
2370
+				['status' => 'trash'],
2371
+				'caps' => 'read_admin',
2372
+			],
2373
+			'EVT_ID',
2374
+			true
2375
+		);
2376
+	}
2377
+
2378
+
2379
+	/**
2380
+	 *    _default_event_settings
2381
+	 *    This generates the Default Settings Tab
2382
+	 *
2383
+	 * @return void
2384
+	 * @throws EE_Error
2385
+	 */
2386
+	protected function _default_event_settings()
2387
+	{
2388
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2389
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
2390
+		$this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2391
+		$this->display_admin_page_with_sidebar();
2392
+	}
2393
+
2394
+
2395
+	/**
2396
+	 * Return the form for event settings.
2397
+	 *
2398
+	 * @return EE_Form_Section_Proper
2399
+	 * @throws EE_Error
2400
+	 */
2401
+	protected function _default_event_settings_form()
2402
+	{
2403
+		$registration_config              = EE_Registry::instance()->CFG->registration;
2404
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2405
+		// exclude
2406
+			[
2407
+				EEM_Registration::status_id_cancelled,
2408
+				EEM_Registration::status_id_declined,
2409
+				EEM_Registration::status_id_incomplete,
2410
+				EEM_Registration::status_id_wait_list,
2411
+			],
2412
+			true
2413
+		);
2414
+		return new EE_Form_Section_Proper(
2415
+			[
2416
+				'name'            => 'update_default_event_settings',
2417
+				'html_id'         => 'update_default_event_settings',
2418
+				'html_class'      => 'form-table',
2419
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2420
+				'subsections'     => apply_filters(
2421
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2422
+					[
2423
+						'default_reg_status'  => new EE_Select_Input(
2424
+							$registration_stati_for_selection,
2425
+							[
2426
+								'default'         => isset($registration_config->default_STS_ID)
2427
+													 && array_key_exists(
2428
+														 $registration_config->default_STS_ID,
2429
+														 $registration_stati_for_selection
2430
+													 )
2431
+									? sanitize_text_field($registration_config->default_STS_ID)
2432
+									: EEM_Registration::status_id_pending_payment,
2433
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2434
+													 . EEH_Template::get_help_tab_link(
2435
+														 'default_settings_status_help_tab'
2436
+													 ),
2437
+								'html_help_text'  => esc_html__(
2438
+									'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.',
2439
+									'event_espresso'
2440
+								),
2441
+							]
2442
+						),
2443
+						'default_max_tickets' => new EE_Integer_Input(
2444
+							[
2445
+								'default'         => isset($registration_config->default_maximum_number_of_tickets)
2446
+									? $registration_config->default_maximum_number_of_tickets
2447
+									: EEM_Event::get_default_additional_limit(),
2448
+								'html_label_text' => esc_html__(
2449
+									'Default Maximum Tickets Allowed Per Order:',
2450
+									'event_espresso'
2451
+								)
2452
+								. EEH_Template::get_help_tab_link(
2453
+									'default_maximum_tickets_help_tab"'
2454
+								),
2455
+								'html_help_text'  => esc_html__(
2456
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2457
+									'event_espresso'
2458
+								),
2459
+							]
2460
+						),
2461
+					]
2462
+				),
2463
+			]
2464
+		);
2465
+	}
2466
+
2467
+
2468
+	/**
2469
+	 * _update_default_event_settings
2470
+	 *
2471
+	 * @access protected
2472
+	 * @return void
2473
+	 * @throws EE_Error
2474
+	 */
2475
+	protected function _update_default_event_settings()
2476
+	{
2477
+		$registration_config = EE_Registry::instance()->CFG->registration;
2478
+		$form                = $this->_default_event_settings_form();
2479
+		if ($form->was_submitted()) {
2480
+			$form->receive_form_submission();
2481
+			if ($form->is_valid()) {
2482
+				$valid_data = $form->valid_data();
2483
+				if (isset($valid_data['default_reg_status'])) {
2484
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2485
+				}
2486
+				if (isset($valid_data['default_max_tickets'])) {
2487
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2488
+				}
2489
+				// update because data was valid!
2490
+				EE_Registry::instance()->CFG->update_espresso_config();
2491
+				EE_Error::overwrite_success();
2492
+				EE_Error::add_success(
2493
+					esc_html__('Default Event Settings were updated', 'event_espresso')
2494
+				);
2495
+			}
2496
+		}
2497
+		$this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2498
+	}
2499
+
2500
+
2501
+	/*************        Templates        *************
20 2502
      *
21
-     * @var EE_Event $_event
22
-     */
23
-    protected $_event;
24
-
25
-
26
-    /**
27
-     * This will hold the category object for category_details screen.
28
-     *
29
-     * @var stdClass $_category
30
-     */
31
-    protected $_category;
32
-
33
-
34
-    /**
35
-     * This will hold the event model instance
36
-     *
37
-     * @var EEM_Event $_event_model
38
-     */
39
-    protected $_event_model;
40
-
41
-
42
-    /**
43
-     * @var EE_Event
44
-     */
45
-    protected $_cpt_model_obj = false;
46
-
47
-
48
-    /**
49
-     * @var NodeGroupDao
50
-     */
51
-    protected $model_obj_node_group_persister;
52
-
53
-
54
-    /**
55
-     * Initialize page props for this admin page group.
56
-     */
57
-    protected function _init_page_props()
58
-    {
59
-        $this->page_slug        = EVENTS_PG_SLUG;
60
-        $this->page_label       = EVENTS_LABEL;
61
-        $this->_admin_base_url  = EVENTS_ADMIN_URL;
62
-        $this->_admin_base_path = EVENTS_ADMIN;
63
-        $this->_cpt_model_names = [
64
-            'create_new' => 'EEM_Event',
65
-            'edit'       => 'EEM_Event',
66
-        ];
67
-        $this->_cpt_edit_routes = [
68
-            'espresso_events' => 'edit',
69
-        ];
70
-        add_action(
71
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
72
-            [$this, 'verify_event_edit'],
73
-            10,
74
-            2
75
-        );
76
-    }
77
-
78
-
79
-    /**
80
-     * Sets the ajax hooks used for this admin page group.
81
-     */
82
-    protected function _ajax_hooks()
83
-    {
84
-        add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
85
-    }
86
-
87
-
88
-    /**
89
-     * Sets the page properties for this admin page group.
90
-     */
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = EVENTS_LABEL;
94
-        $this->_labels           = [
95
-            'buttons'      => [
96
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
97
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
98
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
99
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
100
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
101
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
102
-            ],
103
-            'editor_title' => [
104
-                'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
105
-            ],
106
-            'publishbox'   => [
107
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
108
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
109
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
110
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
111
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
112
-            ],
113
-        ];
114
-    }
115
-
116
-
117
-    /**
118
-     * Sets the page routes property for this admin page group.
119
-     */
120
-    protected function _set_page_routes()
121
-    {
122
-        // load formatter helper
123
-        // load field generator helper
124
-        // is there a evt_id in the request?
125
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
126
-        $EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
127
-
128
-        $this->_page_routes = [
129
-            'default'                       => [
130
-                'func'       => [$this, '_events_overview_list_table'],
131
-                'capability' => 'ee_read_events',
132
-            ],
133
-            'create_new'                    => [
134
-                'func'       => [$this, '_create_new_cpt_item'],
135
-                'capability' => 'ee_edit_events',
136
-            ],
137
-            'edit'                          => [
138
-                'func'       => [$this, '_edit_cpt_item'],
139
-                'capability' => 'ee_edit_event',
140
-                'obj_id'     => $EVT_ID,
141
-            ],
142
-            'copy_event'                    => [
143
-                'func'       => [$this, '_copy_events'],
144
-                'capability' => 'ee_edit_event',
145
-                'obj_id'     => $EVT_ID,
146
-                'noheader'   => true,
147
-            ],
148
-            'trash_event'                   => [
149
-                'func'       => [$this, '_trash_or_restore_event'],
150
-                'args'       => ['event_status' => 'trash'],
151
-                'capability' => 'ee_delete_event',
152
-                'obj_id'     => $EVT_ID,
153
-                'noheader'   => true,
154
-            ],
155
-            'trash_events'                  => [
156
-                'func'       => [$this, '_trash_or_restore_events'],
157
-                'args'       => ['event_status' => 'trash'],
158
-                'capability' => 'ee_delete_events',
159
-                'noheader'   => true,
160
-            ],
161
-            'restore_event'                 => [
162
-                'func'       => [$this, '_trash_or_restore_event'],
163
-                'args'       => ['event_status' => 'draft'],
164
-                'capability' => 'ee_delete_event',
165
-                'obj_id'     => $EVT_ID,
166
-                'noheader'   => true,
167
-            ],
168
-            'restore_events'                => [
169
-                'func'       => [$this, '_trash_or_restore_events'],
170
-                'args'       => ['event_status' => 'draft'],
171
-                'capability' => 'ee_delete_events',
172
-                'noheader'   => true,
173
-            ],
174
-            'delete_event'                  => [
175
-                'func'       => [$this, '_delete_event'],
176
-                'capability' => 'ee_delete_event',
177
-                'obj_id'     => $EVT_ID,
178
-                'noheader'   => true,
179
-            ],
180
-            'delete_events'                 => [
181
-                'func'       => [$this, '_delete_events'],
182
-                'capability' => 'ee_delete_events',
183
-                'noheader'   => true,
184
-            ],
185
-            'view_report'                   => [
186
-                'func'       => [$this, '_view_report'],
187
-                'capability' => 'ee_edit_events',
188
-            ],
189
-            'default_event_settings'        => [
190
-                'func'       => [$this, '_default_event_settings'],
191
-                'capability' => 'manage_options',
192
-            ],
193
-            'update_default_event_settings' => [
194
-                'func'       => [$this, '_update_default_event_settings'],
195
-                'capability' => 'manage_options',
196
-                'noheader'   => true,
197
-            ],
198
-            'template_settings'             => [
199
-                'func'       => [$this, '_template_settings'],
200
-                'capability' => 'manage_options',
201
-            ],
202
-            // event category tab related
203
-            'add_category'                  => [
204
-                'func'       => [$this, '_category_details'],
205
-                'capability' => 'ee_edit_event_category',
206
-                'args'       => ['add'],
207
-            ],
208
-            'edit_category'                 => [
209
-                'func'       => [$this, '_category_details'],
210
-                'capability' => 'ee_edit_event_category',
211
-                'args'       => ['edit'],
212
-            ],
213
-            'delete_categories'             => [
214
-                'func'       => [$this, '_delete_categories'],
215
-                'capability' => 'ee_delete_event_category',
216
-                'noheader'   => true,
217
-            ],
218
-            'delete_category'               => [
219
-                'func'       => [$this, '_delete_categories'],
220
-                'capability' => 'ee_delete_event_category',
221
-                'noheader'   => true,
222
-            ],
223
-            'insert_category'               => [
224
-                'func'       => [$this, '_insert_or_update_category'],
225
-                'args'       => ['new_category' => true],
226
-                'capability' => 'ee_edit_event_category',
227
-                'noheader'   => true,
228
-            ],
229
-            'update_category'               => [
230
-                'func'       => [$this, '_insert_or_update_category'],
231
-                'args'       => ['new_category' => false],
232
-                'capability' => 'ee_edit_event_category',
233
-                'noheader'   => true,
234
-            ],
235
-            'category_list'                 => [
236
-                'func'       => [$this, '_category_list_table'],
237
-                'capability' => 'ee_manage_event_categories',
238
-            ],
239
-            'preview_deletion'              => [
240
-                'func'       => [$this, 'previewDeletion'],
241
-                'capability' => 'ee_delete_events',
242
-            ],
243
-            'confirm_deletion'              => [
244
-                'func'       => [$this, 'confirmDeletion'],
245
-                'capability' => 'ee_delete_events',
246
-                'noheader'   => true,
247
-            ],
248
-        ];
249
-    }
250
-
251
-
252
-    /**
253
-     * Set the _page_config property for this admin page group.
254
-     */
255
-    protected function _set_page_config()
256
-    {
257
-        $post_id            = $this->request->getRequestParam('post', 0, 'int');
258
-        $EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
259
-        $this->_page_config = [
260
-            'default'                => [
261
-                'nav'           => [
262
-                    'label' => esc_html__('Overview', 'event_espresso'),
263
-                    'order' => 10,
264
-                ],
265
-                'list_table'    => 'Events_Admin_List_Table',
266
-                'help_tabs'     => [
267
-                    'events_overview_help_tab'                       => [
268
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
269
-                        'filename' => 'events_overview',
270
-                    ],
271
-                    'events_overview_table_column_headings_help_tab' => [
272
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
273
-                        'filename' => 'events_overview_table_column_headings',
274
-                    ],
275
-                    'events_overview_filters_help_tab'               => [
276
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
277
-                        'filename' => 'events_overview_filters',
278
-                    ],
279
-                    'events_overview_view_help_tab'                  => [
280
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
281
-                        'filename' => 'events_overview_views',
282
-                    ],
283
-                    'events_overview_other_help_tab'                 => [
284
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
285
-                        'filename' => 'events_overview_other',
286
-                    ],
287
-                ],
288
-                'qtips'         => [
289
-                    'EE_Event_List_Table_Tips',
290
-                ],
291
-                'require_nonce' => false,
292
-            ],
293
-            'create_new'             => [
294
-                'nav'           => [
295
-                    'label'      => esc_html__('Add Event', 'event_espresso'),
296
-                    'order'      => 5,
297
-                    'persistent' => false,
298
-                ],
299
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
300
-                'help_tabs'     => [
301
-                    'event_editor_help_tab'                            => [
302
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
303
-                        'filename' => 'event_editor',
304
-                    ],
305
-                    'event_editor_title_richtexteditor_help_tab'       => [
306
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
307
-                        'filename' => 'event_editor_title_richtexteditor',
308
-                    ],
309
-                    'event_editor_venue_details_help_tab'              => [
310
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
311
-                        'filename' => 'event_editor_venue_details',
312
-                    ],
313
-                    'event_editor_event_datetimes_help_tab'            => [
314
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
315
-                        'filename' => 'event_editor_event_datetimes',
316
-                    ],
317
-                    'event_editor_event_tickets_help_tab'              => [
318
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
319
-                        'filename' => 'event_editor_event_tickets',
320
-                    ],
321
-                    'event_editor_event_registration_options_help_tab' => [
322
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
323
-                        'filename' => 'event_editor_event_registration_options',
324
-                    ],
325
-                    'event_editor_tags_categories_help_tab'            => [
326
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
327
-                        'filename' => 'event_editor_tags_categories',
328
-                    ],
329
-                    'event_editor_questions_registrants_help_tab'      => [
330
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
331
-                        'filename' => 'event_editor_questions_registrants',
332
-                    ],
333
-                    'event_editor_save_new_event_help_tab'             => [
334
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
335
-                        'filename' => 'event_editor_save_new_event',
336
-                    ],
337
-                    'event_editor_other_help_tab'                      => [
338
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
339
-                        'filename' => 'event_editor_other',
340
-                    ],
341
-                ],
342
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
343
-                'require_nonce' => false,
344
-            ],
345
-            'edit'                   => [
346
-                'nav'           => [
347
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
348
-                    'order'      => 5,
349
-                    'persistent' => false,
350
-                    'url'        => $post_id
351
-                        ? EE_Admin_Page::add_query_args_and_nonce(
352
-                            ['post' => $post_id, 'action' => 'edit'],
353
-                            $this->_current_page_view_url
354
-                        )
355
-                        : $this->_admin_base_url,
356
-                ],
357
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
358
-                'help_tabs'     => [
359
-                    'event_editor_help_tab'                            => [
360
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
361
-                        'filename' => 'event_editor',
362
-                    ],
363
-                    'event_editor_title_richtexteditor_help_tab'       => [
364
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
365
-                        'filename' => 'event_editor_title_richtexteditor',
366
-                    ],
367
-                    'event_editor_venue_details_help_tab'              => [
368
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
369
-                        'filename' => 'event_editor_venue_details',
370
-                    ],
371
-                    'event_editor_event_datetimes_help_tab'            => [
372
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
373
-                        'filename' => 'event_editor_event_datetimes',
374
-                    ],
375
-                    'event_editor_event_tickets_help_tab'              => [
376
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
377
-                        'filename' => 'event_editor_event_tickets',
378
-                    ],
379
-                    'event_editor_event_registration_options_help_tab' => [
380
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
381
-                        'filename' => 'event_editor_event_registration_options',
382
-                    ],
383
-                    'event_editor_tags_categories_help_tab'            => [
384
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
385
-                        'filename' => 'event_editor_tags_categories',
386
-                    ],
387
-                    'event_editor_questions_registrants_help_tab'      => [
388
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
389
-                        'filename' => 'event_editor_questions_registrants',
390
-                    ],
391
-                    'event_editor_save_new_event_help_tab'             => [
392
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
393
-                        'filename' => 'event_editor_save_new_event',
394
-                    ],
395
-                    'event_editor_other_help_tab'                      => [
396
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
397
-                        'filename' => 'event_editor_other',
398
-                    ],
399
-                ],
400
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
401
-                'require_nonce' => false,
402
-            ],
403
-            'default_event_settings' => [
404
-                'nav'           => [
405
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
406
-                    'order' => 40,
407
-                ],
408
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
409
-                'labels'        => [
410
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
411
-                ],
412
-                'help_tabs'     => [
413
-                    'default_settings_help_tab'        => [
414
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
415
-                        'filename' => 'events_default_settings',
416
-                    ],
417
-                    'default_settings_status_help_tab' => [
418
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
419
-                        'filename' => 'events_default_settings_status',
420
-                    ],
421
-                    'default_maximum_tickets_help_tab' => [
422
-                        'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
423
-                        'filename' => 'events_default_settings_max_tickets',
424
-                    ],
425
-                ],
426
-                'require_nonce' => false,
427
-            ],
428
-            // template settings
429
-            'template_settings'      => [
430
-                'nav'           => [
431
-                    'label' => esc_html__('Templates', 'event_espresso'),
432
-                    'order' => 30,
433
-                ],
434
-                'metaboxes'     => $this->_default_espresso_metaboxes,
435
-                'help_tabs'     => [
436
-                    'general_settings_templates_help_tab' => [
437
-                        'title'    => esc_html__('Templates', 'event_espresso'),
438
-                        'filename' => 'general_settings_templates',
439
-                    ],
440
-                ],
441
-                'require_nonce' => false,
442
-            ],
443
-            // event category stuff
444
-            'add_category'           => [
445
-                'nav'           => [
446
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
447
-                    'order'      => 15,
448
-                    'persistent' => false,
449
-                ],
450
-                'help_tabs'     => [
451
-                    'add_category_help_tab' => [
452
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
453
-                        'filename' => 'events_add_category',
454
-                    ],
455
-                ],
456
-                'metaboxes'     => ['_publish_post_box'],
457
-                'require_nonce' => false,
458
-            ],
459
-            'edit_category'          => [
460
-                'nav'           => [
461
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
462
-                    'order'      => 15,
463
-                    'persistent' => false,
464
-                    'url'        => $EVT_CAT_ID
465
-                        ? add_query_arg(
466
-                            ['EVT_CAT_ID' => $EVT_CAT_ID],
467
-                            $this->_current_page_view_url
468
-                        )
469
-                        : $this->_admin_base_url,
470
-                ],
471
-                'help_tabs'     => [
472
-                    'edit_category_help_tab' => [
473
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
474
-                        'filename' => 'events_edit_category',
475
-                    ],
476
-                ],
477
-                'metaboxes'     => ['_publish_post_box'],
478
-                'require_nonce' => false,
479
-            ],
480
-            'category_list'          => [
481
-                'nav'           => [
482
-                    'label' => esc_html__('Categories', 'event_espresso'),
483
-                    'order' => 20,
484
-                ],
485
-                'list_table'    => 'Event_Categories_Admin_List_Table',
486
-                'help_tabs'     => [
487
-                    'events_categories_help_tab'                       => [
488
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
489
-                        'filename' => 'events_categories',
490
-                    ],
491
-                    'events_categories_table_column_headings_help_tab' => [
492
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
493
-                        'filename' => 'events_categories_table_column_headings',
494
-                    ],
495
-                    'events_categories_view_help_tab'                  => [
496
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
497
-                        'filename' => 'events_categories_views',
498
-                    ],
499
-                    'events_categories_other_help_tab'                 => [
500
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
501
-                        'filename' => 'events_categories_other',
502
-                    ],
503
-                ],
504
-                'metaboxes'     => $this->_default_espresso_metaboxes,
505
-                'require_nonce' => false,
506
-            ],
507
-            'preview_deletion'       => [
508
-                'nav'           => [
509
-                    'label'      => esc_html__('Preview Deletion', 'event_espresso'),
510
-                    'order'      => 15,
511
-                    'persistent' => false,
512
-                    'url'        => '',
513
-                ],
514
-                'require_nonce' => false,
515
-            ],
516
-        ];
517
-    }
518
-
519
-
520
-    /**
521
-     * Used to register any global screen options if necessary for every route in this admin page group.
522
-     */
523
-    protected function _add_screen_options()
524
-    {
525
-    }
526
-
527
-
528
-    /**
529
-     * Implementing the screen options for the 'default' route.
530
-     */
531
-    protected function _add_screen_options_default()
532
-    {
533
-        $this->_per_page_screen_option();
534
-    }
535
-
536
-
537
-    /**
538
-     * Implementing screen options for the category list route.
539
-     */
540
-    protected function _add_screen_options_category_list()
541
-    {
542
-        $page_title              = $this->_admin_page_title;
543
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
544
-        $this->_per_page_screen_option();
545
-        $this->_admin_page_title = $page_title;
546
-    }
547
-
548
-
549
-    /**
550
-     * Used to register any global feature pointers for the admin page group.
551
-     */
552
-    protected function _add_feature_pointers()
553
-    {
554
-    }
555
-
556
-
557
-    /**
558
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
559
-     */
560
-    public function load_scripts_styles()
561
-    {
562
-        wp_register_style(
563
-            'events-admin-css',
564
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
565
-            [],
566
-            EVENT_ESPRESSO_VERSION
567
-        );
568
-        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
569
-        wp_enqueue_style('events-admin-css');
570
-        wp_enqueue_style('ee-cat-admin');
571
-        // todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
572
-        // registers for all views
573
-        // scripts
574
-        wp_register_script(
575
-            'event_editor_js',
576
-            EVENTS_ASSETS_URL . 'event_editor.js',
577
-            ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
578
-            EVENT_ESPRESSO_VERSION,
579
-            true
580
-        );
581
-    }
582
-
583
-
584
-    /**
585
-     * Enqueuing scripts and styles specific to this view
586
-     */
587
-    public function load_scripts_styles_create_new()
588
-    {
589
-        $this->load_scripts_styles_edit();
590
-    }
591
-
592
-
593
-    /**
594
-     * Enqueuing scripts and styles specific to this view
595
-     */
596
-    public function load_scripts_styles_edit()
597
-    {
598
-        // styles
599
-        wp_enqueue_style('espresso-ui-theme');
600
-        wp_register_style(
601
-            'event-editor-css',
602
-            EVENTS_ASSETS_URL . 'event-editor.css',
603
-            ['ee-admin-css'],
604
-            EVENT_ESPRESSO_VERSION
605
-        );
606
-        wp_enqueue_style('event-editor-css');
607
-        // scripts
608
-        wp_register_script(
609
-            'event-datetime-metabox',
610
-            EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
611
-            ['event_editor_js', 'ee-datepicker'],
612
-            EVENT_ESPRESSO_VERSION
613
-        );
614
-        wp_enqueue_script('event-datetime-metabox');
615
-    }
616
-
617
-
618
-    /**
619
-     * Populating the _views property for the category list table view.
620
-     */
621
-    protected function _set_list_table_views_category_list()
622
-    {
623
-        $this->_views = [
624
-            'all' => [
625
-                'slug'        => 'all',
626
-                'label'       => esc_html__('All', 'event_espresso'),
627
-                'count'       => 0,
628
-                'bulk_action' => [
629
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
630
-                ],
631
-            ],
632
-        ];
633
-    }
634
-
635
-
636
-    /**
637
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
638
-     */
639
-    public function admin_init()
640
-    {
641
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
642
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
643
-            'event_espresso'
644
-        );
645
-    }
646
-
647
-
648
-    /**
649
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
650
-     * group.
651
-     */
652
-    public function admin_notices()
653
-    {
654
-    }
655
-
656
-
657
-    /**
658
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
659
-     * this admin page group.
660
-     */
661
-    public function admin_footer_scripts()
662
-    {
663
-    }
664
-
665
-
666
-    /**
667
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
668
-     * warning (via EE_Error::add_error());
669
-     *
670
-     * @param EE_Event $event Event object
671
-     * @param string   $req_type
672
-     * @return void
673
-     * @throws EE_Error
674
-     * @throws ReflectionException
675
-     */
676
-    public function verify_event_edit($event = null, $req_type = '')
677
-    {
678
-        // don't need to do this when processing
679
-        if (! empty($req_type)) {
680
-            return;
681
-        }
682
-        // no event?
683
-        if (empty($event)) {
684
-            // set event
685
-            $event = $this->_cpt_model_obj;
686
-        }
687
-        // STILL no event?
688
-        if (! $event instanceof EE_Event) {
689
-            return;
690
-        }
691
-        $orig_status = $event->status();
692
-        // first check if event is active.
693
-        if (
694
-            $orig_status === EEM_Event::cancelled
695
-            || $orig_status === EEM_Event::postponed
696
-            || $event->is_expired()
697
-            || $event->is_inactive()
698
-        ) {
699
-            return;
700
-        }
701
-        // made it here so it IS active... next check that any of the tickets are sold.
702
-        if ($event->is_sold_out(true)) {
703
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
704
-                EE_Error::add_attention(
705
-                    sprintf(
706
-                        esc_html__(
707
-                            '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.',
708
-                            'event_espresso'
709
-                        ),
710
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
711
-                    )
712
-                );
713
-            }
714
-            return;
715
-        } elseif ($orig_status === EEM_Event::sold_out) {
716
-            EE_Error::add_attention(
717
-                sprintf(
718
-                    esc_html__(
719
-                        '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.',
720
-                        'event_espresso'
721
-                    ),
722
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
723
-                )
724
-            );
725
-        }
726
-        // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
727
-        if (! $event->tickets_on_sale()) {
728
-            return;
729
-        }
730
-        // made it here so show warning
731
-        $this->_edit_event_warning();
732
-    }
733
-
734
-
735
-    /**
736
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
737
-     * When needed, hook this into a EE_Error::add_error() notice.
738
-     *
739
-     * @access protected
740
-     * @return void
741
-     */
742
-    protected function _edit_event_warning()
743
-    {
744
-        // we don't want to add warnings during these requests
745
-        if ($this->request->getRequestParam('action') === 'editpost') {
746
-            return;
747
-        }
748
-        EE_Error::add_attention(
749
-            sprintf(
750
-                esc_html__(
751
-                    'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
752
-                    'event_espresso'
753
-                ),
754
-                '<a class="espresso-help-tab-lnk">',
755
-                '</a>'
756
-            )
757
-        );
758
-    }
759
-
760
-
761
-    /**
762
-     * When a user is creating a new event, notify them if they haven't set their timezone.
763
-     * Otherwise, do the normal logic
764
-     *
765
-     * @return void
766
-     * @throws EE_Error
767
-     */
768
-    protected function _create_new_cpt_item()
769
-    {
770
-        $has_timezone_string = get_option('timezone_string');
771
-        // only nag them about setting their timezone if it's their first event, and they haven't already done it
772
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
773
-            EE_Error::add_attention(
774
-                sprintf(
775
-                    esc_html__(
776
-                        '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',
777
-                        'event_espresso'
778
-                    ),
779
-                    '<br>',
780
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
781
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
782
-                    . '</select>',
783
-                    '<button class="button button-secondary timezone-submit">',
784
-                    '</button><span class="spinner"></span>'
785
-                ),
786
-                __FILE__,
787
-                __FUNCTION__,
788
-                __LINE__
789
-            );
790
-        }
791
-        parent::_create_new_cpt_item();
792
-    }
793
-
794
-
795
-    /**
796
-     * Sets the _views property for the default route in this admin page group.
797
-     */
798
-    protected function _set_list_table_views_default()
799
-    {
800
-        $this->_views = [
801
-            'all'   => [
802
-                'slug'        => 'all',
803
-                'label'       => esc_html__('View All Events', 'event_espresso'),
804
-                'count'       => 0,
805
-                'bulk_action' => [
806
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
807
-                ],
808
-            ],
809
-            'draft' => [
810
-                'slug'        => 'draft',
811
-                'label'       => esc_html__('Draft', 'event_espresso'),
812
-                'count'       => 0,
813
-                'bulk_action' => [
814
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
815
-                ],
816
-            ],
817
-        ];
818
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
819
-            $this->_views['trash'] = [
820
-                'slug'        => 'trash',
821
-                'label'       => esc_html__('Trash', 'event_espresso'),
822
-                'count'       => 0,
823
-                'bulk_action' => [
824
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
825
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
826
-                ],
827
-            ];
828
-        }
829
-    }
830
-
831
-
832
-    /**
833
-     * Provides the legend item array for the default list table view.
834
-     *
835
-     * @return array
836
-     * @throws EE_Error
837
-     * @throws EE_Error
838
-     */
839
-    protected function _event_legend_items()
840
-    {
841
-        $items    = [
842
-            'view_details'   => [
843
-                'class' => 'dashicons dashicons-search',
844
-                'desc'  => esc_html__('View Event', 'event_espresso'),
845
-            ],
846
-            'edit_event'     => [
847
-                'class' => 'ee-icon ee-icon-calendar-edit',
848
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
849
-            ],
850
-            'view_attendees' => [
851
-                'class' => 'dashicons dashicons-groups',
852
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
853
-            ],
854
-        ];
855
-        $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
856
-        $statuses = [
857
-            'sold_out_status'  => [
858
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
859
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
860
-            ],
861
-            'active_status'    => [
862
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
863
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
864
-            ],
865
-            'upcoming_status'  => [
866
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
867
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
868
-            ],
869
-            'postponed_status' => [
870
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
871
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
872
-            ],
873
-            'cancelled_status' => [
874
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
875
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
876
-            ],
877
-            'expired_status'   => [
878
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
879
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
880
-            ],
881
-            'inactive_status'  => [
882
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
883
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
884
-            ],
885
-        ];
886
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
887
-        return array_merge($items, $statuses);
888
-    }
889
-
890
-
891
-    /**
892
-     * @return EEM_Event
893
-     * @throws EE_Error
894
-     * @throws ReflectionException
895
-     */
896
-    private function _event_model()
897
-    {
898
-        if (! $this->_event_model instanceof EEM_Event) {
899
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
900
-        }
901
-        return $this->_event_model;
902
-    }
903
-
904
-
905
-    /**
906
-     * Adds extra buttons to the WP CPT permalink field row.
907
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
908
-     *
909
-     * @param string $return    the current html
910
-     * @param int    $id        the post id for the page
911
-     * @param string $new_title What the title is
912
-     * @param string $new_slug  what the slug is
913
-     * @return string            The new html string for the permalink area
914
-     */
915
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
916
-    {
917
-        // make sure this is only when editing
918
-        if (! empty($id)) {
919
-            $post   = get_post($id);
920
-            $return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
921
-                       . esc_html__('Shortcode', 'event_espresso')
922
-                       . '</a> ';
923
-            $return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
924
-                       . $post->ID
925
-                       . ']">';
926
-        }
927
-        return $return;
928
-    }
929
-
930
-
931
-    /**
932
-     * _events_overview_list_table
933
-     * This contains the logic for showing the events_overview list
934
-     *
935
-     * @access protected
936
-     * @return void
937
-     * @throws EE_Error
938
-     */
939
-    protected function _events_overview_list_table()
940
-    {
941
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
942
-        $this->_template_args['after_list_table']                           =
943
-            ! empty($this->_template_args['after_list_table'])
944
-                ? (array) $this->_template_args['after_list_table']
945
-                : [];
946
-        $this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
947
-            . EEH_Template::get_button_or_link(
948
-                get_post_type_archive_link('espresso_events'),
949
-                esc_html__("View Event Archive Page", "event_espresso"),
950
-                'button'
951
-            );
952
-        $this->_template_args['after_list_table']['legend']                 = $this->_display_legend(
953
-            $this->_event_legend_items()
954
-        );
955
-        $this->_admin_page_title                                            .= ' ' . $this->get_action_link_or_button(
956
-            'create_new',
957
-            'add',
958
-            [],
959
-            'add-new-h2'
960
-        );
961
-        $this->display_admin_list_table_page_with_no_sidebar();
962
-    }
963
-
964
-
965
-    /**
966
-     * this allows for extra misc actions in the default WP publish box
967
-     *
968
-     * @return void
969
-     * @throws EE_Error
970
-     * @throws ReflectionException
971
-     */
972
-    public function extra_misc_actions_publish_box()
973
-    {
974
-        $this->_generate_publish_box_extra_content();
975
-    }
976
-
977
-
978
-    /**
979
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
980
-     * saved.
981
-     * Typically you would use this to save any additional data.
982
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
983
-     * ALSO very important.  When a post transitions from scheduled to published,
984
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
985
-     * other meta saves. So MAKE sure that you handle this accordingly.
986
-     *
987
-     * @access protected
988
-     * @abstract
989
-     * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
990
-     * @param WP_Post $post    The post object of the cpt that was saved.
991
-     * @return void
992
-     * @throws EE_Error
993
-     * @throws ReflectionException
994
-     */
995
-    protected function _insert_update_cpt_item($post_id, $post)
996
-    {
997
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
998
-            // get out we're not processing an event save.
999
-            return;
1000
-        }
1001
-
1002
-        $event_values = [
1003
-            'EVT_display_desc'                => $this->request->getRequestParam('display_desc', false, 'bool'),
1004
-            'EVT_display_ticket_selector'     => $this->request->getRequestParam(
1005
-                'display_ticket_selector',
1006
-                false,
1007
-                'bool'
1008
-            ),
1009
-            'EVT_additional_limit'            => min(
1010
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1011
-                $this->request->getRequestParam('additional_limit', null, 'int')
1012
-            ),
1013
-            'EVT_default_registration_status' => $this->request->getRequestParam(
1014
-                'EVT_default_registration_status',
1015
-                EE_Registry::instance()->CFG->registration->default_STS_ID
1016
-            ),
1017
-
1018
-            'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1019
-            'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1020
-            'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1021
-            'EVT_external_URL'    => $this->request->getRequestParam('externalURL'),
1022
-            'EVT_phone'           => $this->request->getRequestParam('event_phone'),
1023
-        ];
1024
-        // update event
1025
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1026
-        // get event_object for other metaboxes...
1027
-        // though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1028
-        // i have to setup where conditions to override the filters in the model
1029
-        // that filter out auto-draft and inherit statuses so we GET the inherit id!
1030
-        $event = $this->_event_model()->get_one(
1031
-            [
1032
-                [
1033
-                    $this->_event_model()->primary_key_name() => $post_id,
1034
-                    'OR'                                      => [
1035
-                        'status'   => $post->post_status,
1036
-                        // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1037
-                        // but the returned object here has a status of "publish", so use the original post status as well
1038
-                        'status*1' => $this->request->getRequestParam('original_post_status'),
1039
-                    ],
1040
-                ],
1041
-            ]
1042
-        );
1043
-        // the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1044
-        $event_update_callbacks = apply_filters(
1045
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1046
-            [
1047
-                [$this, '_default_venue_update'],
1048
-                [$this, '_default_tickets_update'],
1049
-            ]
1050
-        );
1051
-        $att_success            = true;
1052
-        foreach ($event_update_callbacks as $e_callback) {
1053
-            $_success = is_callable($e_callback)
1054
-                ? call_user_func($e_callback, $event, $this->request->requestParams())
1055
-                : false;
1056
-            // if ANY of these updates fail then we want the appropriate global error message
1057
-            $att_success = ! $att_success ? $att_success : $_success;
1058
-        }
1059
-        // any errors?
1060
-        if ($success && false === $att_success) {
1061
-            EE_Error::add_error(
1062
-                esc_html__(
1063
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1064
-                    'event_espresso'
1065
-                ),
1066
-                __FILE__,
1067
-                __FUNCTION__,
1068
-                __LINE__
1069
-            );
1070
-        } elseif ($success === false) {
1071
-            EE_Error::add_error(
1072
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1073
-                __FILE__,
1074
-                __FUNCTION__,
1075
-                __LINE__
1076
-            );
1077
-        }
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * @param int $post_id
1083
-     * @param int $revision_id
1084
-     * @throws EE_Error
1085
-     * @throws EE_Error
1086
-     * @throws ReflectionException
1087
-     * @see parent::restore_item()
1088
-     */
1089
-    protected function _restore_cpt_item($post_id, $revision_id)
1090
-    {
1091
-        // copy existing event meta to new post
1092
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1093
-        if ($post_evt instanceof EE_Event) {
1094
-            // meta revision restore
1095
-            $post_evt->restore_revision($revision_id);
1096
-            // related objs restore
1097
-            $post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1098
-        }
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * Attach the venue to the Event
1104
-     *
1105
-     * @param EE_Event $event Event Object to add the venue to
1106
-     * @param array    $data  The request data from the form
1107
-     * @return bool           Success or fail.
1108
-     * @throws EE_Error
1109
-     * @throws ReflectionException
1110
-     */
1111
-    protected function _default_venue_update(EE_Event $event, $data)
1112
-    {
1113
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1114
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1115
-        $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1116
-        // very important.  If we don't have a venue name...
1117
-        // then we'll get out because not necessary to create empty venue
1118
-        if (empty($data['venue_title'])) {
1119
-            return false;
1120
-        }
1121
-        $venue_array = [
1122
-            'VNU_wp_user'         => $event->get('EVT_wp_user'),
1123
-            'VNU_name'            => $data['venue_title'],
1124
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1125
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1126
-            'VNU_short_desc'      => ! empty($data['venue_short_description'])
1127
-                ? $data['venue_short_description']
1128
-                : null,
1129
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1130
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1131
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1132
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1133
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1134
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1135
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1136
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1137
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1138
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1139
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1140
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1141
-            'status'              => 'publish',
1142
-        ];
1143
-        // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1144
-        if (! empty($venue_id)) {
1145
-            $update_where  = [$venue_model->primary_key_name() => $venue_id];
1146
-            $rows_affected = $venue_model->update($venue_array, [$update_where]);
1147
-            // 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.
1148
-            $event->_add_relation_to($venue_id, 'Venue');
1149
-            return $rows_affected > 0;
1150
-        }
1151
-        // we insert the venue
1152
-        $venue_id = $venue_model->insert($venue_array);
1153
-        $event->_add_relation_to($venue_id, 'Venue');
1154
-        return ! empty($venue_id);
1155
-        // when we have the ancestor come in it's already been handled by the revision save.
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1161
-     *
1162
-     * @param EE_Event $event The Event object we're attaching data to
1163
-     * @param array    $data  The request data from the form
1164
-     * @return array
1165
-     * @throws EE_Error
1166
-     * @throws ReflectionException
1167
-     * @throws Exception
1168
-     */
1169
-    protected function _default_tickets_update(EE_Event $event, $data)
1170
-    {
1171
-        $datetime       = null;
1172
-        $saved_tickets  = [];
1173
-        $event_timezone = $event->get_timezone();
1174
-        $date_formats   = ['Y-m-d', 'h:i a'];
1175
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1176
-            // trim all values to ensure any excess whitespace is removed.
1177
-            $datetime_data                = array_map('trim', $datetime_data);
1178
-            $datetime_data['DTT_EVT_end'] =
1179
-                isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1180
-                    ? $datetime_data['DTT_EVT_end']
1181
-                    : $datetime_data['DTT_EVT_start'];
1182
-            $datetime_values              = [
1183
-                'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1184
-                'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1185
-                'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1186
-                'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1187
-                'DTT_order'     => $row,
1188
-            ];
1189
-            // if we have an id then let's get existing object first and then set the new values.
1190
-            //  Otherwise we instantiate a new object for save.
1191
-            if (! empty($datetime_data['DTT_ID'])) {
1192
-                $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1193
-                if (! $datetime instanceof EE_Datetime) {
1194
-                    throw new RuntimeException(
1195
-                        sprintf(
1196
-                            esc_html__(
1197
-                                'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1198
-                                'event_espresso'
1199
-                            ),
1200
-                            $datetime_data['DTT_ID']
1201
-                        )
1202
-                    );
1203
-                }
1204
-                $datetime->set_date_format($date_formats[0]);
1205
-                $datetime->set_time_format($date_formats[1]);
1206
-                foreach ($datetime_values as $field => $value) {
1207
-                    $datetime->set($field, $value);
1208
-                }
1209
-            } else {
1210
-                $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1211
-            }
1212
-            if (! $datetime instanceof EE_Datetime) {
1213
-                throw new RuntimeException(
1214
-                    sprintf(
1215
-                        esc_html__(
1216
-                            'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1217
-                            'event_espresso'
1218
-                        ),
1219
-                        print_r($datetime_values, true)
1220
-                    )
1221
-                );
1222
-            }
1223
-            // before going any further make sure our dates are setup correctly
1224
-            // so that the end date is always equal or greater than the start date.
1225
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1226
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1227
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1228
-            }
1229
-            $datetime->save();
1230
-            $event->_add_relation_to($datetime, 'Datetime');
1231
-        }
1232
-        // no datetimes get deleted so we don't do any of that logic here.
1233
-        // update tickets next
1234
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1235
-
1236
-        // set up some default start and end dates in case those are not present in the incoming data
1237
-        $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1238
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1239
-        // use the start date of the first datetime for the end date
1240
-        $first_datetime   = $event->first_datetime();
1241
-        $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1242
-
1243
-        // now process the incoming data
1244
-        foreach ($data['edit_tickets'] as $row => $ticket_data) {
1245
-            $update_prices = false;
1246
-            $ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1247
-                ? $data['edit_prices'][ $row ][1]['PRC_amount']
1248
-                : 0;
1249
-            // trim inputs to ensure any excess whitespace is removed.
1250
-            $ticket_data   = array_map('trim', $ticket_data);
1251
-            $ticket_values = [
1252
-                'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1253
-                'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1254
-                'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1255
-                'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1256
-                'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1257
-                    ? $ticket_data['TKT_start_date']
1258
-                    : $default_start_date,
1259
-                'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1260
-                    ? $ticket_data['TKT_end_date']
1261
-                    : $default_end_date,
1262
-                'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1263
-                                     || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1264
-                    ? $ticket_data['TKT_qty']
1265
-                    : EE_INF,
1266
-                'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1267
-                                     || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1268
-                    ? $ticket_data['TKT_uses']
1269
-                    : EE_INF,
1270
-                'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1271
-                'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1272
-                'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1273
-                'TKT_price'       => $ticket_price,
1274
-                'TKT_row'         => $row,
1275
-            ];
1276
-            // if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1277
-            // which means in turn that the prices will become new prices as well.
1278
-            if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1279
-                $ticket_values['TKT_ID']         = 0;
1280
-                $ticket_values['TKT_is_default'] = 0;
1281
-                $update_prices                   = true;
1282
-            }
1283
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
1284
-            // we actually do our saves ahead of adding any relations because its entirely possible that this
1285
-            // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1286
-            // keep in mind that if the ticket has been sold (and we have changed pricing information),
1287
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1288
-            if (! empty($ticket_data['TKT_ID'])) {
1289
-                $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1290
-                if (! $existing_ticket instanceof EE_Ticket) {
1291
-                    throw new RuntimeException(
1292
-                        sprintf(
1293
-                            esc_html__(
1294
-                                'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1295
-                                'event_espresso'
1296
-                            ),
1297
-                            $ticket_data['TKT_ID']
1298
-                        )
1299
-                    );
1300
-                }
1301
-                $ticket_sold = $existing_ticket->count_related(
1302
-                    'Registration',
1303
-                    [
1304
-                        [
1305
-                            'STS_ID' => [
1306
-                                'NOT IN',
1307
-                                [EEM_Registration::status_id_incomplete],
1308
-                            ],
1309
-                        ],
1310
-                    ]
1311
-                ) > 0;
1312
-                // let's just check the total price for the existing ticket and determine if it matches the new total price.
1313
-                // if they are different then we create a new ticket (if $ticket_sold)
1314
-                // if they aren't different then we go ahead and modify existing ticket.
1315
-                $create_new_ticket = $ticket_sold
1316
-                                     && $ticket_price !== $existing_ticket->price()
1317
-                                     && ! $existing_ticket->deleted();
1318
-                $existing_ticket->set_date_format($date_formats[0]);
1319
-                $existing_ticket->set_time_format($date_formats[1]);
1320
-                // set new values
1321
-                foreach ($ticket_values as $field => $value) {
1322
-                    if ($field == 'TKT_qty') {
1323
-                        $existing_ticket->set_qty($value);
1324
-                    } elseif ($field == 'TKT_price') {
1325
-                        $existing_ticket->set('TKT_price', $ticket_price);
1326
-                    } else {
1327
-                        $existing_ticket->set($field, $value);
1328
-                    }
1329
-                }
1330
-                $ticket = $existing_ticket;
1331
-                // if $create_new_ticket is false then we can safely update the existing ticket.
1332
-                //  Otherwise we have to create a new ticket.
1333
-                if ($create_new_ticket) {
1334
-                    // archive the old ticket first
1335
-                    $existing_ticket->set('TKT_deleted', 1);
1336
-                    $existing_ticket->save();
1337
-                    // make sure this ticket is still recorded in our $saved_tickets
1338
-                    // so we don't run it through the regular trash routine.
1339
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1340
-                    // create new ticket that's a copy of the existing except,
1341
-                    // (a new id of course and not archived) AND has the new TKT_price associated with it.
1342
-                    $new_ticket = clone $existing_ticket;
1343
-                    $new_ticket->set('TKT_ID', 0);
1344
-                    $new_ticket->set('TKT_deleted', 0);
1345
-                    $new_ticket->set('TKT_sold', 0);
1346
-                    // now we need to make sure that $new prices are created as well and attached to new ticket.
1347
-                    $update_prices = true;
1348
-                    $ticket        = $new_ticket;
1349
-                }
1350
-            } else {
1351
-                // no TKT_id so a new ticket
1352
-                $ticket_values['TKT_price'] = $ticket_price;
1353
-                $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1354
-                $update_prices              = true;
1355
-            }
1356
-            if (! $ticket instanceof EE_Ticket) {
1357
-                throw new RuntimeException(
1358
-                    sprintf(
1359
-                        esc_html__(
1360
-                            'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1361
-                            'event_espresso'
1362
-                        ),
1363
-                        print_r($ticket_values, true)
1364
-                    )
1365
-                );
1366
-            }
1367
-            // cap ticket qty by datetime reg limits
1368
-            $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1369
-            // update ticket.
1370
-            $ticket->save();
1371
-            // before going any further make sure our dates are setup correctly
1372
-            // so that the end date is always equal or greater than the start date.
1373
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1374
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1375
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1376
-                $ticket->save();
1377
-            }
1378
-            // initially let's add the ticket to the datetime
1379
-            $datetime->_add_relation_to($ticket, 'Ticket');
1380
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1381
-            // add prices to ticket
1382
-            $prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1383
-                ? $data['edit_prices'][ $row ]
1384
-                : [];
1385
-            $this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1386
-        }
1387
-        // however now we need to handle permanently deleting tickets via the ui.
1388
-        // Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1389
-        // However, it does allow for deleting tickets that have no tickets sold,
1390
-        // in which case we want to get rid of permanently because there is no need to save in db.
1391
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? [] : $old_tickets;
1392
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1393
-        foreach ($tickets_removed as $id) {
1394
-            $id = absint($id);
1395
-            // get the ticket for this id
1396
-            $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1397
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1398
-                continue;
1399
-            }
1400
-            // need to get all the related datetimes on this ticket and remove from every single one of them
1401
-            // (remember this process can ONLY kick off if there are NO tickets sold)
1402
-            $related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1403
-            foreach ($related_datetimes as $related_datetime) {
1404
-                $ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1405
-            }
1406
-            // need to do the same for prices (except these prices can also be deleted because again,
1407
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1408
-            $ticket_to_remove->delete_related_permanently('Price');
1409
-            // finally let's delete this ticket
1410
-            // (which should not be blocked at this point b/c we've removed all our relationships)
1411
-            $ticket_to_remove->delete_permanently();
1412
-        }
1413
-        return [$datetime, $saved_tickets];
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * This attaches a list of given prices to a ticket.
1419
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1420
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1421
-     * price info and prices are automatically "archived" via the ticket.
1422
-     *
1423
-     * @access  private
1424
-     * @param array     $prices_data Array of prices from the form.
1425
-     * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1426
-     * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1427
-     * @return  void
1428
-     * @throws EE_Error
1429
-     * @throws ReflectionException
1430
-     */
1431
-    private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1432
-    {
1433
-        $timezone = $ticket->get_timezone();
1434
-        foreach ($prices_data as $row => $price_data) {
1435
-            $price_values = [
1436
-                'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1437
-                'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1438
-                'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1439
-                'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1440
-                'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1441
-                'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1442
-                'PRC_order'      => $row,
1443
-            ];
1444
-            if ($new_prices || empty($price_values['PRC_ID'])) {
1445
-                $price_values['PRC_ID'] = 0;
1446
-                $price                  = EE_Price::new_instance($price_values, $timezone);
1447
-            } else {
1448
-                $price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1449
-                // update this price with new values
1450
-                foreach ($price_values as $field => $new_price) {
1451
-                    $price->set($field, $new_price);
1452
-                }
1453
-            }
1454
-            if (! $price instanceof EE_Price) {
1455
-                throw new RuntimeException(
1456
-                    sprintf(
1457
-                        esc_html__(
1458
-                            'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1459
-                            'event_espresso'
1460
-                        ),
1461
-                        print_r($price_values, true)
1462
-                    )
1463
-                );
1464
-            }
1465
-            $price->save();
1466
-            $ticket->_add_relation_to($price, 'Price');
1467
-        }
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Add in our autosave ajax handlers
1473
-     *
1474
-     */
1475
-    protected function _ee_autosave_create_new()
1476
-    {
1477
-    }
1478
-
1479
-
1480
-    /**
1481
-     * More autosave handlers.
1482
-     */
1483
-    protected function _ee_autosave_edit()
1484
-    {
1485
-        // TEMPORARILY EXITING CAUSE THIS IS A TODO
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * @throws EE_Error
1491
-     * @throws ReflectionException
1492
-     */
1493
-    private function _generate_publish_box_extra_content()
1494
-    {
1495
-        // load formatter helper
1496
-        // args for getting related registrations
1497
-        $approved_query_args        = [
1498
-            [
1499
-                'REG_deleted' => 0,
1500
-                'STS_ID'      => EEM_Registration::status_id_approved,
1501
-            ],
1502
-        ];
1503
-        $not_approved_query_args    = [
1504
-            [
1505
-                'REG_deleted' => 0,
1506
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1507
-            ],
1508
-        ];
1509
-        $pending_payment_query_args = [
1510
-            [
1511
-                'REG_deleted' => 0,
1512
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1513
-            ],
1514
-        ];
1515
-        // publish box
1516
-        $publish_box_extra_args = [
1517
-            'view_approved_reg_url'        => add_query_arg(
1518
-                [
1519
-                    'action'      => 'default',
1520
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1521
-                    '_reg_status' => EEM_Registration::status_id_approved,
1522
-                    'use_filters' => true,
1523
-                ],
1524
-                REG_ADMIN_URL
1525
-            ),
1526
-            'view_not_approved_reg_url'    => add_query_arg(
1527
-                [
1528
-                    'action'      => 'default',
1529
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1530
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1531
-                    'use_filters' => true,
1532
-                ],
1533
-                REG_ADMIN_URL
1534
-            ),
1535
-            'view_pending_payment_reg_url' => add_query_arg(
1536
-                [
1537
-                    'action'      => 'default',
1538
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1539
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1540
-                    'use_filters' => true,
1541
-                ],
1542
-                REG_ADMIN_URL
1543
-            ),
1544
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1545
-                'Registration',
1546
-                $approved_query_args
1547
-            ),
1548
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1549
-                'Registration',
1550
-                $not_approved_query_args
1551
-            ),
1552
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1553
-                'Registration',
1554
-                $pending_payment_query_args
1555
-            ),
1556
-            'misc_pub_section_class'       => apply_filters(
1557
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1558
-                'misc-pub-section'
1559
-            ),
1560
-        ];
1561
-        ob_start();
1562
-        do_action(
1563
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1564
-            $this->_cpt_model_obj
1565
-        );
1566
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1567
-        // load template
1568
-        EEH_Template::display_template(
1569
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1570
-            $publish_box_extra_args
1571
-        );
1572
-    }
1573
-
1574
-
1575
-    /**
1576
-     * @return EE_Event
1577
-     */
1578
-    public function get_event_object()
1579
-    {
1580
-        return $this->_cpt_model_obj;
1581
-    }
1582
-
1583
-
1584
-
1585
-
1586
-    /** METABOXES * */
1587
-    /**
1588
-     * _register_event_editor_meta_boxes
1589
-     * add all metaboxes related to the event_editor
1590
-     *
1591
-     * @return void
1592
-     * @throws EE_Error
1593
-     * @throws ReflectionException
1594
-     */
1595
-    protected function _register_event_editor_meta_boxes()
1596
-    {
1597
-        $this->verify_cpt_object();
1598
-        add_meta_box(
1599
-            'espresso_event_editor_tickets',
1600
-            esc_html__('Event Datetime & Ticket', 'event_espresso'),
1601
-            [$this, 'ticket_metabox'],
1602
-            $this->page_slug,
1603
-            'normal',
1604
-            'high'
1605
-        );
1606
-        add_meta_box(
1607
-            'espresso_event_editor_event_options',
1608
-            esc_html__('Event Registration Options', 'event_espresso'),
1609
-            [$this, 'registration_options_meta_box'],
1610
-            $this->page_slug,
1611
-            'side'
1612
-        );
1613
-        // NOTE: if you're looking for other metaboxes in here,
1614
-        // where a metabox has a related management page in the admin
1615
-        // you will find it setup in the related management page's "_Hooks" file.
1616
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1617
-    }
1618
-
1619
-
1620
-    /**
1621
-     * @throws DomainException
1622
-     * @throws EE_Error
1623
-     * @throws ReflectionException
1624
-     */
1625
-    public function ticket_metabox()
1626
-    {
1627
-        $existing_datetime_ids = $existing_ticket_ids = [];
1628
-        // defaults for template args
1629
-        $template_args = [
1630
-            'ticket_rows'              => '',
1631
-            'total_ticket_rows'        => 1,
1632
-            'trash_icon'               => 'ee-lock-icon',
1633
-            'disabled'                 => '',
1634
-        ];
1635
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1636
-        /**
1637
-         * 1. Start with retrieving Datetimes
1638
-         * 2. Fore each datetime get related tickets
1639
-         * 3. For each ticket get related prices
1640
-         */
1641
-        $times          = EEM_Datetime::instance()->get_all_event_dates($event_id);
1642
-        $first_datetime = reset($times);
1643
-        // do we get related tickets?
1644
-        if (
1645
-            $first_datetime instanceof EE_Datetime
1646
-            && $first_datetime->ID() !== 0
1647
-        ) {
1648
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1649
-            $template_args['time']   = $first_datetime;
1650
-            $related_tickets         = $first_datetime->tickets(
1651
-                [
1652
-                    ['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1653
-                    'default_where_conditions' => 'none',
1654
-                ]
1655
-            );
1656
-            if (! empty($related_tickets)) {
1657
-                $template_args['total_ticket_rows'] = count($related_tickets);
1658
-                $row                                = 0;
1659
-                foreach ($related_tickets as $ticket) {
1660
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1661
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1662
-                    $row++;
1663
-                }
1664
-            } else {
1665
-                $template_args['total_ticket_rows'] = 1;
1666
-                $ticket                       = EEM_Ticket::instance()->create_default_object();
1667
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1668
-            }
1669
-        } else {
1670
-            $template_args['time']        = $times[0];
1671
-            $tickets                      = EEM_Ticket::instance()->get_all_default_tickets();
1672
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1673
-            // NOTE: we're just sending the first default row
1674
-            // (decaf can't manage default tickets so this should be sufficient);
1675
-        }
1676
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1677
-            'event_editor_event_datetimes_help_tab'
1678
-        );
1679
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1680
-        $template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1681
-        $template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1682
-        $template_args['ticket_js_structure']      = $this->_get_ticket_row(
1683
-            EEM_Ticket::instance()->create_default_object(),
1684
-            true
1685
-        );
1686
-        $template                                  = apply_filters(
1687
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1688
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1689
-        );
1690
-        EEH_Template::display_template($template, $template_args);
1691
-    }
1692
-
1693
-
1694
-    /**
1695
-     * Setup an individual ticket form for the decaf event editor page
1696
-     *
1697
-     * @access private
1698
-     * @param EE_Ticket $ticket   the ticket object
1699
-     * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1700
-     * @param int       $row
1701
-     * @return string generated html for the ticket row.
1702
-     * @throws EE_Error
1703
-     * @throws ReflectionException
1704
-     */
1705
-    private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1706
-    {
1707
-        $template_args = [
1708
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1709
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1710
-                : '',
1711
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1712
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1713
-            'TKT_name'            => $ticket->get('TKT_name'),
1714
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1715
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1716
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1717
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1718
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1719
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1720
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1721
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1722
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1723
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1724
-                : ' disabled=disabled',
1725
-        ];
1726
-        $price         = $ticket->ID() !== 0
1727
-            ? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1728
-            : null;
1729
-        $price         = $price instanceof EE_Price
1730
-            ? $price
1731
-            : EEM_Price::instance()->create_default_object();
1732
-        $price_args    = [
1733
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1734
-            'PRC_amount'            => $price->get('PRC_amount'),
1735
-            'PRT_ID'                => $price->get('PRT_ID'),
1736
-            'PRC_ID'                => $price->get('PRC_ID'),
1737
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1738
-        ];
1739
-        // make sure we have default start and end dates if skeleton
1740
-        // handle rows that should NOT be empty
1741
-        if (empty($template_args['TKT_start_date'])) {
1742
-            // if empty then the start date will be now.
1743
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1744
-        }
1745
-        if (empty($template_args['TKT_end_date'])) {
1746
-            // get the earliest datetime (if present);
1747
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1748
-                ? $this->_cpt_model_obj->get_first_related(
1749
-                    'Datetime',
1750
-                    ['order_by' => ['DTT_EVT_start' => 'ASC']]
1751
-                )
1752
-                : null;
1753
-            $template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1754
-                ? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1755
-                : date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1756
-        }
1757
-        $template_args = array_merge($template_args, $price_args);
1758
-        $template      = apply_filters(
1759
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1760
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1761
-            $ticket
1762
-        );
1763
-        return EEH_Template::display_template($template, $template_args, true);
1764
-    }
1765
-
1766
-
1767
-    /**
1768
-     * @throws EE_Error
1769
-     * @throws ReflectionException
1770
-     */
1771
-    public function registration_options_meta_box()
1772
-    {
1773
-        $yes_no_values             = [
1774
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1775
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1776
-        ];
1777
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1778
-            [
1779
-                EEM_Registration::status_id_cancelled,
1780
-                EEM_Registration::status_id_declined,
1781
-                EEM_Registration::status_id_incomplete,
1782
-            ],
1783
-            true
1784
-        );
1785
-        // $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1786
-        $template_args['_event']                          = $this->_cpt_model_obj;
1787
-        $template_args['event']                           = $this->_cpt_model_obj;
1788
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1789
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1790
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1791
-            'default_reg_status',
1792
-            $default_reg_status_values,
1793
-            $this->_cpt_model_obj->default_registration_status()
1794
-        );
1795
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1796
-            'display_desc',
1797
-            $yes_no_values,
1798
-            $this->_cpt_model_obj->display_description()
1799
-        );
1800
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1801
-            'display_ticket_selector',
1802
-            $yes_no_values,
1803
-            $this->_cpt_model_obj->display_ticket_selector(),
1804
-            '',
1805
-            '',
1806
-            false
1807
-        );
1808
-        $template_args['additional_registration_options'] = apply_filters(
1809
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1810
-            '',
1811
-            $template_args,
1812
-            $yes_no_values,
1813
-            $default_reg_status_values
1814
-        );
1815
-        EEH_Template::display_template(
1816
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1817
-            $template_args
1818
-        );
1819
-    }
1820
-
1821
-
1822
-    /**
1823
-     * _get_events()
1824
-     * This method simply returns all the events (for the given _view and paging)
1825
-     *
1826
-     * @access public
1827
-     * @param int  $per_page     count of items per page (20 default);
1828
-     * @param int  $current_page what is the current page being viewed.
1829
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1830
-     *                           If FALSE then we return an array of event objects
1831
-     *                           that match the given _view and paging parameters.
1832
-     * @return array|int         an array of event objects or a count of them.
1833
-     * @throws Exception
1834
-     */
1835
-    public function get_events($per_page = 10, $current_page = 1, $count = false)
1836
-    {
1837
-        $EEM_Event   = $this->_event_model();
1838
-        $offset      = ($current_page - 1) * $per_page;
1839
-        $limit       = $count ? null : $offset . ',' . $per_page;
1840
-        $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1841
-        $order       = $this->request->getRequestParam('order', 'DESC');
1842
-        $month_range = $this->request->getRequestParam('month_range');
1843
-        if ($month_range) {
1844
-            $pieces = explode(' ', $month_range, 3);
1845
-            // simulate the FIRST day of the month, that fixes issues for months like February
1846
-            // where PHP doesn't know what to assume for date.
1847
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1848
-            $month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1849
-            $year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1850
-        }
1851
-        $where  = [];
1852
-        $status = $this->request->getRequestParam('status');
1853
-        // determine what post_status our condition will have for the query.
1854
-        switch ($status) {
1855
-            case 'month':
1856
-            case 'today':
1857
-            case null:
1858
-            case 'all':
1859
-                break;
1860
-            case 'draft':
1861
-                $where['status'] = ['IN', ['draft', 'auto-draft']];
1862
-                break;
1863
-            default:
1864
-                $where['status'] = $status;
1865
-        }
1866
-        // categories? The default for all categories is -1
1867
-        $category = $this->request->getRequestParam('EVT_CAT', -1, 'int');
1868
-        if ($category !== -1) {
1869
-            $where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1870
-            $where['Term_Taxonomy.term_id']  = $category;
1871
-        }
1872
-        // date where conditions
1873
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1874
-        if ($month_range) {
1875
-            $DateTime = new DateTime(
1876
-                $year_r . '-' . $month_r . '-01 00:00:00',
1877
-                new DateTimeZone('UTC')
1878
-            );
1879
-            $start    = $DateTime->getTimestamp();
1880
-            // set the datetime to be the end of the month
1881
-            $DateTime->setDate(
1882
-                $year_r,
1883
-                $month_r,
1884
-                $DateTime->format('t')
1885
-            )->setTime(23, 59, 59);
1886
-            $end                             = $DateTime->getTimestamp();
1887
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1888
-        } elseif ($status === 'today') {
1889
-            $DateTime                        =
1890
-                new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1891
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1892
-            $end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1893
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1894
-        } elseif ($status === 'month') {
1895
-            $now                             = date('Y-m-01');
1896
-            $DateTime                        =
1897
-                new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1898
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1899
-            $end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1900
-                                                        ->setTime(23, 59, 59)
1901
-                                                        ->format(implode(' ', $start_formats));
1902
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1903
-        }
1904
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1905
-            $where['EVT_wp_user'] = get_current_user_id();
1906
-        } else {
1907
-            if (! isset($where['status'])) {
1908
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1909
-                    $where['OR'] = [
1910
-                        'status*restrict_private' => ['!=', 'private'],
1911
-                        'AND'                     => [
1912
-                            'status*inclusive' => ['=', 'private'],
1913
-                            'EVT_wp_user'      => get_current_user_id(),
1914
-                        ],
1915
-                    ];
1916
-                }
1917
-            }
1918
-        }
1919
-        $wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
1920
-        if (
1921
-            $wp_user
1922
-            && $wp_user !== get_current_user_id()
1923
-            && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1924
-        ) {
1925
-            $where['EVT_wp_user'] = $wp_user;
1926
-        }
1927
-        // search query handling
1928
-        $search_term = $this->request->getRequestParam('s');
1929
-        if ($search_term) {
1930
-            $search_term = '%' . $search_term . '%';
1931
-            $where['OR'] = [
1932
-                'EVT_name'       => ['LIKE', $search_term],
1933
-                'EVT_desc'       => ['LIKE', $search_term],
1934
-                'EVT_short_desc' => ['LIKE', $search_term],
1935
-            ];
1936
-        }
1937
-        // filter events by venue.
1938
-        $venue = $this->request->getRequestParam('venue', 0, 'int');
1939
-        if ($venue) {
1940
-            $where['Venue.VNU_ID'] = $venue;
1941
-        }
1942
-        $request_params = $this->request->requestParams();
1943
-        $where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
1944
-        $query_params   = apply_filters(
1945
-            'FHEE__Events_Admin_Page__get_events__query_params',
1946
-            [
1947
-                $where,
1948
-                'limit'    => $limit,
1949
-                'order_by' => $orderby,
1950
-                'order'    => $order,
1951
-                'group_by' => 'EVT_ID',
1952
-            ],
1953
-            $request_params
1954
-        );
1955
-
1956
-        // let's first check if we have special requests coming in.
1957
-        $active_status = $this->request->getRequestParam('active_status');
1958
-        if ($active_status) {
1959
-            switch ($active_status) {
1960
-                case 'upcoming':
1961
-                    return $EEM_Event->get_upcoming_events($query_params, $count);
1962
-                case 'expired':
1963
-                    return $EEM_Event->get_expired_events($query_params, $count);
1964
-                case 'active':
1965
-                    return $EEM_Event->get_active_events($query_params, $count);
1966
-                case 'inactive':
1967
-                    return $EEM_Event->get_inactive_events($query_params, $count);
1968
-            }
1969
-        }
1970
-
1971
-        return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * handling for WordPress CPT actions (trash, restore, delete)
1977
-     *
1978
-     * @param string $post_id
1979
-     * @throws EE_Error
1980
-     * @throws ReflectionException
1981
-     */
1982
-    public function trash_cpt_item($post_id)
1983
-    {
1984
-        $this->request->setRequestParam('EVT_ID', $post_id);
1985
-        $this->_trash_or_restore_event('trash', false);
1986
-    }
1987
-
1988
-
1989
-    /**
1990
-     * @param string $post_id
1991
-     * @throws EE_Error
1992
-     * @throws ReflectionException
1993
-     */
1994
-    public function restore_cpt_item($post_id)
1995
-    {
1996
-        $this->request->setRequestParam('EVT_ID', $post_id);
1997
-        $this->_trash_or_restore_event('draft', false);
1998
-    }
1999
-
2000
-
2001
-    /**
2002
-     * @param string $post_id
2003
-     * @throws EE_Error
2004
-     * @throws EE_Error
2005
-     */
2006
-    public function delete_cpt_item($post_id)
2007
-    {
2008
-        throw new EE_Error(
2009
-            esc_html__(
2010
-                'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2011
-                'event_espresso'
2012
-            )
2013
-        );
2014
-        // $this->request->setRequestParam('EVT_ID', $post_id);
2015
-        // $this->_delete_event();
2016
-    }
2017
-
2018
-
2019
-    /**
2020
-     * _trash_or_restore_event
2021
-     *
2022
-     * @access protected
2023
-     * @param string $event_status
2024
-     * @param bool   $redirect_after
2025
-     * @throws EE_Error
2026
-     * @throws EE_Error
2027
-     * @throws ReflectionException
2028
-     */
2029
-    protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2030
-    {
2031
-        // determine the event id and set to array.
2032
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2033
-        // loop thru events
2034
-        if ($EVT_ID) {
2035
-            // clean status
2036
-            $event_status = sanitize_key($event_status);
2037
-            // grab status
2038
-            if (! empty($event_status)) {
2039
-                $success = $this->_change_event_status($EVT_ID, $event_status);
2040
-            } else {
2041
-                $success = false;
2042
-                $msg     = esc_html__(
2043
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2044
-                    'event_espresso'
2045
-                );
2046
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2047
-            }
2048
-        } else {
2049
-            $success = false;
2050
-            $msg     = esc_html__(
2051
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2052
-                'event_espresso'
2053
-            );
2054
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2055
-        }
2056
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2057
-        if ($redirect_after) {
2058
-            $this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2059
-        }
2060
-    }
2061
-
2062
-
2063
-    /**
2064
-     * _trash_or_restore_events
2065
-     *
2066
-     * @access protected
2067
-     * @param string $event_status
2068
-     * @return void
2069
-     * @throws EE_Error
2070
-     * @throws EE_Error
2071
-     * @throws ReflectionException
2072
-     */
2073
-    protected function _trash_or_restore_events($event_status = 'trash')
2074
-    {
2075
-        // clean status
2076
-        $event_status = sanitize_key($event_status);
2077
-        // grab status
2078
-        if (! empty($event_status)) {
2079
-            $success = true;
2080
-            // determine the event id and set to array.
2081
-            $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2082
-            // loop thru events
2083
-            foreach ($EVT_IDs as $EVT_ID) {
2084
-                if ($EVT_ID = absint($EVT_ID)) {
2085
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
2086
-                    $success = $results !== false ? $success : false;
2087
-                } else {
2088
-                    $msg = sprintf(
2089
-                        esc_html__(
2090
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2091
-                            'event_espresso'
2092
-                        ),
2093
-                        $EVT_ID
2094
-                    );
2095
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2096
-                    $success = false;
2097
-                }
2098
-            }
2099
-        } else {
2100
-            $success = false;
2101
-            $msg     = esc_html__(
2102
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2103
-                'event_espresso'
2104
-            );
2105
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2106
-        }
2107
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2108
-        $success = $success ? 2 : false;
2109
-        $action  = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2110
-        $this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2111
-    }
2112
-
2113
-
2114
-    /**
2115
-     * @param int    $EVT_ID
2116
-     * @param string $event_status
2117
-     * @return bool
2118
-     * @throws EE_Error
2119
-     * @throws ReflectionException
2120
-     */
2121
-    private function _change_event_status($EVT_ID = 0, $event_status = '')
2122
-    {
2123
-        // grab event id
2124
-        if (! $EVT_ID) {
2125
-            $msg = esc_html__(
2126
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2127
-                'event_espresso'
2128
-            );
2129
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2130
-            return false;
2131
-        }
2132
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2133
-        // clean status
2134
-        $event_status = sanitize_key($event_status);
2135
-        // grab status
2136
-        if (empty($event_status)) {
2137
-            $msg = esc_html__(
2138
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2139
-                'event_espresso'
2140
-            );
2141
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2142
-            return false;
2143
-        }
2144
-        // was event trashed or restored ?
2145
-        switch ($event_status) {
2146
-            case 'draft':
2147
-                $action = 'restored from the trash';
2148
-                $hook   = 'AHEE_event_restored_from_trash';
2149
-                break;
2150
-            case 'trash':
2151
-                $action = 'moved to the trash';
2152
-                $hook   = 'AHEE_event_moved_to_trash';
2153
-                break;
2154
-            default:
2155
-                $action = 'updated';
2156
-                $hook   = false;
2157
-        }
2158
-        // use class to change status
2159
-        $this->_cpt_model_obj->set_status($event_status);
2160
-        $success = $this->_cpt_model_obj->save();
2161
-        if (! $success) {
2162
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2163
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2164
-            return false;
2165
-        }
2166
-        if ($hook) {
2167
-            do_action($hook);
2168
-            // fake the action hook in EE_Soft_Delete_Base_Class::delete_or_restore()
2169
-            // because events side step that and it otherwise won't get called
2170
-            do_action(
2171
-                'AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after',
2172
-                $this->_cpt_model_obj,
2173
-                $hook === 'AHEE_event_moved_to_trash',
2174
-                $success
2175
-            );
2176
-        }
2177
-        return true;
2178
-    }
2179
-
2180
-
2181
-    /**
2182
-     * @param array $event_ids
2183
-     * @return array
2184
-     * @since   4.10.23.p
2185
-     */
2186
-    private function cleanEventIds(array $event_ids)
2187
-    {
2188
-        return array_map('absint', $event_ids);
2189
-    }
2190
-
2191
-
2192
-    /**
2193
-     * @return array
2194
-     * @since   4.10.23.p
2195
-     */
2196
-    private function getEventIdsFromRequest()
2197
-    {
2198
-        if ($this->request->requestParamIsSet('EVT_IDs')) {
2199
-            return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2200
-        } else {
2201
-            return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2202
-        }
2203
-    }
2204
-
2205
-
2206
-    /**
2207
-     * @param bool $preview_delete
2208
-     * @throws EE_Error
2209
-     * @throws ReflectionException
2210
-     */
2211
-    protected function _delete_event($preview_delete = true)
2212
-    {
2213
-        $this->_delete_events($preview_delete);
2214
-    }
2215
-
2216
-
2217
-    /**
2218
-     * Gets the tree traversal batch persister.
2219
-     *
2220
-     * @return NodeGroupDao
2221
-     * @throws InvalidArgumentException
2222
-     * @throws InvalidDataTypeException
2223
-     * @throws InvalidInterfaceException
2224
-     * @since 4.10.12.p
2225
-     */
2226
-    protected function getModelObjNodeGroupPersister()
2227
-    {
2228
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2229
-            $this->model_obj_node_group_persister =
2230
-                $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2231
-        }
2232
-        return $this->model_obj_node_group_persister;
2233
-    }
2234
-
2235
-
2236
-    /**
2237
-     * @param bool $preview_delete
2238
-     * @return void
2239
-     * @throws EE_Error
2240
-     * @throws ReflectionException
2241
-     */
2242
-    protected function _delete_events($preview_delete = true)
2243
-    {
2244
-        $event_ids = $this->getEventIdsFromRequest();
2245
-        if ($preview_delete) {
2246
-            $this->generateDeletionPreview($event_ids);
2247
-        } else {
2248
-            foreach ($event_ids as $event_id) {
2249
-                $event = EEM_Event::instance()->get_one_by_ID($event_id);
2250
-                if ($event instanceof EE_Event) {
2251
-                    $event->delete_permanently();
2252
-                }
2253
-            }
2254
-        }
2255
-    }
2256
-
2257
-
2258
-    /**
2259
-     * @param array $event_ids
2260
-     */
2261
-    protected function generateDeletionPreview(array $event_ids)
2262
-    {
2263
-        $event_ids = $this->cleanEventIds($event_ids);
2264
-        // Set a code we can use to reference this deletion task in the batch jobs and preview page.
2265
-        $deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2266
-        $return_url        = EE_Admin_Page::add_query_args_and_nonce(
2267
-            [
2268
-                'action'            => 'preview_deletion',
2269
-                'deletion_job_code' => $deletion_job_code,
2270
-            ],
2271
-            $this->_admin_base_url
2272
-        );
2273
-        EEH_URL::safeRedirectAndExit(
2274
-            EE_Admin_Page::add_query_args_and_nonce(
2275
-                [
2276
-                    'page'              => 'espresso_batch',
2277
-                    'batch'             => EED_Batch::batch_job,
2278
-                    'EVT_IDs'           => $event_ids,
2279
-                    'deletion_job_code' => $deletion_job_code,
2280
-                    'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2281
-                    'return_url'        => urlencode($return_url),
2282
-                ],
2283
-                admin_url()
2284
-            )
2285
-        );
2286
-    }
2287
-
2288
-
2289
-    /**
2290
-     * Checks for a POST submission
2291
-     *
2292
-     * @since 4.10.12.p
2293
-     */
2294
-    protected function confirmDeletion()
2295
-    {
2296
-        $deletion_redirect_logic = $this->getLoader()->getShared(
2297
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'
2298
-        );
2299
-        $deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2300
-    }
2301
-
2302
-
2303
-    /**
2304
-     * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2305
-     *
2306
-     * @throws EE_Error
2307
-     * @since 4.10.12.p
2308
-     */
2309
-    protected function previewDeletion()
2310
-    {
2311
-        $preview_deletion_logic = $this->getLoader()->getShared(
2312
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'
2313
-        );
2314
-        $this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2315
-        $this->display_admin_page_with_no_sidebar();
2316
-    }
2317
-
2318
-
2319
-    /**
2320
-     * get total number of events
2321
-     *
2322
-     * @access public
2323
-     * @return int
2324
-     * @throws EE_Error
2325
-     * @throws EE_Error
2326
-     */
2327
-    public function total_events()
2328
-    {
2329
-        return EEM_Event::instance()->count(
2330
-            ['caps' => 'read_admin'],
2331
-            'EVT_ID',
2332
-            true
2333
-        );
2334
-    }
2335
-
2336
-
2337
-    /**
2338
-     * get total number of draft events
2339
-     *
2340
-     * @access public
2341
-     * @return int
2342
-     * @throws EE_Error
2343
-     * @throws EE_Error
2344
-     */
2345
-    public function total_events_draft()
2346
-    {
2347
-        return EEM_Event::instance()->count(
2348
-            [
2349
-                ['status' => ['IN', ['draft', 'auto-draft']]],
2350
-                'caps' => 'read_admin',
2351
-            ],
2352
-            'EVT_ID',
2353
-            true
2354
-        );
2355
-    }
2356
-
2357
-
2358
-    /**
2359
-     * get total number of trashed events
2360
-     *
2361
-     * @access public
2362
-     * @return int
2363
-     * @throws EE_Error
2364
-     * @throws EE_Error
2365
-     */
2366
-    public function total_trashed_events()
2367
-    {
2368
-        return EEM_Event::instance()->count(
2369
-            [
2370
-                ['status' => 'trash'],
2371
-                'caps' => 'read_admin',
2372
-            ],
2373
-            'EVT_ID',
2374
-            true
2375
-        );
2376
-    }
2377
-
2378
-
2379
-    /**
2380
-     *    _default_event_settings
2381
-     *    This generates the Default Settings Tab
2382
-     *
2383
-     * @return void
2384
-     * @throws EE_Error
2385
-     */
2386
-    protected function _default_event_settings()
2387
-    {
2388
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2389
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
2390
-        $this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2391
-        $this->display_admin_page_with_sidebar();
2392
-    }
2393
-
2394
-
2395
-    /**
2396
-     * Return the form for event settings.
2397
-     *
2398
-     * @return EE_Form_Section_Proper
2399
-     * @throws EE_Error
2400
-     */
2401
-    protected function _default_event_settings_form()
2402
-    {
2403
-        $registration_config              = EE_Registry::instance()->CFG->registration;
2404
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2405
-        // exclude
2406
-            [
2407
-                EEM_Registration::status_id_cancelled,
2408
-                EEM_Registration::status_id_declined,
2409
-                EEM_Registration::status_id_incomplete,
2410
-                EEM_Registration::status_id_wait_list,
2411
-            ],
2412
-            true
2413
-        );
2414
-        return new EE_Form_Section_Proper(
2415
-            [
2416
-                'name'            => 'update_default_event_settings',
2417
-                'html_id'         => 'update_default_event_settings',
2418
-                'html_class'      => 'form-table',
2419
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2420
-                'subsections'     => apply_filters(
2421
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2422
-                    [
2423
-                        'default_reg_status'  => new EE_Select_Input(
2424
-                            $registration_stati_for_selection,
2425
-                            [
2426
-                                'default'         => isset($registration_config->default_STS_ID)
2427
-                                                     && array_key_exists(
2428
-                                                         $registration_config->default_STS_ID,
2429
-                                                         $registration_stati_for_selection
2430
-                                                     )
2431
-                                    ? sanitize_text_field($registration_config->default_STS_ID)
2432
-                                    : EEM_Registration::status_id_pending_payment,
2433
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2434
-                                                     . EEH_Template::get_help_tab_link(
2435
-                                                         'default_settings_status_help_tab'
2436
-                                                     ),
2437
-                                'html_help_text'  => esc_html__(
2438
-                                    '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.',
2439
-                                    'event_espresso'
2440
-                                ),
2441
-                            ]
2442
-                        ),
2443
-                        'default_max_tickets' => new EE_Integer_Input(
2444
-                            [
2445
-                                'default'         => isset($registration_config->default_maximum_number_of_tickets)
2446
-                                    ? $registration_config->default_maximum_number_of_tickets
2447
-                                    : EEM_Event::get_default_additional_limit(),
2448
-                                'html_label_text' => esc_html__(
2449
-                                    'Default Maximum Tickets Allowed Per Order:',
2450
-                                    'event_espresso'
2451
-                                )
2452
-                                . EEH_Template::get_help_tab_link(
2453
-                                    'default_maximum_tickets_help_tab"'
2454
-                                ),
2455
-                                'html_help_text'  => esc_html__(
2456
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2457
-                                    'event_espresso'
2458
-                                ),
2459
-                            ]
2460
-                        ),
2461
-                    ]
2462
-                ),
2463
-            ]
2464
-        );
2465
-    }
2466
-
2467
-
2468
-    /**
2469
-     * _update_default_event_settings
2470
-     *
2471
-     * @access protected
2472
-     * @return void
2473
-     * @throws EE_Error
2474
-     */
2475
-    protected function _update_default_event_settings()
2476
-    {
2477
-        $registration_config = EE_Registry::instance()->CFG->registration;
2478
-        $form                = $this->_default_event_settings_form();
2479
-        if ($form->was_submitted()) {
2480
-            $form->receive_form_submission();
2481
-            if ($form->is_valid()) {
2482
-                $valid_data = $form->valid_data();
2483
-                if (isset($valid_data['default_reg_status'])) {
2484
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2485
-                }
2486
-                if (isset($valid_data['default_max_tickets'])) {
2487
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2488
-                }
2489
-                // update because data was valid!
2490
-                EE_Registry::instance()->CFG->update_espresso_config();
2491
-                EE_Error::overwrite_success();
2492
-                EE_Error::add_success(
2493
-                    esc_html__('Default Event Settings were updated', 'event_espresso')
2494
-                );
2495
-            }
2496
-        }
2497
-        $this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2498
-    }
2499
-
2500
-
2501
-    /*************        Templates        *************
2502
-     *
2503
-     * @throws EE_Error
2504
-     */
2505
-    protected function _template_settings()
2506
-    {
2507
-        $this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2508
-        $this->_template_args['preview_img']  = '<img src="'
2509
-                                                . EVENTS_ASSETS_URL
2510
-                                                . '/images/'
2511
-                                                . 'caffeinated_template_features.jpg" alt="'
2512
-                                                . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2513
-                                                . '" />';
2514
-        $this->_template_args['preview_text'] = '<strong>'
2515
-                                                . esc_html__(
2516
-                                                    '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.',
2517
-                                                    'event_espresso'
2518
-                                                ) . '</strong>';
2519
-        $this->display_admin_caf_preview_page('template_settings_tab');
2520
-    }
2521
-
2522
-
2523
-    /** Event Category Stuff **/
2524
-    /**
2525
-     * set the _category property with the category object for the loaded page.
2526
-     *
2527
-     * @access private
2528
-     * @return void
2529
-     */
2530
-    private function _set_category_object()
2531
-    {
2532
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2533
-            return;
2534
-        } //already have the category object so get out.
2535
-        // set default category object
2536
-        $this->_set_empty_category_object();
2537
-        // only set if we've got an id
2538
-        $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2539
-        if (! $category_ID) {
2540
-            return;
2541
-        }
2542
-        $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2543
-        if (! empty($term)) {
2544
-            $this->_category->category_name       = $term->name;
2545
-            $this->_category->category_identifier = $term->slug;
2546
-            $this->_category->category_desc       = $term->description;
2547
-            $this->_category->id                  = $term->term_id;
2548
-            $this->_category->parent              = $term->parent;
2549
-        }
2550
-    }
2551
-
2552
-
2553
-    /**
2554
-     * Clears out category properties.
2555
-     */
2556
-    private function _set_empty_category_object()
2557
-    {
2558
-        $this->_category                = new stdClass();
2559
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2560
-        $this->_category->id            = $this->_category->parent = 0;
2561
-    }
2562
-
2563
-
2564
-    /**
2565
-     * @throws EE_Error
2566
-     */
2567
-    protected function _category_list_table()
2568
-    {
2569
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2570
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2571
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2572
-            'add_category',
2573
-            'add_category',
2574
-            [],
2575
-            'add-new-h2'
2576
-        );
2577
-        $this->display_admin_list_table_page_with_sidebar();
2578
-    }
2579
-
2580
-
2581
-    /**
2582
-     * Output category details view.
2583
-     *
2584
-     * @throws EE_Error
2585
-     * @throws EE_Error
2586
-     */
2587
-    protected function _category_details($view)
2588
-    {
2589
-        // load formatter helper
2590
-        // load field generator helper
2591
-        $route = $view == 'edit' ? 'update_category' : 'insert_category';
2592
-        $this->_set_add_edit_form_tags($route);
2593
-        $this->_set_category_object();
2594
-        $id            = ! empty($this->_category->id) ? $this->_category->id : '';
2595
-        $delete_action = 'delete_category';
2596
-        // custom redirect
2597
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2598
-            ['action' => 'category_list'],
2599
-            $this->_admin_base_url
2600
-        );
2601
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2602
-        // take care of contents
2603
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2604
-        $this->display_admin_page_with_sidebar();
2605
-    }
2606
-
2607
-
2608
-    /**
2609
-     * Output category details content.
2610
-     */
2611
-    protected function _category_details_content()
2612
-    {
2613
-        $editor_args['category_desc'] = [
2614
-            'type'          => 'wp_editor',
2615
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2616
-            'class'         => 'my_editor_custom',
2617
-            'wpeditor_args' => ['media_buttons' => false],
2618
-        ];
2619
-        $_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2620
-        $all_terms                    = get_terms(
2621
-            [EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2622
-            ['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2623
-        );
2624
-        // setup category select for term parents.
2625
-        $category_select_values[] = [
2626
-            'text' => esc_html__('No Parent', 'event_espresso'),
2627
-            'id'   => 0,
2628
-        ];
2629
-        foreach ($all_terms as $term) {
2630
-            $category_select_values[] = [
2631
-                'text' => $term->name,
2632
-                'id'   => $term->term_id,
2633
-            ];
2634
-        }
2635
-        $category_select = EEH_Form_Fields::select_input(
2636
-            'category_parent',
2637
-            $category_select_values,
2638
-            $this->_category->parent
2639
-        );
2640
-        $template_args   = [
2641
-            'category'                 => $this->_category,
2642
-            'category_select'          => $category_select,
2643
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2644
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2645
-            'disable'                  => '',
2646
-            'disabled_message'         => false,
2647
-        ];
2648
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2649
-        return EEH_Template::display_template($template, $template_args, true);
2650
-    }
2651
-
2652
-
2653
-    /**
2654
-     * Handles deleting categories.
2655
-     *
2656
-     * @throws EE_Error
2657
-     */
2658
-    protected function _delete_categories()
2659
-    {
2660
-        $category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2661
-        foreach ($category_IDs as $category_ID) {
2662
-            $this->_delete_category($category_ID);
2663
-        }
2664
-        // doesn't matter what page we're coming from... we're going to the same place after delete.
2665
-        $query_args = [
2666
-            'action' => 'category_list',
2667
-        ];
2668
-        $this->_redirect_after_action(0, '', '', $query_args);
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * Handles deleting specific category.
2674
-     *
2675
-     * @param int $cat_id
2676
-     */
2677
-    protected function _delete_category($cat_id)
2678
-    {
2679
-        $cat_id = absint($cat_id);
2680
-        wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2681
-    }
2682
-
2683
-
2684
-    /**
2685
-     * Handles triggering the update or insertion of a new category.
2686
-     *
2687
-     * @param bool $new_category true means we're triggering the insert of a new category.
2688
-     * @throws EE_Error
2689
-     * @throws EE_Error
2690
-     */
2691
-    protected function _insert_or_update_category($new_category)
2692
-    {
2693
-        $cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2694
-        $success = 0; // we already have a success message so lets not send another.
2695
-        if ($cat_id) {
2696
-            $query_args = [
2697
-                'action'     => 'edit_category',
2698
-                'EVT_CAT_ID' => $cat_id,
2699
-            ];
2700
-        } else {
2701
-            $query_args = ['action' => 'add_category'];
2702
-        }
2703
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2704
-    }
2705
-
2706
-
2707
-    /**
2708
-     * Inserts or updates category
2709
-     *
2710
-     * @param bool $update (true indicates we're updating a category).
2711
-     * @return bool|mixed|string
2712
-     */
2713
-    private function _insert_category($update = false)
2714
-    {
2715
-        $category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2716
-        $category_name       = $this->request->getRequestParam('category_name', '');
2717
-        $category_desc       = $this->request->getRequestParam('category_desc', '');
2718
-        $category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2719
-        $category_identifier = $this->request->getRequestParam('category_identifier', '');
2720
-
2721
-        if (empty($category_name)) {
2722
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2723
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2724
-            return false;
2725
-        }
2726
-        $term_args = [
2727
-            'name'        => $category_name,
2728
-            'description' => $category_desc,
2729
-            'parent'      => $category_parent,
2730
-        ];
2731
-        // was the category_identifier input disabled?
2732
-        if ($category_identifier) {
2733
-            $term_args['slug'] = $category_identifier;
2734
-        }
2735
-        $insert_ids = $update
2736
-            ? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2737
-            : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2738
-        if (! is_array($insert_ids)) {
2739
-            $msg = esc_html__(
2740
-                'An error occurred and the category has not been saved to the database.',
2741
-                'event_espresso'
2742
-            );
2743
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2744
-        } else {
2745
-            $category_ID = $insert_ids['term_id'];
2746
-            $msg         =
2747
-                sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2748
-            EE_Error::add_success($msg);
2749
-        }
2750
-        return $category_ID;
2751
-    }
2752
-
2753
-
2754
-    /**
2755
-     * Gets categories or count of categories matching the arguments in the request.
2756
-     *
2757
-     * @param int  $per_page
2758
-     * @param int  $current_page
2759
-     * @param bool $count
2760
-     * @return EE_Term_Taxonomy[]|int
2761
-     * @throws EE_Error
2762
-     * @throws EE_Error
2763
-     */
2764
-    public function get_categories($per_page = 10, $current_page = 1, $count = false)
2765
-    {
2766
-        // testing term stuff
2767
-        $orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2768
-        $order       = $this->request->getRequestParam('order', 'DESC');
2769
-        $limit       = ($current_page - 1) * $per_page;
2770
-        $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2771
-        $search_term = $this->request->getRequestParam('s');
2772
-        if ($search_term) {
2773
-            $search_term = '%' . $search_term . '%';
2774
-            $where['OR'] = [
2775
-                'Term.name'   => ['LIKE', $search_term],
2776
-                'description' => ['LIKE', $search_term],
2777
-            ];
2778
-        }
2779
-        $query_params = [
2780
-            $where,
2781
-            'order_by'   => [$orderby => $order],
2782
-            'limit'      => $limit . ',' . $per_page,
2783
-            'force_join' => ['Term'],
2784
-        ];
2785
-        return $count
2786
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2787
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2788
-    }
2789
-
2790
-    /* end category stuff */
2791
-    /**************/
2792
-
2793
-
2794
-    /**
2795
-     * Callback for the `ee_save_timezone_setting` ajax action.
2796
-     *
2797
-     * @throws EE_Error
2798
-     */
2799
-    public function saveTimezoneString()
2800
-    {
2801
-        $timezone_string = $this->request->getRequestParam('timezone_selected');
2802
-        if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2803
-            EE_Error::add_error(
2804
-                esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2805
-                __FILE__,
2806
-                __FUNCTION__,
2807
-                __LINE__
2808
-            );
2809
-            $this->_template_args['error'] = true;
2810
-            $this->_return_json();
2811
-        }
2812
-
2813
-        update_option('timezone_string', $timezone_string);
2814
-        EE_Error::add_success(
2815
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2816
-        );
2817
-        $this->_template_args['success'] = true;
2818
-        $this->_return_json(true, ['action' => 'create_new']);
2819
-    }
2820
-
2821
-
2822
-    /**
2823 2503
      * @throws EE_Error
2824
-     * @deprecated 4.10.25.p
2825 2504
      */
2826
-    public function save_timezonestring_setting()
2827
-    {
2828
-        $this->saveTimezoneString();
2829
-    }
2505
+	protected function _template_settings()
2506
+	{
2507
+		$this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2508
+		$this->_template_args['preview_img']  = '<img src="'
2509
+												. EVENTS_ASSETS_URL
2510
+												. '/images/'
2511
+												. 'caffeinated_template_features.jpg" alt="'
2512
+												. esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2513
+												. '" />';
2514
+		$this->_template_args['preview_text'] = '<strong>'
2515
+												. esc_html__(
2516
+													'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.',
2517
+													'event_espresso'
2518
+												) . '</strong>';
2519
+		$this->display_admin_caf_preview_page('template_settings_tab');
2520
+	}
2521
+
2522
+
2523
+	/** Event Category Stuff **/
2524
+	/**
2525
+	 * set the _category property with the category object for the loaded page.
2526
+	 *
2527
+	 * @access private
2528
+	 * @return void
2529
+	 */
2530
+	private function _set_category_object()
2531
+	{
2532
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2533
+			return;
2534
+		} //already have the category object so get out.
2535
+		// set default category object
2536
+		$this->_set_empty_category_object();
2537
+		// only set if we've got an id
2538
+		$category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2539
+		if (! $category_ID) {
2540
+			return;
2541
+		}
2542
+		$term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2543
+		if (! empty($term)) {
2544
+			$this->_category->category_name       = $term->name;
2545
+			$this->_category->category_identifier = $term->slug;
2546
+			$this->_category->category_desc       = $term->description;
2547
+			$this->_category->id                  = $term->term_id;
2548
+			$this->_category->parent              = $term->parent;
2549
+		}
2550
+	}
2551
+
2552
+
2553
+	/**
2554
+	 * Clears out category properties.
2555
+	 */
2556
+	private function _set_empty_category_object()
2557
+	{
2558
+		$this->_category                = new stdClass();
2559
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2560
+		$this->_category->id            = $this->_category->parent = 0;
2561
+	}
2562
+
2563
+
2564
+	/**
2565
+	 * @throws EE_Error
2566
+	 */
2567
+	protected function _category_list_table()
2568
+	{
2569
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2570
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2571
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2572
+			'add_category',
2573
+			'add_category',
2574
+			[],
2575
+			'add-new-h2'
2576
+		);
2577
+		$this->display_admin_list_table_page_with_sidebar();
2578
+	}
2579
+
2580
+
2581
+	/**
2582
+	 * Output category details view.
2583
+	 *
2584
+	 * @throws EE_Error
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	protected function _category_details($view)
2588
+	{
2589
+		// load formatter helper
2590
+		// load field generator helper
2591
+		$route = $view == 'edit' ? 'update_category' : 'insert_category';
2592
+		$this->_set_add_edit_form_tags($route);
2593
+		$this->_set_category_object();
2594
+		$id            = ! empty($this->_category->id) ? $this->_category->id : '';
2595
+		$delete_action = 'delete_category';
2596
+		// custom redirect
2597
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2598
+			['action' => 'category_list'],
2599
+			$this->_admin_base_url
2600
+		);
2601
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2602
+		// take care of contents
2603
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2604
+		$this->display_admin_page_with_sidebar();
2605
+	}
2606
+
2607
+
2608
+	/**
2609
+	 * Output category details content.
2610
+	 */
2611
+	protected function _category_details_content()
2612
+	{
2613
+		$editor_args['category_desc'] = [
2614
+			'type'          => 'wp_editor',
2615
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2616
+			'class'         => 'my_editor_custom',
2617
+			'wpeditor_args' => ['media_buttons' => false],
2618
+		];
2619
+		$_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2620
+		$all_terms                    = get_terms(
2621
+			[EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2622
+			['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2623
+		);
2624
+		// setup category select for term parents.
2625
+		$category_select_values[] = [
2626
+			'text' => esc_html__('No Parent', 'event_espresso'),
2627
+			'id'   => 0,
2628
+		];
2629
+		foreach ($all_terms as $term) {
2630
+			$category_select_values[] = [
2631
+				'text' => $term->name,
2632
+				'id'   => $term->term_id,
2633
+			];
2634
+		}
2635
+		$category_select = EEH_Form_Fields::select_input(
2636
+			'category_parent',
2637
+			$category_select_values,
2638
+			$this->_category->parent
2639
+		);
2640
+		$template_args   = [
2641
+			'category'                 => $this->_category,
2642
+			'category_select'          => $category_select,
2643
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2644
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2645
+			'disable'                  => '',
2646
+			'disabled_message'         => false,
2647
+		];
2648
+		$template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2649
+		return EEH_Template::display_template($template, $template_args, true);
2650
+	}
2651
+
2652
+
2653
+	/**
2654
+	 * Handles deleting categories.
2655
+	 *
2656
+	 * @throws EE_Error
2657
+	 */
2658
+	protected function _delete_categories()
2659
+	{
2660
+		$category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2661
+		foreach ($category_IDs as $category_ID) {
2662
+			$this->_delete_category($category_ID);
2663
+		}
2664
+		// doesn't matter what page we're coming from... we're going to the same place after delete.
2665
+		$query_args = [
2666
+			'action' => 'category_list',
2667
+		];
2668
+		$this->_redirect_after_action(0, '', '', $query_args);
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * Handles deleting specific category.
2674
+	 *
2675
+	 * @param int $cat_id
2676
+	 */
2677
+	protected function _delete_category($cat_id)
2678
+	{
2679
+		$cat_id = absint($cat_id);
2680
+		wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2681
+	}
2682
+
2683
+
2684
+	/**
2685
+	 * Handles triggering the update or insertion of a new category.
2686
+	 *
2687
+	 * @param bool $new_category true means we're triggering the insert of a new category.
2688
+	 * @throws EE_Error
2689
+	 * @throws EE_Error
2690
+	 */
2691
+	protected function _insert_or_update_category($new_category)
2692
+	{
2693
+		$cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2694
+		$success = 0; // we already have a success message so lets not send another.
2695
+		if ($cat_id) {
2696
+			$query_args = [
2697
+				'action'     => 'edit_category',
2698
+				'EVT_CAT_ID' => $cat_id,
2699
+			];
2700
+		} else {
2701
+			$query_args = ['action' => 'add_category'];
2702
+		}
2703
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2704
+	}
2705
+
2706
+
2707
+	/**
2708
+	 * Inserts or updates category
2709
+	 *
2710
+	 * @param bool $update (true indicates we're updating a category).
2711
+	 * @return bool|mixed|string
2712
+	 */
2713
+	private function _insert_category($update = false)
2714
+	{
2715
+		$category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2716
+		$category_name       = $this->request->getRequestParam('category_name', '');
2717
+		$category_desc       = $this->request->getRequestParam('category_desc', '');
2718
+		$category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2719
+		$category_identifier = $this->request->getRequestParam('category_identifier', '');
2720
+
2721
+		if (empty($category_name)) {
2722
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2723
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2724
+			return false;
2725
+		}
2726
+		$term_args = [
2727
+			'name'        => $category_name,
2728
+			'description' => $category_desc,
2729
+			'parent'      => $category_parent,
2730
+		];
2731
+		// was the category_identifier input disabled?
2732
+		if ($category_identifier) {
2733
+			$term_args['slug'] = $category_identifier;
2734
+		}
2735
+		$insert_ids = $update
2736
+			? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2737
+			: wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2738
+		if (! is_array($insert_ids)) {
2739
+			$msg = esc_html__(
2740
+				'An error occurred and the category has not been saved to the database.',
2741
+				'event_espresso'
2742
+			);
2743
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2744
+		} else {
2745
+			$category_ID = $insert_ids['term_id'];
2746
+			$msg         =
2747
+				sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2748
+			EE_Error::add_success($msg);
2749
+		}
2750
+		return $category_ID;
2751
+	}
2752
+
2753
+
2754
+	/**
2755
+	 * Gets categories or count of categories matching the arguments in the request.
2756
+	 *
2757
+	 * @param int  $per_page
2758
+	 * @param int  $current_page
2759
+	 * @param bool $count
2760
+	 * @return EE_Term_Taxonomy[]|int
2761
+	 * @throws EE_Error
2762
+	 * @throws EE_Error
2763
+	 */
2764
+	public function get_categories($per_page = 10, $current_page = 1, $count = false)
2765
+	{
2766
+		// testing term stuff
2767
+		$orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2768
+		$order       = $this->request->getRequestParam('order', 'DESC');
2769
+		$limit       = ($current_page - 1) * $per_page;
2770
+		$where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2771
+		$search_term = $this->request->getRequestParam('s');
2772
+		if ($search_term) {
2773
+			$search_term = '%' . $search_term . '%';
2774
+			$where['OR'] = [
2775
+				'Term.name'   => ['LIKE', $search_term],
2776
+				'description' => ['LIKE', $search_term],
2777
+			];
2778
+		}
2779
+		$query_params = [
2780
+			$where,
2781
+			'order_by'   => [$orderby => $order],
2782
+			'limit'      => $limit . ',' . $per_page,
2783
+			'force_join' => ['Term'],
2784
+		];
2785
+		return $count
2786
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2787
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2788
+	}
2789
+
2790
+	/* end category stuff */
2791
+	/**************/
2792
+
2793
+
2794
+	/**
2795
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2796
+	 *
2797
+	 * @throws EE_Error
2798
+	 */
2799
+	public function saveTimezoneString()
2800
+	{
2801
+		$timezone_string = $this->request->getRequestParam('timezone_selected');
2802
+		if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2803
+			EE_Error::add_error(
2804
+				esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2805
+				__FILE__,
2806
+				__FUNCTION__,
2807
+				__LINE__
2808
+			);
2809
+			$this->_template_args['error'] = true;
2810
+			$this->_return_json();
2811
+		}
2812
+
2813
+		update_option('timezone_string', $timezone_string);
2814
+		EE_Error::add_success(
2815
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2816
+		);
2817
+		$this->_template_args['success'] = true;
2818
+		$this->_return_json(true, ['action' => 'create_new']);
2819
+	}
2820
+
2821
+
2822
+	/**
2823
+	 * @throws EE_Error
2824
+	 * @deprecated 4.10.25.p
2825
+	 */
2826
+	public function save_timezonestring_setting()
2827
+	{
2828
+		$this->saveTimezoneString();
2829
+	}
2830 2830
 }
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -561,11 +561,11 @@  discard block
 block discarded – undo
561 561
     {
562 562
         wp_register_style(
563 563
             'events-admin-css',
564
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
564
+            EVENTS_ASSETS_URL.'events-admin-page.css',
565 565
             [],
566 566
             EVENT_ESPRESSO_VERSION
567 567
         );
568
-        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
568
+        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL.'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
569 569
         wp_enqueue_style('events-admin-css');
570 570
         wp_enqueue_style('ee-cat-admin');
571 571
         // todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
@@ -573,7 +573,7 @@  discard block
 block discarded – undo
573 573
         // scripts
574 574
         wp_register_script(
575 575
             'event_editor_js',
576
-            EVENTS_ASSETS_URL . 'event_editor.js',
576
+            EVENTS_ASSETS_URL.'event_editor.js',
577 577
             ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
578 578
             EVENT_ESPRESSO_VERSION,
579 579
             true
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
         wp_enqueue_style('espresso-ui-theme');
600 600
         wp_register_style(
601 601
             'event-editor-css',
602
-            EVENTS_ASSETS_URL . 'event-editor.css',
602
+            EVENTS_ASSETS_URL.'event-editor.css',
603 603
             ['ee-admin-css'],
604 604
             EVENT_ESPRESSO_VERSION
605 605
         );
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
         // scripts
608 608
         wp_register_script(
609 609
             'event-datetime-metabox',
610
-            EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
610
+            EVENTS_ASSETS_URL.'event-datetime-metabox.js',
611 611
             ['event_editor_js', 'ee-datepicker'],
612 612
             EVENT_ESPRESSO_VERSION
613 613
         );
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
     public function verify_event_edit($event = null, $req_type = '')
677 677
     {
678 678
         // don't need to do this when processing
679
-        if (! empty($req_type)) {
679
+        if ( ! empty($req_type)) {
680 680
             return;
681 681
         }
682 682
         // no event?
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
             $event = $this->_cpt_model_obj;
686 686
         }
687 687
         // STILL no event?
688
-        if (! $event instanceof EE_Event) {
688
+        if ( ! $event instanceof EE_Event) {
689 689
             return;
690 690
         }
691 691
         $orig_status = $event->status();
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
             );
725 725
         }
726 726
         // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
727
-        if (! $event->tickets_on_sale()) {
727
+        if ( ! $event->tickets_on_sale()) {
728 728
             return;
729 729
         }
730 730
         // made it here so show warning
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
     {
770 770
         $has_timezone_string = get_option('timezone_string');
771 771
         // only nag them about setting their timezone if it's their first event, and they haven't already done it
772
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
772
+        if ( ! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
773 773
             EE_Error::add_attention(
774 774
                 sprintf(
775 775
                     esc_html__(
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
      */
839 839
     protected function _event_legend_items()
840 840
     {
841
-        $items    = [
841
+        $items = [
842 842
             'view_details'   => [
843 843
                 'class' => 'dashicons dashicons-search',
844 844
                 'desc'  => esc_html__('View Event', 'event_espresso'),
@@ -855,31 +855,31 @@  discard block
 block discarded – undo
855 855
         $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
856 856
         $statuses = [
857 857
             'sold_out_status'  => [
858
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
858
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::sold_out,
859 859
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
860 860
             ],
861 861
             'active_status'    => [
862
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
862
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::active,
863 863
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
864 864
             ],
865 865
             'upcoming_status'  => [
866
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
866
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::upcoming,
867 867
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
868 868
             ],
869 869
             'postponed_status' => [
870
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
870
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::postponed,
871 871
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
872 872
             ],
873 873
             'cancelled_status' => [
874
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
874
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::cancelled,
875 875
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
876 876
             ],
877 877
             'expired_status'   => [
878
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
878
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::expired,
879 879
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
880 880
             ],
881 881
             'inactive_status'  => [
882
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
882
+                'class' => 'ee-status-legend ee-status-legend-'.EE_Datetime::inactive,
883 883
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
884 884
             ],
885 885
         ];
@@ -895,7 +895,7 @@  discard block
 block discarded – undo
895 895
      */
896 896
     private function _event_model()
897 897
     {
898
-        if (! $this->_event_model instanceof EEM_Event) {
898
+        if ( ! $this->_event_model instanceof EEM_Event) {
899 899
             $this->_event_model = EE_Registry::instance()->load_model('Event');
900 900
         }
901 901
         return $this->_event_model;
@@ -915,8 +915,8 @@  discard block
 block discarded – undo
915 915
     public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
916 916
     {
917 917
         // make sure this is only when editing
918
-        if (! empty($id)) {
919
-            $post   = get_post($id);
918
+        if ( ! empty($id)) {
919
+            $post = get_post($id);
920 920
             $return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
921 921
                        . esc_html__('Shortcode', 'event_espresso')
922 922
                        . '</a> ';
@@ -939,7 +939,7 @@  discard block
 block discarded – undo
939 939
     protected function _events_overview_list_table()
940 940
     {
941 941
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
942
-        $this->_template_args['after_list_table']                           =
942
+        $this->_template_args['after_list_table'] =
943 943
             ! empty($this->_template_args['after_list_table'])
944 944
                 ? (array) $this->_template_args['after_list_table']
945 945
                 : [];
@@ -949,10 +949,10 @@  discard block
 block discarded – undo
949 949
                 esc_html__("View Event Archive Page", "event_espresso"),
950 950
                 'button'
951 951
             );
952
-        $this->_template_args['after_list_table']['legend']                 = $this->_display_legend(
952
+        $this->_template_args['after_list_table']['legend'] = $this->_display_legend(
953 953
             $this->_event_legend_items()
954 954
         );
955
-        $this->_admin_page_title                                            .= ' ' . $this->get_action_link_or_button(
955
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
956 956
             'create_new',
957 957
             'add',
958 958
             [],
@@ -1048,7 +1048,7 @@  discard block
 block discarded – undo
1048 1048
                 [$this, '_default_tickets_update'],
1049 1049
             ]
1050 1050
         );
1051
-        $att_success            = true;
1051
+        $att_success = true;
1052 1052
         foreach ($event_update_callbacks as $e_callback) {
1053 1053
             $_success = is_callable($e_callback)
1054 1054
                 ? call_user_func($e_callback, $event, $this->request->requestParams())
@@ -1110,7 +1110,7 @@  discard block
 block discarded – undo
1110 1110
      */
1111 1111
     protected function _default_venue_update(EE_Event $event, $data)
1112 1112
     {
1113
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1113
+        require_once(EE_MODELS.'EEM_Venue.model.php');
1114 1114
         $venue_model = EE_Registry::instance()->load_model('Venue');
1115 1115
         $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1116 1116
         // very important.  If we don't have a venue name...
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
             'status'              => 'publish',
1142 1142
         ];
1143 1143
         // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1144
-        if (! empty($venue_id)) {
1144
+        if ( ! empty($venue_id)) {
1145 1145
             $update_where  = [$venue_model->primary_key_name() => $venue_id];
1146 1146
             $rows_affected = $venue_model->update($venue_array, [$update_where]);
1147 1147
             // 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.
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
                 isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1180 1180
                     ? $datetime_data['DTT_EVT_end']
1181 1181
                     : $datetime_data['DTT_EVT_start'];
1182
-            $datetime_values              = [
1182
+            $datetime_values = [
1183 1183
                 'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1184 1184
                 'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1185 1185
                 'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
@@ -1188,9 +1188,9 @@  discard block
 block discarded – undo
1188 1188
             ];
1189 1189
             // if we have an id then let's get existing object first and then set the new values.
1190 1190
             //  Otherwise we instantiate a new object for save.
1191
-            if (! empty($datetime_data['DTT_ID'])) {
1191
+            if ( ! empty($datetime_data['DTT_ID'])) {
1192 1192
                 $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1193
-                if (! $datetime instanceof EE_Datetime) {
1193
+                if ( ! $datetime instanceof EE_Datetime) {
1194 1194
                     throw new RuntimeException(
1195 1195
                         sprintf(
1196 1196
                             esc_html__(
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
             } else {
1210 1210
                 $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1211 1211
             }
1212
-            if (! $datetime instanceof EE_Datetime) {
1212
+            if ( ! $datetime instanceof EE_Datetime) {
1213 1213
                 throw new RuntimeException(
1214 1214
                     sprintf(
1215 1215
                         esc_html__(
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
 
1236 1236
         // set up some default start and end dates in case those are not present in the incoming data
1237 1237
         $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1238
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1238
+        $default_start_date = $default_start_date->format($date_formats[0].' '.$date_formats[1]);
1239 1239
         // use the start date of the first datetime for the end date
1240 1240
         $first_datetime   = $event->first_datetime();
1241 1241
         $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
@@ -1243,8 +1243,8 @@  discard block
 block discarded – undo
1243 1243
         // now process the incoming data
1244 1244
         foreach ($data['edit_tickets'] as $row => $ticket_data) {
1245 1245
             $update_prices = false;
1246
-            $ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1247
-                ? $data['edit_prices'][ $row ][1]['PRC_amount']
1246
+            $ticket_price  = isset($data['edit_prices'][$row][1]['PRC_amount'])
1247
+                ? $data['edit_prices'][$row][1]['PRC_amount']
1248 1248
                 : 0;
1249 1249
             // trim inputs to ensure any excess whitespace is removed.
1250 1250
             $ticket_data   = array_map('trim', $ticket_data);
@@ -1285,9 +1285,9 @@  discard block
 block discarded – undo
1285 1285
             // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1286 1286
             // keep in mind that if the ticket has been sold (and we have changed pricing information),
1287 1287
             // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1288
-            if (! empty($ticket_data['TKT_ID'])) {
1288
+            if ( ! empty($ticket_data['TKT_ID'])) {
1289 1289
                 $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1290
-                if (! $existing_ticket instanceof EE_Ticket) {
1290
+                if ( ! $existing_ticket instanceof EE_Ticket) {
1291 1291
                     throw new RuntimeException(
1292 1292
                         sprintf(
1293 1293
                             esc_html__(
@@ -1336,7 +1336,7 @@  discard block
 block discarded – undo
1336 1336
                     $existing_ticket->save();
1337 1337
                     // make sure this ticket is still recorded in our $saved_tickets
1338 1338
                     // so we don't run it through the regular trash routine.
1339
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1339
+                    $saved_tickets[$existing_ticket->ID()] = $existing_ticket;
1340 1340
                     // create new ticket that's a copy of the existing except,
1341 1341
                     // (a new id of course and not archived) AND has the new TKT_price associated with it.
1342 1342
                     $new_ticket = clone $existing_ticket;
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
                 $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1354 1354
                 $update_prices              = true;
1355 1355
             }
1356
-            if (! $ticket instanceof EE_Ticket) {
1356
+            if ( ! $ticket instanceof EE_Ticket) {
1357 1357
                 throw new RuntimeException(
1358 1358
                     sprintf(
1359 1359
                         esc_html__(
@@ -1377,10 +1377,10 @@  discard block
 block discarded – undo
1377 1377
             }
1378 1378
             // initially let's add the ticket to the datetime
1379 1379
             $datetime->_add_relation_to($ticket, 'Ticket');
1380
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1380
+            $saved_tickets[$ticket->ID()] = $ticket;
1381 1381
             // add prices to ticket
1382
-            $prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1383
-                ? $data['edit_prices'][ $row ]
1382
+            $prices_data = isset($data['edit_prices'][$row]) && is_array($data['edit_prices'][$row])
1383
+                ? $data['edit_prices'][$row]
1384 1384
                 : [];
1385 1385
             $this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1386 1386
         }
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
             $id = absint($id);
1395 1395
             // get the ticket for this id
1396 1396
             $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1397
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1397
+            if ( ! $ticket_to_remove instanceof EE_Ticket) {
1398 1398
                 continue;
1399 1399
             }
1400 1400
             // need to get all the related datetimes on this ticket and remove from every single one of them
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
                     $price->set($field, $new_price);
1452 1452
                 }
1453 1453
             }
1454
-            if (! $price instanceof EE_Price) {
1454
+            if ( ! $price instanceof EE_Price) {
1455 1455
                 throw new RuntimeException(
1456 1456
                     sprintf(
1457 1457
                         esc_html__(
@@ -1494,13 +1494,13 @@  discard block
 block discarded – undo
1494 1494
     {
1495 1495
         // load formatter helper
1496 1496
         // args for getting related registrations
1497
-        $approved_query_args        = [
1497
+        $approved_query_args = [
1498 1498
             [
1499 1499
                 'REG_deleted' => 0,
1500 1500
                 'STS_ID'      => EEM_Registration::status_id_approved,
1501 1501
             ],
1502 1502
         ];
1503
-        $not_approved_query_args    = [
1503
+        $not_approved_query_args = [
1504 1504
             [
1505 1505
                 'REG_deleted' => 0,
1506 1506
                 'STS_ID'      => EEM_Registration::status_id_not_approved,
@@ -1566,7 +1566,7 @@  discard block
 block discarded – undo
1566 1566
         $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1567 1567
         // load template
1568 1568
         EEH_Template::display_template(
1569
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1569
+            EVENTS_TEMPLATE_PATH.'event_publish_box_extras.template.php',
1570 1570
             $publish_box_extra_args
1571 1571
         );
1572 1572
     }
@@ -1632,7 +1632,7 @@  discard block
 block discarded – undo
1632 1632
             'trash_icon'               => 'ee-lock-icon',
1633 1633
             'disabled'                 => '',
1634 1634
         ];
1635
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1635
+        $event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1636 1636
         /**
1637 1637
          * 1. Start with retrieving Datetimes
1638 1638
          * 2. Fore each datetime get related tickets
@@ -1653,17 +1653,17 @@  discard block
 block discarded – undo
1653 1653
                     'default_where_conditions' => 'none',
1654 1654
                 ]
1655 1655
             );
1656
-            if (! empty($related_tickets)) {
1656
+            if ( ! empty($related_tickets)) {
1657 1657
                 $template_args['total_ticket_rows'] = count($related_tickets);
1658 1658
                 $row                                = 0;
1659 1659
                 foreach ($related_tickets as $ticket) {
1660
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1660
+                    $existing_ticket_ids[] = $ticket->get('TKT_ID');
1661 1661
                     $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1662 1662
                     $row++;
1663 1663
                 }
1664 1664
             } else {
1665 1665
                 $template_args['total_ticket_rows'] = 1;
1666
-                $ticket                       = EEM_Ticket::instance()->create_default_object();
1666
+                $ticket = EEM_Ticket::instance()->create_default_object();
1667 1667
                 $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1668 1668
             }
1669 1669
         } else {
@@ -1683,9 +1683,9 @@  discard block
 block discarded – undo
1683 1683
             EEM_Ticket::instance()->create_default_object(),
1684 1684
             true
1685 1685
         );
1686
-        $template                                  = apply_filters(
1686
+        $template = apply_filters(
1687 1687
             'FHEE__Events_Admin_Page__ticket_metabox__template',
1688
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1688
+            EVENTS_TEMPLATE_PATH.'event_tickets_metabox_main.template.php'
1689 1689
         );
1690 1690
         EEH_Template::display_template($template, $template_args);
1691 1691
     }
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
     private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1706 1706
     {
1707 1707
         $template_args = [
1708
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1708
+            'tkt_status_class'    => ' tkt-status-'.$ticket->ticket_status(),
1709 1709
             'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1710 1710
                 : '',
1711 1711
             'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
@@ -1717,10 +1717,10 @@  discard block
 block discarded – undo
1717 1717
             'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1718 1718
             'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1719 1719
             'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1720
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1721
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1720
+            'trash_icon'          => ($skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')))
1721
+                                     && ( ! empty($ticket) && $ticket->get('TKT_sold') === 0)
1722 1722
                 ? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1723
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1723
+            'disabled'            => $skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1724 1724
                 : ' disabled=disabled',
1725 1725
         ];
1726 1726
         $price         = $ticket->ID() !== 0
@@ -1744,7 +1744,7 @@  discard block
 block discarded – undo
1744 1744
         }
1745 1745
         if (empty($template_args['TKT_end_date'])) {
1746 1746
             // get the earliest datetime (if present);
1747
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1747
+            $earliest_datetime = $this->_cpt_model_obj->ID() > 0
1748 1748
                 ? $this->_cpt_model_obj->get_first_related(
1749 1749
                     'Datetime',
1750 1750
                     ['order_by' => ['DTT_EVT_start' => 'ASC']]
@@ -1757,7 +1757,7 @@  discard block
 block discarded – undo
1757 1757
         $template_args = array_merge($template_args, $price_args);
1758 1758
         $template      = apply_filters(
1759 1759
             'FHEE__Events_Admin_Page__get_ticket_row__template',
1760
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1760
+            EVENTS_TEMPLATE_PATH.'event_tickets_metabox_ticket_row.template.php',
1761 1761
             $ticket
1762 1762
         );
1763 1763
         return EEH_Template::display_template($template, $template_args, true);
@@ -1770,7 +1770,7 @@  discard block
 block discarded – undo
1770 1770
      */
1771 1771
     public function registration_options_meta_box()
1772 1772
     {
1773
-        $yes_no_values             = [
1773
+        $yes_no_values = [
1774 1774
             ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1775 1775
             ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1776 1776
         ];
@@ -1792,12 +1792,12 @@  discard block
 block discarded – undo
1792 1792
             $default_reg_status_values,
1793 1793
             $this->_cpt_model_obj->default_registration_status()
1794 1794
         );
1795
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1795
+        $template_args['display_description'] = EEH_Form_Fields::select_input(
1796 1796
             'display_desc',
1797 1797
             $yes_no_values,
1798 1798
             $this->_cpt_model_obj->display_description()
1799 1799
         );
1800
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1800
+        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1801 1801
             'display_ticket_selector',
1802 1802
             $yes_no_values,
1803 1803
             $this->_cpt_model_obj->display_ticket_selector(),
@@ -1813,7 +1813,7 @@  discard block
 block discarded – undo
1813 1813
             $default_reg_status_values
1814 1814
         );
1815 1815
         EEH_Template::display_template(
1816
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1816
+            EVENTS_TEMPLATE_PATH.'event_registration_options.template.php',
1817 1817
             $template_args
1818 1818
         );
1819 1819
     }
@@ -1836,7 +1836,7 @@  discard block
 block discarded – undo
1836 1836
     {
1837 1837
         $EEM_Event   = $this->_event_model();
1838 1838
         $offset      = ($current_page - 1) * $per_page;
1839
-        $limit       = $count ? null : $offset . ',' . $per_page;
1839
+        $limit       = $count ? null : $offset.','.$per_page;
1840 1840
         $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1841 1841
         $order       = $this->request->getRequestParam('order', 'DESC');
1842 1842
         $month_range = $this->request->getRequestParam('month_range');
@@ -1873,10 +1873,10 @@  discard block
 block discarded – undo
1873 1873
         $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1874 1874
         if ($month_range) {
1875 1875
             $DateTime = new DateTime(
1876
-                $year_r . '-' . $month_r . '-01 00:00:00',
1876
+                $year_r.'-'.$month_r.'-01 00:00:00',
1877 1877
                 new DateTimeZone('UTC')
1878 1878
             );
1879
-            $start    = $DateTime->getTimestamp();
1879
+            $start = $DateTime->getTimestamp();
1880 1880
             // set the datetime to be the end of the month
1881 1881
             $DateTime->setDate(
1882 1882
                 $year_r,
@@ -1901,11 +1901,11 @@  discard block
 block discarded – undo
1901 1901
                                                         ->format(implode(' ', $start_formats));
1902 1902
             $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1903 1903
         }
1904
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1904
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1905 1905
             $where['EVT_wp_user'] = get_current_user_id();
1906 1906
         } else {
1907
-            if (! isset($where['status'])) {
1908
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1907
+            if ( ! isset($where['status'])) {
1908
+                if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1909 1909
                     $where['OR'] = [
1910 1910
                         'status*restrict_private' => ['!=', 'private'],
1911 1911
                         'AND'                     => [
@@ -1927,7 +1927,7 @@  discard block
 block discarded – undo
1927 1927
         // search query handling
1928 1928
         $search_term = $this->request->getRequestParam('s');
1929 1929
         if ($search_term) {
1930
-            $search_term = '%' . $search_term . '%';
1930
+            $search_term = '%'.$search_term.'%';
1931 1931
             $where['OR'] = [
1932 1932
                 'EVT_name'       => ['LIKE', $search_term],
1933 1933
                 'EVT_desc'       => ['LIKE', $search_term],
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
             // clean status
2036 2036
             $event_status = sanitize_key($event_status);
2037 2037
             // grab status
2038
-            if (! empty($event_status)) {
2038
+            if ( ! empty($event_status)) {
2039 2039
                 $success = $this->_change_event_status($EVT_ID, $event_status);
2040 2040
             } else {
2041 2041
                 $success = false;
@@ -2075,7 +2075,7 @@  discard block
 block discarded – undo
2075 2075
         // clean status
2076 2076
         $event_status = sanitize_key($event_status);
2077 2077
         // grab status
2078
-        if (! empty($event_status)) {
2078
+        if ( ! empty($event_status)) {
2079 2079
             $success = true;
2080 2080
             // determine the event id and set to array.
2081 2081
             $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
@@ -2121,7 +2121,7 @@  discard block
 block discarded – undo
2121 2121
     private function _change_event_status($EVT_ID = 0, $event_status = '')
2122 2122
     {
2123 2123
         // grab event id
2124
-        if (! $EVT_ID) {
2124
+        if ( ! $EVT_ID) {
2125 2125
             $msg = esc_html__(
2126 2126
                 'An error occurred. No Event ID or an invalid Event ID was received.',
2127 2127
                 'event_espresso'
@@ -2158,7 +2158,7 @@  discard block
 block discarded – undo
2158 2158
         // use class to change status
2159 2159
         $this->_cpt_model_obj->set_status($event_status);
2160 2160
         $success = $this->_cpt_model_obj->save();
2161
-        if (! $success) {
2161
+        if ( ! $success) {
2162 2162
             $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2163 2163
             EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2164 2164
             return false;
@@ -2225,7 +2225,7 @@  discard block
 block discarded – undo
2225 2225
      */
2226 2226
     protected function getModelObjNodeGroupPersister()
2227 2227
     {
2228
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2228
+        if ( ! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2229 2229
             $this->model_obj_node_group_persister =
2230 2230
                 $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2231 2231
         }
@@ -2515,7 +2515,7 @@  discard block
 block discarded – undo
2515 2515
                                                 . esc_html__(
2516 2516
                                                     '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.',
2517 2517
                                                     'event_espresso'
2518
-                                                ) . '</strong>';
2518
+                                                ).'</strong>';
2519 2519
         $this->display_admin_caf_preview_page('template_settings_tab');
2520 2520
     }
2521 2521
 
@@ -2536,11 +2536,11 @@  discard block
 block discarded – undo
2536 2536
         $this->_set_empty_category_object();
2537 2537
         // only set if we've got an id
2538 2538
         $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2539
-        if (! $category_ID) {
2539
+        if ( ! $category_ID) {
2540 2540
             return;
2541 2541
         }
2542 2542
         $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2543
-        if (! empty($term)) {
2543
+        if ( ! empty($term)) {
2544 2544
             $this->_category->category_name       = $term->name;
2545 2545
             $this->_category->category_identifier = $term->slug;
2546 2546
             $this->_category->category_desc       = $term->description;
@@ -2568,7 +2568,7 @@  discard block
 block discarded – undo
2568 2568
     {
2569 2569
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2570 2570
         $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2571
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2571
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
2572 2572
             'add_category',
2573 2573
             'add_category',
2574 2574
             [],
@@ -2637,7 +2637,7 @@  discard block
 block discarded – undo
2637 2637
             $category_select_values,
2638 2638
             $this->_category->parent
2639 2639
         );
2640
-        $template_args   = [
2640
+        $template_args = [
2641 2641
             'category'                 => $this->_category,
2642 2642
             'category_select'          => $category_select,
2643 2643
             'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
@@ -2645,7 +2645,7 @@  discard block
 block discarded – undo
2645 2645
             'disable'                  => '',
2646 2646
             'disabled_message'         => false,
2647 2647
         ];
2648
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2648
+        $template = EVENTS_TEMPLATE_PATH.'event_category_details.template.php';
2649 2649
         return EEH_Template::display_template($template, $template_args, true);
2650 2650
     }
2651 2651
 
@@ -2735,7 +2735,7 @@  discard block
 block discarded – undo
2735 2735
         $insert_ids = $update
2736 2736
             ? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2737 2737
             : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2738
-        if (! is_array($insert_ids)) {
2738
+        if ( ! is_array($insert_ids)) {
2739 2739
             $msg = esc_html__(
2740 2740
                 'An error occurred and the category has not been saved to the database.',
2741 2741
                 'event_espresso'
@@ -2770,7 +2770,7 @@  discard block
 block discarded – undo
2770 2770
         $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2771 2771
         $search_term = $this->request->getRequestParam('s');
2772 2772
         if ($search_term) {
2773
-            $search_term = '%' . $search_term . '%';
2773
+            $search_term = '%'.$search_term.'%';
2774 2774
             $where['OR'] = [
2775 2775
                 'Term.name'   => ['LIKE', $search_term],
2776 2776
                 'description' => ['LIKE', $search_term],
@@ -2779,7 +2779,7 @@  discard block
 block discarded – undo
2779 2779
         $query_params = [
2780 2780
             $where,
2781 2781
             'order_by'   => [$orderby => $order],
2782
-            'limit'      => $limit . ',' . $per_page,
2782
+            'limit'      => $limit.','.$per_page,
2783 2783
             'force_join' => ['Term'],
2784 2784
         ];
2785 2785
         return $count
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 2 patches
Indentation   +2521 added lines, -2521 removed lines patch added patch discarded remove patch
@@ -12,2525 +12,2525 @@
 block discarded – undo
12 12
  */
13 13
 class Transactions_Admin_Page extends EE_Admin_Page
14 14
 {
15
-    /**
16
-     * @var EE_Transaction
17
-     */
18
-    private $_transaction;
19
-
20
-    /**
21
-     * @var EE_Session
22
-     */
23
-    private $_session;
24
-
25
-    /**
26
-     * @var array $_txn_status
27
-     */
28
-    private static $_txn_status;
29
-
30
-    /**
31
-     * @var array $_pay_status
32
-     */
33
-    private static $_pay_status;
34
-
35
-    /**
36
-     * @var array $_existing_reg_payment_REG_IDs
37
-     */
38
-    protected $_existing_reg_payment_REG_IDs;
39
-
40
-
41
-    /**
42
-     *    _init_page_props
43
-     *
44
-     * @return void
45
-     */
46
-    protected function _init_page_props()
47
-    {
48
-        $this->page_slug        = TXN_PG_SLUG;
49
-        $this->page_label       = esc_html__('Transactions', 'event_espresso');
50
-        $this->_admin_base_url  = TXN_ADMIN_URL;
51
-        $this->_admin_base_path = TXN_ADMIN;
52
-    }
53
-
54
-
55
-    /**
56
-     *    _ajax_hooks
57
-     *
58
-     * @return void
59
-     */
60
-    protected function _ajax_hooks()
61
-    {
62
-        add_action('wp_ajax_espresso_apply_payment', [$this, 'apply_payments_or_refunds']);
63
-        add_action('wp_ajax_espresso_apply_refund', [$this, 'apply_payments_or_refunds']);
64
-        add_action('wp_ajax_espresso_delete_payment', [$this, 'delete_payment']);
65
-    }
66
-
67
-
68
-    /**
69
-     *    _define_page_props
70
-     *
71
-     * @return void
72
-     */
73
-    protected function _define_page_props()
74
-    {
75
-        $this->_admin_page_title = $this->page_label;
76
-        $this->_labels           = [
77
-            'buttons' => [
78
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
79
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
80
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
81
-            ],
82
-        ];
83
-    }
84
-
85
-
86
-    /**
87
-     *        grab url requests and route them
88
-     *
89
-     * @access private
90
-     * @return void
91
-     * @throws EE_Error
92
-     * @throws InvalidArgumentException
93
-     * @throws InvalidDataTypeException
94
-     * @throws InvalidInterfaceException
95
-     */
96
-    public function _set_page_routes()
97
-    {
98
-
99
-        $this->_set_transaction_status_array();
100
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
101
-
102
-        $this->_page_routes = [
103
-
104
-            'default' => [
105
-                'func'       => '_transactions_overview_list_table',
106
-                'capability' => 'ee_read_transactions',
107
-            ],
108
-
109
-            'view_transaction' => [
110
-                'func'       => '_transaction_details',
111
-                'capability' => 'ee_read_transaction',
112
-                'obj_id'     => $TXN_ID,
113
-            ],
114
-
115
-            'send_payment_reminder' => [
116
-                'func'       => '_send_payment_reminder',
117
-                'noheader'   => true,
118
-                'capability' => 'ee_send_message',
119
-            ],
120
-
121
-            'espresso_apply_payment' => [
122
-                'func'       => 'apply_payments_or_refunds',
123
-                'noheader'   => true,
124
-                'capability' => 'ee_edit_payments',
125
-            ],
126
-
127
-            'espresso_apply_refund' => [
128
-                'func'       => 'apply_payments_or_refunds',
129
-                'noheader'   => true,
130
-                'capability' => 'ee_edit_payments',
131
-            ],
132
-
133
-            'espresso_delete_payment' => [
134
-                'func'       => 'delete_payment',
135
-                'noheader'   => true,
136
-                'capability' => 'ee_delete_payments',
137
-            ],
138
-
139
-            'espresso_recalculate_line_items' => [
140
-                'func'       => 'recalculateLineItems',
141
-                'noheader'   => true,
142
-                'capability' => 'ee_edit_payments',
143
-            ],
144
-
145
-        ];
146
-    }
147
-
148
-
149
-    protected function _set_page_config()
150
-    {
151
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
152
-        $this->_page_config = [
153
-            'default'          => [
154
-                'nav'           => [
155
-                    'label' => esc_html__('Overview', 'event_espresso'),
156
-                    'order' => 10,
157
-                ],
158
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
159
-                'help_tabs'     => [
160
-                    'transactions_overview_help_tab'                       => [
161
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
162
-                        'filename' => 'transactions_overview',
163
-                    ],
164
-                    'transactions_overview_table_column_headings_help_tab' => [
165
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
166
-                        'filename' => 'transactions_overview_table_column_headings',
167
-                    ],
168
-                    'transactions_overview_views_filters_help_tab'         => [
169
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
170
-                        'filename' => 'transactions_overview_views_filters_search',
171
-                    ],
172
-                ],
173
-                /**
174
-                 * commented out because currently we are not displaying tips for transaction list table status but this
175
-                 * may change in a later iteration so want to keep the code for then.
176
-                 */
177
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
178
-                'require_nonce' => false,
179
-            ],
180
-            'view_transaction' => [
181
-                'nav'       => [
182
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
183
-                    'order'      => 5,
184
-                    'url'        => $TXN_ID
185
-                        ? add_query_arg(['TXN_ID' => $TXN_ID], $this->_current_page_view_url)
186
-                        : $this->_admin_base_url,
187
-                    'persistent' => false,
188
-                ],
189
-                'help_tabs' => [
190
-                    'transactions_view_transaction_help_tab'                                              => [
191
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
192
-                        'filename' => 'transactions_view_transaction',
193
-                    ],
194
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => [
195
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
196
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
197
-                    ],
198
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => [
199
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
200
-                        'filename' => 'transactions_view_transaction_attendees_registered',
201
-                    ],
202
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => [
203
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
204
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
205
-                    ],
206
-                ],
207
-                'qtips'     => ['Transaction_Details_Tips'],
208
-                'metaboxes' => ['_transaction_details_metaboxes'],
209
-
210
-                'require_nonce' => false,
211
-            ],
212
-        ];
213
-    }
214
-
215
-
216
-    /**
217
-     * The below methods aren't used by this class currently
218
-     */
219
-    protected function _add_screen_options()
220
-    {
221
-        // noop
222
-    }
223
-
224
-
225
-    protected function _add_feature_pointers()
226
-    {
227
-        // noop
228
-    }
229
-
230
-
231
-    public function admin_init()
232
-    {
233
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
234
-        $event_name = $this->request->getRequestParam('event_name');
235
-        $redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
236
-        // IF a registration was JUST added via the admin...
237
-        if ($EVT_ID && $event_name && $redirect_from) {
238
-            // then set a cookie so that we can block any attempts to use
239
-            // the back button as a way to enter another registration.
240
-            setcookie('ee_registration_added', $EVT_ID, time() + WEEK_IN_SECONDS, '/');
241
-            // and update the global
242
-            $_COOKIE['ee_registration_added'] = $EVT_ID;
243
-        }
244
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
245
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
246
-            'event_espresso'
247
-        );
248
-        EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
249
-            'An error occurred! Please refresh the page and try again.',
250
-            'event_espresso'
251
-        );
252
-        EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
253
-        EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
254
-        EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
255
-        EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__(
256
-            'This transaction has been overpaid ! Payments Total',
257
-            'event_espresso'
258
-        );
259
-    }
260
-
261
-
262
-    public function admin_notices()
263
-    {
264
-        // noop
265
-    }
266
-
267
-
268
-    public function admin_footer_scripts()
269
-    {
270
-        // noop
271
-    }
272
-
273
-
274
-    /**
275
-     * _set_transaction_status_array
276
-     * sets list of transaction statuses
277
-     *
278
-     * @access private
279
-     * @return void
280
-     * @throws EE_Error
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidDataTypeException
283
-     * @throws InvalidInterfaceException
284
-     */
285
-    private function _set_transaction_status_array()
286
-    {
287
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
288
-    }
289
-
290
-
291
-    /**
292
-     * get_transaction_status_array
293
-     * return the transaction status array for wp_list_table
294
-     *
295
-     * @access public
296
-     * @return array
297
-     */
298
-    public function get_transaction_status_array()
299
-    {
300
-        return self::$_txn_status;
301
-    }
302
-
303
-
304
-    /**
305
-     *    get list of payment statuses
306
-     *
307
-     * @access private
308
-     * @return void
309
-     * @throws EE_Error
310
-     * @throws InvalidArgumentException
311
-     * @throws InvalidDataTypeException
312
-     * @throws InvalidInterfaceException
313
-     */
314
-    private function _get_payment_status_array()
315
-    {
316
-        self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
317
-        $this->_template_args['payment_status'] = self::$_pay_status;
318
-    }
319
-
320
-
321
-    /**
322
-     *    _add_screen_options_default
323
-     *
324
-     * @access protected
325
-     * @return void
326
-     * @throws InvalidArgumentException
327
-     * @throws InvalidDataTypeException
328
-     * @throws InvalidInterfaceException
329
-     */
330
-    protected function _add_screen_options_default()
331
-    {
332
-        $this->_per_page_screen_option();
333
-    }
334
-
335
-
336
-    /**
337
-     * load_scripts_styles
338
-     *
339
-     * @access public
340
-     * @return void
341
-     */
342
-    public function load_scripts_styles()
343
-    {
344
-        // enqueue style
345
-        wp_register_style(
346
-            'espresso_txn',
347
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
348
-            [],
349
-            EVENT_ESPRESSO_VERSION
350
-        );
351
-        wp_enqueue_style('espresso_txn');
352
-        // scripts
353
-        wp_register_script(
354
-            'espresso_txn',
355
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
356
-            [
357
-                'ee_admin_js',
358
-                'ee-datepicker',
359
-                'jquery-ui-datepicker',
360
-                'jquery-ui-draggable',
361
-                'ee-dialog',
362
-                'ee-accounting',
363
-                'ee-serialize-full-array',
364
-            ],
365
-            EVENT_ESPRESSO_VERSION,
366
-            true
367
-        );
368
-        wp_enqueue_script('espresso_txn');
369
-    }
370
-
371
-
372
-    /**
373
-     *    load_scripts_styles_view_transaction
374
-     *
375
-     * @access public
376
-     * @return void
377
-     */
378
-    public function load_scripts_styles_view_transaction()
379
-    {
380
-        // styles
381
-        wp_enqueue_style('espresso-ui-theme');
382
-    }
383
-
384
-
385
-    /**
386
-     *    load_scripts_styles_default
387
-     *
388
-     * @access public
389
-     * @return void
390
-     */
391
-    public function load_scripts_styles_default()
392
-    {
393
-        // styles
394
-        wp_enqueue_style('espresso-ui-theme');
395
-    }
396
-
397
-
398
-    /**
399
-     *    _set_list_table_views_default
400
-     *
401
-     * @access protected
402
-     * @return void
403
-     */
404
-    protected function _set_list_table_views_default()
405
-    {
406
-        $this->_views = [
407
-            'all'        => [
408
-                'slug'  => 'all',
409
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
410
-                'count' => 0,
411
-            ],
412
-            'abandoned'  => [
413
-                'slug'  => 'abandoned',
414
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
415
-                'count' => 0,
416
-            ],
417
-            'incomplete' => [
418
-                'slug'  => 'incomplete',
419
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
420
-                'count' => 0,
421
-            ],
422
-        ];
423
-        if (
424
-            /**
425
-             * Filters whether a link to the "Failed Transactions" list table
426
-             * appears on the Transactions Admin Page list table.
427
-             * List display can be turned back on via the following:
428
-             * add_filter(
429
-             *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
430
-             *     '__return_true'
431
-             * );
432
-             *
433
-             * @param boolean                 $display_failed_txns_list
434
-             * @param Transactions_Admin_Page $this
435
-             * @since 4.9.70.p
436
-             */
437
-            apply_filters(
438
-                'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
439
-                false,
440
-                $this
441
-            )
442
-        ) {
443
-            $this->_views['failed'] = [
444
-                'slug'  => 'failed',
445
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
446
-                'count' => 0,
447
-            ];
448
-        }
449
-    }
450
-
451
-
452
-    /**
453
-     * _set_transaction_object
454
-     * This sets the _transaction property for the transaction details screen
455
-     *
456
-     * @access private
457
-     * @return void
458
-     * @throws EE_Error
459
-     * @throws InvalidArgumentException
460
-     * @throws RuntimeException
461
-     * @throws InvalidDataTypeException
462
-     * @throws InvalidInterfaceException
463
-     * @throws ReflectionException
464
-     */
465
-    private function _set_transaction_object()
466
-    {
467
-        if ($this->_transaction instanceof EE_Transaction) {
468
-            return;
469
-        } //get out we've already set the object
470
-
471
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
472
-
473
-        // get transaction object
474
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
475
-        $this->_session     = $this->_transaction instanceof EE_Transaction
476
-            ? $this->_transaction->session_data()
477
-            : null;
478
-        if ($this->_transaction instanceof EE_Transaction) {
479
-            $this->_transaction->verify_abandoned_transaction_status();
480
-        }
481
-
482
-        if (! $this->_transaction instanceof EE_Transaction) {
483
-            $error_msg = sprintf(
484
-                esc_html__(
485
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
486
-                    'event_espresso'
487
-                ),
488
-                $TXN_ID
489
-            );
490
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
491
-        }
492
-    }
493
-
494
-
495
-    /**
496
-     *    _transaction_legend_items
497
-     *
498
-     * @access protected
499
-     * @return array
500
-     * @throws EE_Error
501
-     * @throws InvalidArgumentException
502
-     * @throws ReflectionException
503
-     * @throws InvalidDataTypeException
504
-     * @throws InvalidInterfaceException
505
-     */
506
-    protected function _transaction_legend_items()
507
-    {
508
-        EE_Registry::instance()->load_helper('MSG_Template');
509
-        $items = [];
510
-
511
-        if (
512
-            EE_Registry::instance()->CAP->current_user_can(
513
-                'ee_read_global_messages',
514
-                'view_filtered_messages'
515
-            )
516
-        ) {
517
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
518
-            if (
519
-                is_array($related_for_icon)
520
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
521
-            ) {
522
-                $items['view_related_messages'] = [
523
-                    'class' => $related_for_icon['css_class'],
524
-                    'desc'  => $related_for_icon['label'],
525
-                ];
526
-            }
527
-        }
528
-
529
-        $items = apply_filters(
530
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
531
-            array_merge(
532
-                $items,
533
-                [
534
-                    'view_details'          => [
535
-                        'class' => 'dashicons dashicons-cart',
536
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
537
-                    ],
538
-                    'view_invoice'          => [
539
-                        'class' => 'dashicons dashicons-media-spreadsheet',
540
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
541
-                    ],
542
-                    'view_receipt'          => [
543
-                        'class' => 'dashicons dashicons-media-default',
544
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
545
-                    ],
546
-                    'view_registration'     => [
547
-                        'class' => 'dashicons dashicons-clipboard',
548
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
549
-                    ],
550
-                    'payment_overview_link' => [
551
-                        'class' => 'dashicons dashicons-money',
552
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
553
-                    ],
554
-                ]
555
-            )
556
-        );
557
-
558
-        if (
559
-            EEH_MSG_Template::is_mt_active('payment_reminder')
560
-            && EE_Registry::instance()->CAP->current_user_can(
561
-                'ee_send_message',
562
-                'espresso_transactions_send_payment_reminder'
563
-            )
564
-        ) {
565
-            $items['send_payment_reminder'] = [
566
-                'class' => 'dashicons dashicons-email-alt',
567
-                'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
568
-            ];
569
-        } else {
570
-            $items['blank*'] = [
571
-                'class' => '',
572
-                'desc'  => '',
573
-            ];
574
-        }
575
-        $more_items = apply_filters(
576
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
577
-            [
578
-                'overpaid'   => [
579
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
580
-                    'desc'  => EEH_Template::pretty_status(
581
-                        EEM_Transaction::overpaid_status_code,
582
-                        false,
583
-                        'sentence'
584
-                    ),
585
-                ],
586
-                'complete'   => [
587
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
588
-                    'desc'  => EEH_Template::pretty_status(
589
-                        EEM_Transaction::complete_status_code,
590
-                        false,
591
-                        'sentence'
592
-                    ),
593
-                ],
594
-                'incomplete' => [
595
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
596
-                    'desc'  => EEH_Template::pretty_status(
597
-                        EEM_Transaction::incomplete_status_code,
598
-                        false,
599
-                        'sentence'
600
-                    ),
601
-                ],
602
-                'abandoned'  => [
603
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
604
-                    'desc'  => EEH_Template::pretty_status(
605
-                        EEM_Transaction::abandoned_status_code,
606
-                        false,
607
-                        'sentence'
608
-                    ),
609
-                ],
610
-                'failed'     => [
611
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
612
-                    'desc'  => EEH_Template::pretty_status(
613
-                        EEM_Transaction::failed_status_code,
614
-                        false,
615
-                        'sentence'
616
-                    ),
617
-                ],
618
-            ]
619
-        );
620
-
621
-        return array_merge($items, $more_items);
622
-    }
623
-
624
-
625
-    /**
626
-     *    _transactions_overview_list_table
627
-     *
628
-     * @access protected
629
-     * @return void
630
-     * @throws DomainException
631
-     * @throws EE_Error
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidDataTypeException
634
-     * @throws InvalidInterfaceException
635
-     * @throws ReflectionException
636
-     */
637
-    protected function _transactions_overview_list_table()
638
-    {
639
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
640
-
641
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
642
-        $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
643
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
644
-            ? sprintf(
645
-                esc_html__('%sViewing Transactions for the Event: %s%s', 'event_espresso'),
646
-                '<h3>',
647
-                '<a href="'
648
-                . EE_Admin_Page::add_query_args_and_nonce(
649
-                    ['action' => 'edit', 'post' => $event->ID()],
650
-                    EVENTS_ADMIN_URL
651
-                )
652
-                . '" aria-label="'
653
-                . esc_attr__('Click to Edit event', 'event_espresso')
654
-                . '">' . $event->name() . '</a>',
655
-                '</h3>'
656
-            )
657
-            : '';
658
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
659
-        $this->display_admin_list_table_page_with_no_sidebar();
660
-    }
661
-
662
-
663
-    /**
664
-     *    _transaction_details
665
-     * generates HTML for the View Transaction Details Admin page
666
-     *
667
-     * @access protected
668
-     * @return void
669
-     * @throws DomainException
670
-     * @throws EE_Error
671
-     * @throws InvalidArgumentException
672
-     * @throws InvalidDataTypeException
673
-     * @throws InvalidInterfaceException
674
-     * @throws RuntimeException
675
-     * @throws ReflectionException
676
-     */
677
-    protected function _transaction_details()
678
-    {
679
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
680
-
681
-        $this->_set_transaction_status_array();
682
-
683
-        $this->_template_args                      = [];
684
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
685
-
686
-        $this->_set_transaction_object();
687
-
688
-        if (! $this->_transaction instanceof EE_Transaction) {
689
-            return;
690
-        }
691
-
692
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
693
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
694
-
695
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
696
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
697
-
698
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
699
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
700
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
701
-
702
-        $this->_template_args['grand_total'] = $this->_transaction->total();
703
-        $this->_template_args['total_paid']  = $this->_transaction->paid();
704
-
705
-        $amount_due                         = $this->_transaction->total() - $this->_transaction->paid();
706
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
707
-            $amount_due,
708
-            true
709
-        );
710
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
711
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
712
-                                                  . $this->_template_args['amount_due'];
713
-        } else {
714
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
715
-        }
716
-        $this->_template_args['amount_due_class'] = '';
717
-
718
-        if ($this->_transaction->paid() === $this->_transaction->total()) {
719
-            // paid in full
720
-            $this->_template_args['amount_due'] = false;
721
-        } elseif ($this->_transaction->paid() > $this->_transaction->total()) {
722
-            // overpaid
723
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
724
-        } elseif ($this->_transaction->total() > (float) 0) {
725
-            if ($this->_transaction->paid() > (float) 0) {
726
-                // monies owing
727
-                $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
728
-            } elseif ($this->_transaction->paid() === (float) 0) {
729
-                // no payments made yet
730
-                $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
731
-            }
732
-        } elseif ($this->_transaction->total() === (float) 0) {
733
-            // free event
734
-            $this->_template_args['amount_due'] = false;
735
-        }
736
-
737
-        $payment_method = $this->_transaction->payment_method();
738
-
739
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
740
-            ? $payment_method->admin_name()
741
-            : esc_html__('Unknown', 'event_espresso');
742
-
743
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
744
-        // link back to overview
745
-        $this->_template_args['txn_overview_url'] = $this->request->getServerParam(
746
-            'HTTP_REFERER',
747
-            TXN_ADMIN_URL
748
-        );
749
-
750
-
751
-        // next link
752
-        $next_txn                                 = $this->_transaction->next(
753
-            null,
754
-            [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
755
-            'TXN_ID'
756
-        );
757
-        $this->_template_args['next_transaction'] = $next_txn
758
-            ? $this->_next_link(
759
-                EE_Admin_Page::add_query_args_and_nonce(
760
-                    ['action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']],
761
-                    TXN_ADMIN_URL
762
-                ),
763
-                'dashicons dashicons-arrow-right ee-icon-size-22'
764
-            )
765
-            : '';
766
-        // previous link
767
-        $previous_txn                                 = $this->_transaction->previous(
768
-            null,
769
-            [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
770
-            'TXN_ID'
771
-        );
772
-        $this->_template_args['previous_transaction'] = $previous_txn
773
-            ? $this->_previous_link(
774
-                EE_Admin_Page::add_query_args_and_nonce(
775
-                    ['action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']],
776
-                    TXN_ADMIN_URL
777
-                ),
778
-                'dashicons dashicons-arrow-left ee-icon-size-22'
779
-            )
780
-            : '';
781
-
782
-        $EVT_ID        = $this->request->getRequestParam('EVT_ID', 0, 'int');
783
-        $event_name    = $this->request->getRequestParam('event_name');
784
-        $redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
785
-
786
-        // were we just redirected here after adding a new registration ???
787
-        if ($EVT_ID && $event_name && $redirect_from) {
788
-            if (
789
-                EE_Registry::instance()->CAP->current_user_can(
790
-                    'ee_edit_registrations',
791
-                    'espresso_registrations_new_registration',
792
-                    $EVT_ID
793
-                )
794
-            ) {
795
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
796
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
797
-                    [
798
-                        'page'     => 'espresso_registrations',
799
-                        'action'   => 'new_registration',
800
-                        'return'   => 'default',
801
-                        'TXN_ID'   => $this->_transaction->ID(),
802
-                        'event_id' => $EVT_ID,
803
-                    ],
804
-                    REG_ADMIN_URL
805
-                );
806
-                $this->_admin_page_title .= '">';
807
-
808
-                $this->_admin_page_title .= sprintf(
809
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
810
-                    htmlentities(urldecode($event_name), ENT_QUOTES, 'UTF-8')
811
-                );
812
-                $this->_admin_page_title .= '</a>';
813
-            }
814
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
815
-        }
816
-        // grab messages at the last second
817
-        $this->_template_args['notices'] = EE_Error::get_notices();
818
-        // path to template
819
-        $template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
820
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
821
-            $template_path,
822
-            $this->_template_args,
823
-            true
824
-        );
825
-
826
-        // the details template wrapper
827
-        $this->display_admin_page_with_sidebar();
828
-    }
829
-
830
-
831
-    /**
832
-     *        _transaction_details_metaboxes
833
-     *
834
-     * @access protected
835
-     * @return void
836
-     * @throws EE_Error
837
-     * @throws InvalidArgumentException
838
-     * @throws InvalidDataTypeException
839
-     * @throws InvalidInterfaceException
840
-     * @throws RuntimeException
841
-     * @throws ReflectionException
842
-     */
843
-    protected function _transaction_details_metaboxes()
844
-    {
845
-
846
-        $this->_set_transaction_object();
847
-
848
-        if (! $this->_transaction instanceof EE_Transaction) {
849
-            return;
850
-        }
851
-        add_meta_box(
852
-            'edit-txn-details-mbox',
853
-            esc_html__('Transaction Details', 'event_espresso'),
854
-            [$this, 'txn_details_meta_box'],
855
-            $this->_wp_page_slug,
856
-            'normal',
857
-            'high'
858
-        );
859
-        add_meta_box(
860
-            'edit-txn-attendees-mbox',
861
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
862
-            [$this, 'txn_attendees_meta_box'],
863
-            $this->_wp_page_slug,
864
-            'normal',
865
-            'high',
866
-            ['TXN_ID' => $this->_transaction->ID()]
867
-        );
868
-        add_meta_box(
869
-            'edit-txn-registrant-mbox',
870
-            esc_html__('Primary Contact', 'event_espresso'),
871
-            [$this, 'txn_registrant_side_meta_box'],
872
-            $this->_wp_page_slug,
873
-            'side',
874
-            'high'
875
-        );
876
-        add_meta_box(
877
-            'edit-txn-billing-info-mbox',
878
-            esc_html__('Billing Information', 'event_espresso'),
879
-            [$this, 'txn_billing_info_side_meta_box'],
880
-            $this->_wp_page_slug,
881
-            'side',
882
-            'high'
883
-        );
884
-    }
885
-
886
-
887
-    /**
888
-     * Callback for transaction actions metabox.
889
-     *
890
-     * @param EE_Transaction|null $transaction
891
-     * @return string
892
-     * @throws DomainException
893
-     * @throws EE_Error
894
-     * @throws InvalidArgumentException
895
-     * @throws InvalidDataTypeException
896
-     * @throws InvalidInterfaceException
897
-     * @throws ReflectionException
898
-     * @throws RuntimeException
899
-     */
900
-    public function getActionButtons(EE_Transaction $transaction = null)
901
-    {
902
-        $content = '';
903
-        $actions = [];
904
-        if (! $transaction instanceof EE_Transaction) {
905
-            return $content;
906
-        }
907
-        /** @var EE_Registration $primary_registration */
908
-        $primary_registration = $transaction->primary_registration();
909
-        $attendee             = $primary_registration instanceof EE_Registration
910
-            ? $primary_registration->attendee()
911
-            : null;
912
-
913
-        if (
914
-            $attendee instanceof EE_Attendee
915
-            && EE_Registry::instance()->CAP->current_user_can(
916
-                'ee_send_message',
917
-                'espresso_transactions_send_payment_reminder'
918
-            )
919
-        ) {
920
-            $actions['payment_reminder'] =
921
-                EEH_MSG_Template::is_mt_active('payment_reminder')
922
-                && $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
923
-                && $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
924
-                    ? EEH_Template::get_button_or_link(
925
-                        EE_Admin_Page::add_query_args_and_nonce(
926
-                            [
927
-                            'action'      => 'send_payment_reminder',
928
-                            'TXN_ID'      => $this->_transaction->ID(),
929
-                            'redirect_to' => 'view_transaction',
930
-                            ],
931
-                            TXN_ADMIN_URL
932
-                        ),
933
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
934
-                        'button secondary-button',
935
-                        'dashicons dashicons-email-alt'
936
-                    )
937
-                    : '';
938
-        }
939
-
940
-        if (
941
-            EE_Registry::instance()->CAP->current_user_can(
942
-                'ee_edit_payments',
943
-                'espresso_transactions_recalculate_line_items'
944
-            )
945
-        ) {
946
-            $actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
947
-                EE_Admin_Page::add_query_args_and_nonce(
948
-                    [
949
-                        'action'      => 'espresso_recalculate_line_items',
950
-                        'TXN_ID'      => $this->_transaction->ID(),
951
-                        'redirect_to' => 'view_transaction',
952
-                    ],
953
-                    TXN_ADMIN_URL
954
-                ),
955
-                esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
956
-                'button secondary-button',
957
-                'dashicons dashicons-update'
958
-            );
959
-        }
960
-
961
-        if (
962
-            $primary_registration instanceof EE_Registration
963
-            && EEH_MSG_Template::is_mt_active('receipt')
964
-        ) {
965
-            $actions['receipt'] = EEH_Template::get_button_or_link(
966
-                $primary_registration->receipt_url(),
967
-                esc_html__('View Receipt', 'event_espresso'),
968
-                'button secondary-button',
969
-                'dashicons dashicons-media-default'
970
-            );
971
-        }
972
-
973
-        if (
974
-            $primary_registration instanceof EE_Registration
975
-            && EEH_MSG_Template::is_mt_active('invoice')
976
-        ) {
977
-            $actions['invoice'] = EEH_Template::get_button_or_link(
978
-                $primary_registration->invoice_url(),
979
-                esc_html__('View Invoice', 'event_espresso'),
980
-                'button secondary-button',
981
-                'dashicons dashicons-media-spreadsheet'
982
-            );
983
-        }
984
-        $actions = array_filter(
985
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
986
-        );
987
-        if ($actions) {
988
-            $content = '<ul>';
989
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
990
-            $content .= '</uL>';
991
-        }
992
-        return $content;
993
-    }
994
-
995
-
996
-    /**
997
-     * txn_details_meta_box
998
-     * generates HTML for the Transaction main meta box
999
-     *
1000
-     * @return void
1001
-     * @throws DomainException
1002
-     * @throws EE_Error
1003
-     * @throws InvalidArgumentException
1004
-     * @throws InvalidDataTypeException
1005
-     * @throws InvalidInterfaceException
1006
-     * @throws RuntimeException
1007
-     * @throws ReflectionException
1008
-     */
1009
-    public function txn_details_meta_box()
1010
-    {
1011
-        $this->_set_transaction_object();
1012
-        $this->_template_args['TXN_ID']              = $this->_transaction->ID();
1013
-        $this->_template_args['attendee']            =
1014
-            $this->_transaction->primary_registration() instanceof EE_Registration
1015
-                ? $this->_transaction->primary_registration()->attendee()
1016
-                : null;
1017
-        $this->_template_args['can_edit_payments']   = EE_Registry::instance()->CAP->current_user_can(
1018
-            'ee_edit_payments',
1019
-            'apply_payment_or_refund_from_registration_details'
1020
-        );
1021
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
-            'ee_delete_payments',
1023
-            'delete_payment_from_registration_details'
1024
-        );
1025
-
1026
-        // get line table
1027
-        EEH_Autoloader::register_line_item_display_autoloaders();
1028
-        $Line_Item_Display                       = new EE_Line_Item_Display(
1029
-            'admin_table',
1030
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1031
-        );
1032
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1033
-            $this->_transaction->total_line_item()
1034
-        );
1035
-        $this->_template_args['REG_code']        =
1036
-            $this->_transaction->primary_registration() instanceof EE_Registration
1037
-                ? $this->_transaction->primary_registration()->reg_code()
1038
-                : null;
1039
-        // process taxes
1040
-        $taxes                         = $this->_transaction->line_items([['LIN_type' => EEM_Line_Item::type_tax]]);
1041
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1042
-
1043
-        $this->_template_args['grand_total']     = EEH_Template::format_currency(
1044
-            $this->_transaction->total(),
1045
-            false,
1046
-            false
1047
-        );
1048
-        $this->_template_args['grand_raw_total'] = $this->_transaction->total();
1049
-        $this->_template_args['TXN_status']      = $this->_transaction->status_ID();
1050
-
1051
-        // process payment details
1052
-        $payments = $this->_transaction->payments();
1053
-        if (! empty($payments)) {
1054
-            $this->_template_args['payments']              = $payments;
1055
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1056
-        } else {
1057
-            $this->_template_args['payments']              = false;
1058
-            $this->_template_args['existing_reg_payments'] = [];
1059
-        }
1060
-
1061
-        $this->_template_args['edit_payment_url']   = add_query_arg(['action' => 'edit_payment'], TXN_ADMIN_URL);
1062
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1063
-            ['action' => 'espresso_delete_payment'],
1064
-            TXN_ADMIN_URL
1065
-        );
1066
-
1067
-        if (isset($txn_details['invoice_number'])) {
1068
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1069
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1070
-                'Invoice Number',
1071
-                'event_espresso'
1072
-            );
1073
-        }
1074
-
1075
-        $this->_template_args['txn_details']['registration_session']['value'] =
1076
-            $this->_transaction->primary_registration() instanceof EE_Registration
1077
-                ? $this->_transaction->primary_registration()->session_ID()
1078
-                : null;
1079
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1080
-            'Registration Session',
1081
-            'event_espresso'
1082
-        );
1083
-
1084
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1085
-            ? $this->_session['ip_address']
1086
-            : '';
1087
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1088
-            'Transaction placed from IP',
1089
-            'event_espresso'
1090
-        );
1091
-
1092
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1093
-            ? $this->_session['user_agent']
1094
-            : '';
1095
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1096
-            'Registrant User Agent',
1097
-            'event_espresso'
1098
-        );
1099
-
1100
-        $reg_steps = '<ul>';
1101
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1102
-            if ($reg_step_status === true) {
1103
-                $reg_steps .= '<li style="color:#70cc50">'
1104
-                              . sprintf(
1105
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1106
-                                  ucwords(str_replace('_', ' ', $reg_step))
1107
-                              )
1108
-                              . '</li>';
1109
-            } elseif ($reg_step_status !== false && is_numeric($reg_step_status)) {
1110
-                $reg_steps .= '<li style="color:#2EA2CC">'
1111
-                              . sprintf(
1112
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1113
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1114
-                                  date(
1115
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1116
-                                      $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1117
-                                  )
1118
-                              )
1119
-                              . '</li>';
1120
-            } else {
1121
-                $reg_steps .= '<li style="color:#E76700">'
1122
-                              . sprintf(
1123
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1124
-                                  ucwords(str_replace('_', ' ', $reg_step))
1125
-                              )
1126
-                              . '</li>';
1127
-            }
1128
-        }
1129
-        $reg_steps                                                 .= '</ul>';
1130
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1131
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1132
-            'Registration Step Progress',
1133
-            'event_espresso'
1134
-        );
1135
-
1136
-
1137
-        $this->_get_registrations_to_apply_payment_to();
1138
-        $this->_get_payment_methods($payments);
1139
-        $this->_get_payment_status_array();
1140
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1141
-
1142
-        $this->_template_args['transaction_form_url']    = add_query_arg(
1143
-            [
1144
-                'action'  => 'edit_transaction',
1145
-                'process' => 'transaction',
1146
-            ],
1147
-            TXN_ADMIN_URL
1148
-        );
1149
-        $this->_template_args['apply_payment_form_url']  = add_query_arg(
1150
-            [
1151
-                'page'   => 'espresso_transactions',
1152
-                'action' => 'espresso_apply_payment',
1153
-            ],
1154
-            WP_AJAX_URL
1155
-        );
1156
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1157
-            [
1158
-                'page'   => 'espresso_transactions',
1159
-                'action' => 'espresso_delete_payment',
1160
-            ],
1161
-            WP_AJAX_URL
1162
-        );
1163
-
1164
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1165
-
1166
-        // 'espresso_delete_payment_nonce'
1167
-
1168
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1169
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1170
-    }
1171
-
1172
-
1173
-    /**
1174
-     * _get_registration_payment_IDs
1175
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1176
-     *
1177
-     * @access protected
1178
-     * @param EE_Payment[] $payments
1179
-     * @return array
1180
-     * @throws EE_Error
1181
-     * @throws InvalidArgumentException
1182
-     * @throws InvalidDataTypeException
1183
-     * @throws InvalidInterfaceException
1184
-     * @throws ReflectionException
1185
-     */
1186
-    protected function _get_registration_payment_IDs($payments = [])
1187
-    {
1188
-        $existing_reg_payments = [];
1189
-        // get all reg payments for these payments
1190
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1191
-            [
1192
-                [
1193
-                    'PAY_ID' => [
1194
-                        'IN',
1195
-                        array_keys($payments),
1196
-                    ],
1197
-                ],
1198
-            ]
1199
-        );
1200
-        if (! empty($reg_payments)) {
1201
-            foreach ($payments as $payment) {
1202
-                if (! $payment instanceof EE_Payment) {
1203
-                    continue;
1204
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1205
-                    $existing_reg_payments[ $payment->ID() ] = [];
1206
-                }
1207
-                foreach ($reg_payments as $reg_payment) {
1208
-                    if (
1209
-                        $reg_payment instanceof EE_Registration_Payment
1210
-                        && $reg_payment->payment_ID() === $payment->ID()
1211
-                    ) {
1212
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1213
-                    }
1214
-                }
1215
-            }
1216
-        }
1217
-
1218
-        return $existing_reg_payments;
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * _get_registrations_to_apply_payment_to
1224
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1225
-     * which allows the admin to only apply the payment to the specific registrations
1226
-     *
1227
-     * @access protected
1228
-     * @return void
1229
-     * @throws EE_Error
1230
-     * @throws InvalidArgumentException
1231
-     * @throws InvalidDataTypeException
1232
-     * @throws InvalidInterfaceException
1233
-     * @throws ReflectionException
1234
-     */
1235
-    protected function _get_registrations_to_apply_payment_to()
1236
-    {
1237
-        // we want any registration with an active status (ie: not deleted or cancelled)
1238
-        $query_params                      = [
1239
-            [
1240
-                'STS_ID' => [
1241
-                    'IN',
1242
-                    [
1243
-                        EEM_Registration::status_id_approved,
1244
-                        EEM_Registration::status_id_pending_payment,
1245
-                        EEM_Registration::status_id_not_approved,
1246
-                    ],
1247
-                ],
1248
-            ],
1249
-        ];
1250
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1251
-            '',
1252
-            'txn-admin-apply-payment-to-registrations-dv',
1253
-            '',
1254
-            'clear: both; margin: 1.5em 0 0; display: none;'
1255
-        );
1256
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1257
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1258
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1259
-            EEH_HTML::tr(
1260
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1261
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1262
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1263
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1264
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1265
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1266
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1267
-            )
1268
-        );
1269
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1270
-        // get registrations for TXN
1271
-        $registrations         = $this->_transaction->registrations($query_params);
1272
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1273
-        foreach ($registrations as $registration) {
1274
-            if ($registration instanceof EE_Registration) {
1275
-                $attendee_name                     = $registration->attendee() instanceof EE_Attendee
1276
-                    ? $registration->attendee()->full_name()
1277
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1278
-                $owing                             = $registration->final_price() - $registration->paid();
1279
-                $taxable                           = $registration->ticket()->taxable()
1280
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1281
-                    : '';
1282
-                $checked                           = empty($existing_reg_payments)
1283
-                                                     || in_array($registration->ID(), $existing_reg_payments, true)
1284
-                    ? ' checked'
1285
-                    : '';
1286
-                $disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1287
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
-                    EEH_HTML::td($registration->ID()) .
1289
-                    EEH_HTML::td($attendee_name) .
1290
-                    EEH_HTML::td(
1291
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
-                    ) .
1293
-                    EEH_HTML::td($registration->event_name()) .
1294
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
-                    EEH_HTML::td(
1296
-                        EEH_Template::format_currency($owing),
1297
-                        '',
1298
-                        'txn-admin-payment-owing-td jst-cntr'
1299
-                    ) .
1300
-                    EEH_HTML::td(
1301
-                        '<input type="checkbox" value="' . $registration->ID()
1302
-                        . '" name="txn_admin_payment[registrations]"'
1303
-                        . $checked . $disabled . '>',
1304
-                        '',
1305
-                        'jst-cntr'
1306
-                    ),
1307
-                    'apply-payment-registration-row-' . $registration->ID()
1308
-                );
1309
-            }
1310
-        }
1311
-        $registrations_to_apply_payment_to                         .= EEH_HTML::tbodyx();
1312
-        $registrations_to_apply_payment_to                         .= EEH_HTML::tablex();
1313
-        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1314
-        $registrations_to_apply_payment_to                         .= EEH_HTML::p(
1315
-            esc_html__(
1316
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1317
-                'event_espresso'
1318
-            ),
1319
-            '',
1320
-            'clear description'
1321
-        );
1322
-        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1323
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * _get_reg_status_selection
1329
-     *
1330
-     * @return void
1331
-     * @throws EE_Error
1332
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1333
-     *         instead of events.
1334
-     * @access protected
1335
-     */
1336
-    protected function _get_reg_status_selection()
1337
-    {
1338
-        // first get all possible statuses
1339
-        $statuses = EEM_Registration::reg_status_array([], true);
1340
-        // let's add a "don't change" option.
1341
-        $status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1342
-        $status_array                                        = array_merge($status_array, $statuses);
1343
-        $this->_template_args['status_change_select']        = EEH_Form_Fields::select_input(
1344
-            'txn_reg_status_change[reg_status]',
1345
-            $status_array,
1346
-            'NAN',
1347
-            'id="txn-admin-payment-reg-status-inp"',
1348
-            'txn-reg-status-change-reg-status'
1349
-        );
1350
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1351
-            'delete_txn_reg_status_change[reg_status]',
1352
-            $status_array,
1353
-            'NAN',
1354
-            'delete-txn-admin-payment-reg-status-inp',
1355
-            'delete-txn-reg-status-change-reg-status'
1356
-        );
1357
-    }
1358
-
1359
-
1360
-    /**
1361
-     *    _get_payment_methods
1362
-     * Gets all the payment methods available generally, or the ones that are already
1363
-     * selected on these payments (in case their payment methods are no longer active).
1364
-     * Has the side-effect of updating the template args' payment_methods item
1365
-     *
1366
-     * @access private
1367
-     * @param EE_Payment[] to show on this page
1368
-     * @return void
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    private function _get_payment_methods($payments = [])
1376
-    {
1377
-        $payment_methods_of_payments = [];
1378
-        foreach ($payments as $payment) {
1379
-            if ($payment instanceof EE_Payment) {
1380
-                $payment_methods_of_payments[] = $payment->ID();
1381
-            }
1382
-        }
1383
-        if ($payment_methods_of_payments) {
1384
-            $query_args = [
1385
-                [
1386
-                    'OR*payment_method_for_payment' => [
1387
-                        'PMD_ID'    => ['IN', $payment_methods_of_payments],
1388
-                        'PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%'],
1389
-                    ],
1390
-                ],
1391
-            ];
1392
-        } else {
1393
-            $query_args = [['PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%']]];
1394
-        }
1395
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1396
-    }
1397
-
1398
-
1399
-    /**
1400
-     * txn_attendees_meta_box
1401
-     *    generates HTML for the Attendees Transaction main meta box
1402
-     *
1403
-     * @access public
1404
-     * @param WP_Post $post
1405
-     * @param array   $metabox
1406
-     * @return void
1407
-     * @throws DomainException
1408
-     * @throws EE_Error
1409
-     * @throws InvalidArgumentException
1410
-     * @throws InvalidDataTypeException
1411
-     * @throws InvalidInterfaceException
1412
-     * @throws ReflectionException
1413
-     */
1414
-    public function txn_attendees_meta_box($post, $metabox = ['args' => []])
1415
-    {
1416
-
1417
-        /** @noinspection NonSecureExtractUsageInspection */
1418
-        extract($metabox['args']);
1419
-        $this->_template_args['post']            = $post;
1420
-        $this->_template_args['event_attendees'] = [];
1421
-        // process items in cart
1422
-        $line_items = $this->_transaction->get_many_related(
1423
-            'Line_Item',
1424
-            [['LIN_type' => 'line-item']]
1425
-        );
1426
-        if (! empty($line_items)) {
1427
-            foreach ($line_items as $item) {
1428
-                if ($item instanceof EE_Line_Item) {
1429
-                    switch ($item->OBJ_type()) {
1430
-                        case 'Event':
1431
-                            break;
1432
-                        case 'Ticket':
1433
-                            $ticket = $item->ticket();
1434
-                            // right now we're only handling tickets here.
1435
-                            // Cause its expected that only tickets will have attendees right?
1436
-                            if (! $ticket instanceof EE_Ticket) {
1437
-                                break;
1438
-                            }
1439
-                            try {
1440
-                                $event_name = $ticket->get_event_name();
1441
-                            } catch (Exception $e) {
1442
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1443
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1444
-                            }
1445
-                            $event_name   .= ' - ' . $item->name();
1446
-                            $ticket_price = EEH_Template::format_currency($item->unit_price());
1447
-                            // now get all of the registrations for this transaction that use this ticket
1448
-                            $registrations = $ticket->registrations(
1449
-                                [['TXN_ID' => $this->_transaction->ID()]]
1450
-                            );
1451
-                            foreach ($registrations as $registration) {
1452
-                                if (! $registration instanceof EE_Registration) {
1453
-                                    break;
1454
-                                }
1455
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1456
-                                    = $registration->status_ID();
1457
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1458
-                                    = $registration->count();
1459
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1460
-                                    = $event_name;
1461
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1462
-                                    = $ticket_price;
1463
-                                // attendee info
1464
-                                $attendee = $registration->get_first_related('Attendee');
1465
-                                if ($attendee instanceof EE_Attendee) {
1466
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1467
-                                        = $attendee->ID();
1468
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1469
-                                        = $attendee->full_name();
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1471
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1472
-                                          . esc_html__(
1473
-                                              ' Event',
1474
-                                              'event_espresso'
1475
-                                          )
1476
-                                          . '">' . $attendee->email() . '</a>';
1477
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1478
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1479
-                                } else {
1480
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']   = '';
1481
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1482
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']    = '';
1483
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']  = '';
1484
-                                }
1485
-                            }
1486
-                            break;
1487
-                    }
1488
-                }
1489
-            }
1490
-
1491
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1492
-                [
1493
-                    'action'  => 'edit_transaction',
1494
-                    'process' => 'attendees',
1495
-                ],
1496
-                TXN_ADMIN_URL
1497
-            );
1498
-            echo EEH_Template::display_template(
1499
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1500
-                $this->_template_args,
1501
-                true
1502
-            );
1503
-        } else {
1504
-            printf(
1505
-                esc_html__(
1506
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1507
-                    'event_espresso'
1508
-                ),
1509
-                '<p class="important-notice">',
1510
-                '</p>'
1511
-            );
1512
-        }
1513
-    }
1514
-
1515
-
1516
-    /**
1517
-     * txn_registrant_side_meta_box
1518
-     * generates HTML for the Edit Transaction side meta box
1519
-     *
1520
-     * @access public
1521
-     * @return void
1522
-     * @throws DomainException
1523
-     * @throws EE_Error
1524
-     * @throws InvalidArgumentException
1525
-     * @throws InvalidDataTypeException
1526
-     * @throws InvalidInterfaceException
1527
-     * @throws ReflectionException
1528
-     */
1529
-    public function txn_registrant_side_meta_box()
1530
-    {
1531
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1532
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1533
-            : null;
1534
-        if (! $primary_att instanceof EE_Attendee) {
1535
-            $this->_template_args['no_attendee_message'] = esc_html__(
1536
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1537
-                'event_espresso'
1538
-            );
1539
-            $primary_att                           = EEM_Attendee::instance()->create_default_object();
1540
-        }
1541
-        $this->_template_args['ATT_ID']            = $primary_att->ID();
1542
-        $this->_template_args['prime_reg_fname']   = $primary_att->fname();
1543
-        $this->_template_args['prime_reg_lname']   = $primary_att->lname();
1544
-        $this->_template_args['prime_reg_email']   = $primary_att->email();
1545
-        $this->_template_args['prime_reg_phone']   = $primary_att->phone();
1546
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1547
-            [
1548
-                'action' => 'edit_attendee',
1549
-                'post'   => $primary_att->ID(),
1550
-            ],
1551
-            REG_ADMIN_URL
1552
-        );
1553
-        // get formatted address for registrant
1554
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1555
-        echo EEH_Template::display_template(
1556
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1557
-            $this->_template_args,
1558
-            true
1559
-        );
1560
-    }
1561
-
1562
-
1563
-    /**
1564
-     * txn_billing_info_side_meta_box
1565
-     *    generates HTML for the Edit Transaction side meta box
1566
-     *
1567
-     * @access public
1568
-     * @return void
1569
-     * @throws DomainException
1570
-     * @throws EE_Error
1571
-     * @throws ReflectionException
1572
-     */
1573
-    public function txn_billing_info_side_meta_box()
1574
-    {
1575
-
1576
-        $this->_template_args['billing_form']     = $this->_transaction->billing_info();
1577
-        $this->_template_args['billing_form_url'] = add_query_arg(
1578
-            ['action' => 'edit_transaction', 'process' => 'billing'],
1579
-            TXN_ADMIN_URL
1580
-        );
1581
-
1582
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1583
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1584
-    }
1585
-
1586
-
1587
-    /**
1588
-     * apply_payments_or_refunds
1589
-     *    registers a payment or refund made towards a transaction
1590
-     *
1591
-     * @access public
1592
-     * @return void
1593
-     * @throws EE_Error
1594
-     * @throws InvalidArgumentException
1595
-     * @throws ReflectionException
1596
-     * @throws RuntimeException
1597
-     * @throws InvalidDataTypeException
1598
-     * @throws InvalidInterfaceException
1599
-     */
1600
-    public function apply_payments_or_refunds()
1601
-    {
1602
-        $json_response_data = ['return_data' => false];
1603
-        $valid_data         = $this->_validate_payment_request_data();
1604
-        $has_access         = EE_Registry::instance()->CAP->current_user_can(
1605
-            'ee_edit_payments',
1606
-            'apply_payment_or_refund_from_registration_details'
1607
-        );
1608
-        if (! empty($valid_data) && $has_access) {
1609
-            $PAY_ID = $valid_data['PAY_ID'];
1610
-            // save  the new payment
1611
-            $payment = $this->_create_payment_from_request_data($valid_data);
1612
-            // get the TXN for this payment
1613
-            $transaction = $payment->transaction();
1614
-            // verify transaction
1615
-            if ($transaction instanceof EE_Transaction) {
1616
-                // calculate_total_payments_and_update_status
1617
-                $this->_process_transaction_payments($transaction);
1618
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1619
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1620
-                // apply payment to registrations (if applicable)
1621
-                if (! empty($REG_IDs)) {
1622
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1623
-                    $this->_maybe_send_notifications();
1624
-                    // now process status changes for the same registrations
1625
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1626
-                }
1627
-                $this->_maybe_send_notifications($payment);
1628
-                // prepare to render page
1629
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1630
-                do_action(
1631
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1632
-                    $transaction,
1633
-                    $payment
1634
-                );
1635
-            } else {
1636
-                EE_Error::add_error(
1637
-                    esc_html__(
1638
-                        'A valid Transaction for this payment could not be retrieved.',
1639
-                        'event_espresso'
1640
-                    ),
1641
-                    __FILE__,
1642
-                    __FUNCTION__,
1643
-                    __LINE__
1644
-                );
1645
-            }
1646
-        } elseif ($has_access) {
1647
-            EE_Error::add_error(
1648
-                esc_html__(
1649
-                    'The payment form data could not be processed. Please try again.',
1650
-                    'event_espresso'
1651
-                ),
1652
-                __FILE__,
1653
-                __FUNCTION__,
1654
-                __LINE__
1655
-            );
1656
-        } else {
1657
-            EE_Error::add_error(
1658
-                esc_html__(
1659
-                    'You do not have access to apply payments or refunds to a registration.',
1660
-                    'event_espresso'
1661
-                ),
1662
-                __FILE__,
1663
-                __FUNCTION__,
1664
-                __LINE__
1665
-            );
1666
-        }
1667
-        $notices              = EE_Error::get_notices(
1668
-            false,
1669
-            false,
1670
-            false
1671
-        );
1672
-        $this->_template_args = [
1673
-            'data'    => $json_response_data,
1674
-            'error'   => $notices['errors'],
1675
-            'success' => $notices['success'],
1676
-        ];
1677
-        $this->_return_json();
1678
-    }
1679
-
1680
-
1681
-    /**
1682
-     * _validate_payment_request_data
1683
-     *
1684
-     * @return array
1685
-     * @throws EE_Error
1686
-     * @throws InvalidArgumentException
1687
-     * @throws InvalidDataTypeException
1688
-     * @throws InvalidInterfaceException
1689
-     */
1690
-    protected function _validate_payment_request_data()
1691
-    {
1692
-        if (! $this->request->requestParamIsSet('txn_admin_payment')) {
1693
-            return [];
1694
-        }
1695
-        $payment_form = $this->_generate_payment_form_section();
1696
-        try {
1697
-            if ($payment_form->was_submitted()) {
1698
-                $payment_form->receive_form_submission();
1699
-                if (! $payment_form->is_valid()) {
1700
-                    $submission_error_messages = [];
1701
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1702
-                        if ($validation_error instanceof EE_Validation_Error) {
1703
-                            $form_input = $validation_error->get_form_section();
1704
-                            $submission_error_messages[] = sprintf(
1705
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1706
-                                $form_input instanceof EE_Form_Input_Base ? $form_input->html_label_text() : '',
1707
-                                $validation_error->getMessage()
1708
-                            );
1709
-                        }
1710
-                    }
1711
-                    EE_Error::add_error(
1712
-                        implode('<br />', $submission_error_messages),
1713
-                        __FILE__,
1714
-                        __FUNCTION__,
1715
-                        __LINE__
1716
-                    );
1717
-                    return [];
1718
-                }
1719
-            }
1720
-        } catch (EE_Error $e) {
1721
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1722
-            return [];
1723
-        }
1724
-
1725
-        return $payment_form->valid_data();
1726
-    }
1727
-
1728
-
1729
-    /**
1730
-     * _generate_payment_form_section
1731
-     *
1732
-     * @return EE_Form_Section_Proper
1733
-     * @throws EE_Error
1734
-     */
1735
-    protected function _generate_payment_form_section()
1736
-    {
1737
-        return new EE_Form_Section_Proper(
1738
-            [
1739
-                'name'        => 'txn_admin_payment',
1740
-                'subsections' => [
1741
-                    'PAY_ID'          => new EE_Text_Input(
1742
-                        [
1743
-                            'default'               => 0,
1744
-                            'required'              => false,
1745
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1746
-                            'validation_strategies' => [new EE_Int_Normalization()],
1747
-                        ]
1748
-                    ),
1749
-                    'TXN_ID'          => new EE_Text_Input(
1750
-                        [
1751
-                            'default'               => 0,
1752
-                            'required'              => true,
1753
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1754
-                            'validation_strategies' => [new EE_Int_Normalization()],
1755
-                        ]
1756
-                    ),
1757
-                    'type'            => new EE_Text_Input(
1758
-                        [
1759
-                            'default'               => 1,
1760
-                            'required'              => true,
1761
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1762
-                            'validation_strategies' => [new EE_Int_Normalization()],
1763
-                        ]
1764
-                    ),
1765
-                    'amount'          => new EE_Text_Input(
1766
-                        [
1767
-                            'default'               => 0,
1768
-                            'required'              => true,
1769
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1770
-                            'validation_strategies' => [new EE_Float_Normalization()],
1771
-                        ]
1772
-                    ),
1773
-                    'status'          => new EE_Text_Input(
1774
-                        [
1775
-                            'default'         => EEM_Payment::status_id_approved,
1776
-                            'required'        => true,
1777
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1778
-                        ]
1779
-                    ),
1780
-                    'PMD_ID'          => new EE_Text_Input(
1781
-                        [
1782
-                            'default'               => 2,
1783
-                            'required'              => true,
1784
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1785
-                            'validation_strategies' => [new EE_Int_Normalization()],
1786
-                        ]
1787
-                    ),
1788
-                    'date'            => new EE_Text_Input(
1789
-                        [
1790
-                            'default'         => time(),
1791
-                            'required'        => true,
1792
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1793
-                        ]
1794
-                    ),
1795
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1796
-                        [
1797
-                            'default'               => '',
1798
-                            'required'              => false,
1799
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1800
-                            'validation_strategies' => [
1801
-                                new EE_Max_Length_Validation_Strategy(
1802
-                                    esc_html__('Input too long', 'event_espresso'),
1803
-                                    100
1804
-                                ),
1805
-                            ],
1806
-                        ]
1807
-                    ),
1808
-                    'po_number'       => new EE_Text_Input(
1809
-                        [
1810
-                            'default'               => '',
1811
-                            'required'              => false,
1812
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1813
-                            'validation_strategies' => [
1814
-                                new EE_Max_Length_Validation_Strategy(
1815
-                                    esc_html__('Input too long', 'event_espresso'),
1816
-                                    100
1817
-                                ),
1818
-                            ],
1819
-                        ]
1820
-                    ),
1821
-                    'accounting'      => new EE_Text_Input(
1822
-                        [
1823
-                            'default'               => '',
1824
-                            'required'              => false,
1825
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1826
-                            'validation_strategies' => [
1827
-                                new EE_Max_Length_Validation_Strategy(
1828
-                                    esc_html__('Input too long', 'event_espresso'),
1829
-                                    100
1830
-                                ),
1831
-                            ],
1832
-                        ]
1833
-                    ),
1834
-                ],
1835
-            ]
1836
-        );
1837
-    }
1838
-
1839
-
1840
-    /**
1841
-     * _create_payment_from_request_data
1842
-     *
1843
-     * @param array $valid_data
1844
-     * @return EE_Payment
1845
-     * @throws EE_Error
1846
-     * @throws InvalidArgumentException
1847
-     * @throws InvalidDataTypeException
1848
-     * @throws InvalidInterfaceException
1849
-     * @throws ReflectionException
1850
-     */
1851
-    protected function _create_payment_from_request_data($valid_data)
1852
-    {
1853
-        $PAY_ID = $valid_data['PAY_ID'];
1854
-        // get payment amount
1855
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1856
-        // payments have a type value of 1 and refunds have a type value of -1
1857
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1858
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1859
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1860
-        $date    = $valid_data['date']
1861
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1862
-            : date('Y-m-d g:i a', current_time('timestamp'));
1863
-        $payment = EE_Payment::new_instance(
1864
-            [
1865
-                'TXN_ID'              => $valid_data['TXN_ID'],
1866
-                'STS_ID'              => $valid_data['status'],
1867
-                'PAY_timestamp'       => $date,
1868
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1869
-                'PMD_ID'              => $valid_data['PMD_ID'],
1870
-                'PAY_amount'          => $amount,
1871
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1872
-                'PAY_po_number'       => $valid_data['po_number'],
1873
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1874
-                'PAY_details'         => $valid_data,
1875
-                'PAY_ID'              => $PAY_ID,
1876
-            ],
1877
-            '',
1878
-            ['Y-m-d', 'g:i a']
1879
-        );
1880
-
1881
-        if (! $payment->save()) {
1882
-            EE_Error::add_error(
1883
-                sprintf(
1884
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1885
-                    $payment->ID()
1886
-                ),
1887
-                __FILE__,
1888
-                __FUNCTION__,
1889
-                __LINE__
1890
-            );
1891
-        }
1892
-
1893
-        return $payment;
1894
-    }
1895
-
1896
-
1897
-    /**
1898
-     * _process_transaction_payments
1899
-     *
1900
-     * @param EE_Transaction $transaction
1901
-     * @return void
1902
-     * @throws EE_Error
1903
-     * @throws InvalidArgumentException
1904
-     * @throws ReflectionException
1905
-     * @throws InvalidDataTypeException
1906
-     * @throws InvalidInterfaceException
1907
-     */
1908
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1909
-    {
1910
-        /** @type EE_Transaction_Payments $transaction_payments */
1911
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1912
-        // update the transaction with this payment
1913
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1914
-            EE_Error::add_success(
1915
-                esc_html__(
1916
-                    'The payment has been processed successfully.',
1917
-                    'event_espresso'
1918
-                ),
1919
-                __FILE__,
1920
-                __FUNCTION__,
1921
-                __LINE__
1922
-            );
1923
-        } else {
1924
-            EE_Error::add_error(
1925
-                esc_html__(
1926
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1927
-                    'event_espresso'
1928
-                ),
1929
-                __FILE__,
1930
-                __FUNCTION__,
1931
-                __LINE__
1932
-            );
1933
-        }
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * _get_REG_IDs_to_apply_payment_to
1939
-     * returns a list of registration IDs that the payment will apply to
1940
-     *
1941
-     * @param EE_Payment $payment
1942
-     * @return array
1943
-     * @throws EE_Error
1944
-     * @throws InvalidArgumentException
1945
-     * @throws InvalidDataTypeException
1946
-     * @throws InvalidInterfaceException
1947
-     * @throws ReflectionException
1948
-     */
1949
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1950
-    {
1951
-        // grab array of IDs for specific registrations to apply changes to
1952
-        $REG_IDs = $this->request->getRequestParam('txn_admin_payment[registrations]', [], 'int', true);
1953
-        // nothing specified ? then get all reg IDs
1954
-        if (empty($REG_IDs)) {
1955
-            $registrations = $payment->transaction()->registrations();
1956
-            $REG_IDs       = ! empty($registrations)
1957
-                ? array_keys($registrations)
1958
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1959
-        }
1960
-
1961
-        // ensure that REG_IDs are integers and NOT strings
1962
-        return array_map('intval', $REG_IDs);
1963
-    }
1964
-
1965
-
1966
-    /**
1967
-     * @return array
1968
-     */
1969
-    public function existing_reg_payment_REG_IDs()
1970
-    {
1971
-        return $this->_existing_reg_payment_REG_IDs;
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * @param array $existing_reg_payment_REG_IDs
1977
-     */
1978
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1979
-    {
1980
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1981
-    }
1982
-
1983
-
1984
-    /**
1985
-     * _get_existing_reg_payment_REG_IDs
1986
-     * returns a list of registration IDs that the payment is currently related to
1987
-     * as recorded in the database
1988
-     *
1989
-     * @param EE_Payment $payment
1990
-     * @return array
1991
-     * @throws EE_Error
1992
-     * @throws InvalidArgumentException
1993
-     * @throws InvalidDataTypeException
1994
-     * @throws InvalidInterfaceException
1995
-     * @throws ReflectionException
1996
-     */
1997
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1998
-    {
1999
-        if ($this->existing_reg_payment_REG_IDs() === null) {
2000
-            // let's get any existing reg payment records for this payment
2001
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2002
-            // but we only want the REG IDs, so grab the array keys
2003
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2004
-                ? array_keys($existing_reg_payment_REG_IDs)
2005
-                : [];
2006
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2007
-        }
2008
-
2009
-        return $this->existing_reg_payment_REG_IDs();
2010
-    }
2011
-
2012
-
2013
-    /**
2014
-     * _remove_existing_registration_payments
2015
-     * this calculates the difference between existing relations
2016
-     * to the supplied payment and the new list registration IDs,
2017
-     * removes any related registrations that no longer apply,
2018
-     * and then updates the registration paid fields
2019
-     *
2020
-     * @param EE_Payment $payment
2021
-     * @param int        $PAY_ID
2022
-     * @return bool;
2023
-     * @throws EE_Error
2024
-     * @throws InvalidArgumentException
2025
-     * @throws ReflectionException
2026
-     * @throws InvalidDataTypeException
2027
-     * @throws InvalidInterfaceException
2028
-     */
2029
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2030
-    {
2031
-        // newly created payments will have nothing recorded for $PAY_ID
2032
-        if (absint($PAY_ID) === 0) {
2033
-            return false;
2034
-        }
2035
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2036
-        if (empty($existing_reg_payment_REG_IDs)) {
2037
-            return false;
2038
-        }
2039
-        /** @type EE_Transaction_Payments $transaction_payments */
2040
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2041
-
2042
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2043
-            $payment,
2044
-            [
2045
-                [
2046
-                    'PAY_ID' => $payment->ID(),
2047
-                    'REG_ID' => ['IN', $existing_reg_payment_REG_IDs],
2048
-                ],
2049
-            ]
2050
-        );
2051
-    }
2052
-
2053
-
2054
-    /**
2055
-     * _update_registration_payments
2056
-     * this applies the payments to the selected registrations
2057
-     * but only if they have not already been paid for
2058
-     *
2059
-     * @param EE_Transaction $transaction
2060
-     * @param EE_Payment     $payment
2061
-     * @param array          $REG_IDs
2062
-     * @return void
2063
-     * @throws EE_Error
2064
-     * @throws InvalidArgumentException
2065
-     * @throws ReflectionException
2066
-     * @throws RuntimeException
2067
-     * @throws InvalidDataTypeException
2068
-     * @throws InvalidInterfaceException
2069
-     */
2070
-    protected function _update_registration_payments(
2071
-        EE_Transaction $transaction,
2072
-        EE_Payment $payment,
2073
-        $REG_IDs = []
2074
-    ) {
2075
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2076
-        // so let's do that using our set of REG_IDs from the form
2077
-        $registration_query_where_params = [
2078
-            'REG_ID' => ['IN', $REG_IDs],
2079
-        ];
2080
-        // but add in some conditions regarding payment,
2081
-        // so that we don't apply payments to registrations that are free or have already been paid for
2082
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2083
-        if (! $payment->is_a_refund()) {
2084
-            $registration_query_where_params['REG_final_price']  = ['!=', 0];
2085
-            $registration_query_where_params['REG_final_price*'] = ['!=', 'REG_paid', true];
2086
-        }
2087
-        $registrations = $transaction->registrations([$registration_query_where_params]);
2088
-        if (! empty($registrations)) {
2089
-            /** @type EE_Payment_Processor $payment_processor */
2090
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2091
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2092
-        }
2093
-    }
2094
-
2095
-
2096
-    /**
2097
-     * _process_registration_status_change
2098
-     * This processes requested registration status changes for all the registrations
2099
-     * on a given transaction and (optionally) sends out notifications for the changes.
2100
-     *
2101
-     * @param EE_Transaction $transaction
2102
-     * @param array          $REG_IDs
2103
-     * @return bool
2104
-     * @throws EE_Error
2105
-     * @throws InvalidArgumentException
2106
-     * @throws ReflectionException
2107
-     * @throws InvalidDataTypeException
2108
-     * @throws InvalidInterfaceException
2109
-     */
2110
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = [])
2111
-    {
2112
-        // first if there is no change in status then we get out.
2113
-        $reg_status = $this->request->getRequestParam('txn_reg_status_change[reg_status]', 'NAN');
2114
-        if ($reg_status === 'NAN') {
2115
-            // no error message, no change requested, just nothing to do man.
2116
-            return false;
2117
-        }
2118
-        /** @type EE_Transaction_Processor $transaction_processor */
2119
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2120
-
2121
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2122
-        return $transaction_processor->manually_update_registration_statuses(
2123
-            $transaction,
2124
-            $reg_status,
2125
-            [['REG_ID' => ['IN', $REG_IDs]]]
2126
-        );
2127
-    }
2128
-
2129
-
2130
-    /**
2131
-     * _build_payment_json_response
2132
-     *
2133
-     * @access public
2134
-     * @param EE_Payment  $payment
2135
-     * @param array       $REG_IDs
2136
-     * @param bool | null $delete_txn_reg_status_change
2137
-     * @return array
2138
-     * @throws EE_Error
2139
-     * @throws InvalidArgumentException
2140
-     * @throws InvalidDataTypeException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws ReflectionException
2143
-     */
2144
-    protected function _build_payment_json_response(
2145
-        EE_Payment $payment,
2146
-        $REG_IDs = [],
2147
-        $delete_txn_reg_status_change = null
2148
-    ) {
2149
-        // was the payment deleted ?
2150
-        if (is_bool($delete_txn_reg_status_change)) {
2151
-            return [
2152
-                'PAY_ID'                       => $payment->ID(),
2153
-                'amount'                       => $payment->amount(),
2154
-                'total_paid'                   => $payment->transaction()->paid(),
2155
-                'txn_status'                   => $payment->transaction()->status_ID(),
2156
-                'pay_status'                   => $payment->STS_ID(),
2157
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2158
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2159
-            ];
2160
-        }
2161
-
2162
-        $this->_get_payment_status_array();
2163
-        return [
2164
-            'amount'           => $payment->amount(),
2165
-            'total_paid'       => $payment->transaction()->paid(),
2166
-            'txn_status'       => $payment->transaction()->status_ID(),
2167
-            'pay_status'       => $payment->STS_ID(),
2168
-            'PAY_ID'           => $payment->ID(),
2169
-            'STS_ID'           => $payment->STS_ID(),
2170
-            'status'           => self::$_pay_status[ $payment->STS_ID() ],
2171
-            'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2172
-            'method'           => strtoupper($payment->source()),
2173
-            'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2174
-            'gateway'          => $payment->payment_method()
2175
-                ? $payment->payment_method()->admin_name()
2176
-                : esc_html__('Unknown', 'event_espresso'),
2177
-            'gateway_response' => $payment->gateway_response(),
2178
-            'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2179
-            'po_number'        => $payment->po_number(),
2180
-            'extra_accntng'    => $payment->extra_accntng(),
2181
-            'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2182
-        ];
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * delete_payment
2188
-     *    delete a payment or refund made towards a transaction
2189
-     *
2190
-     * @access public
2191
-     * @return void
2192
-     * @throws EE_Error
2193
-     * @throws InvalidArgumentException
2194
-     * @throws ReflectionException
2195
-     * @throws InvalidDataTypeException
2196
-     * @throws InvalidInterfaceException
2197
-     */
2198
-    public function delete_payment()
2199
-    {
2200
-        $json_response_data = ['return_data' => false];
2201
-        $PAY_ID = $this->request->getRequestParam('delete_txn_admin_payment[PAY_ID]', 0, 'int');
2202
-
2203
-        $can_delete         = EE_Registry::instance()->CAP->current_user_can(
2204
-            'ee_delete_payments',
2205
-            'delete_payment_from_registration_details'
2206
-        );
2207
-        if ($PAY_ID && $can_delete) {
2208
-            $delete_txn_reg_status_change = $this->request->getRequestParam(
2209
-                'delete_txn_reg_status_change',
2210
-                false,
2211
-                'bool'
2212
-            );
2213
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2214
-            if ($payment instanceof EE_Payment) {
2215
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2216
-                /** @type EE_Transaction_Payments $transaction_payments */
2217
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2218
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2219
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2220
-                        $payment,
2221
-                        $REG_IDs,
2222
-                        $delete_txn_reg_status_change
2223
-                    );
2224
-                    if ($delete_txn_reg_status_change) {
2225
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2226
-                        // request data because that's how messages will be looking for it.
2227
-                        $this->request->setRequestParam('txn_reg_status_change', $delete_txn_reg_status_change);
2228
-                        $this->_maybe_send_notifications();
2229
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2230
-                    }
2231
-                }
2232
-            } else {
2233
-                EE_Error::add_error(
2234
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2235
-                    __FILE__,
2236
-                    __FUNCTION__,
2237
-                    __LINE__
2238
-                );
2239
-            }
2240
-        } elseif ($can_delete) {
2241
-            EE_Error::add_error(
2242
-                esc_html__(
2243
-                    'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2244
-                    'event_espresso'
2245
-                ),
2246
-                __FILE__,
2247
-                __FUNCTION__,
2248
-                __LINE__
2249
-            );
2250
-        } else {
2251
-            EE_Error::add_error(
2252
-                esc_html__(
2253
-                    'You do not have access to delete a payment.',
2254
-                    'event_espresso'
2255
-                ),
2256
-                __FILE__,
2257
-                __FUNCTION__,
2258
-                __LINE__
2259
-            );
2260
-        }
2261
-        $notices              = EE_Error::get_notices(false, false, false);
2262
-        $this->_template_args = [
2263
-            'data'      => $json_response_data,
2264
-            'success'   => $notices['success'],
2265
-            'error'     => $notices['errors'],
2266
-            'attention' => $notices['attention'],
2267
-        ];
2268
-        $this->_return_json();
2269
-    }
2270
-
2271
-
2272
-    /**
2273
-     * _registration_payment_data_array
2274
-     * adds info for 'owing' and 'paid' for each registration to the json response
2275
-     *
2276
-     * @access protected
2277
-     * @param array $REG_IDs
2278
-     * @return array
2279
-     * @throws EE_Error
2280
-     * @throws InvalidArgumentException
2281
-     * @throws InvalidDataTypeException
2282
-     * @throws InvalidInterfaceException
2283
-     * @throws ReflectionException
2284
-     */
2285
-    protected function _registration_payment_data_array($REG_IDs)
2286
-    {
2287
-        $registration_payment_data = [];
2288
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2289
-        if (! empty($REG_IDs)) {
2290
-            $registrations = EEM_Registration::instance()->get_all([['REG_ID' => ['IN', $REG_IDs]]]);
2291
-            foreach ($registrations as $registration) {
2292
-                if ($registration instanceof EE_Registration) {
2293
-                    $registration_payment_data[ $registration->ID() ] = [
2294
-                        'paid'  => $registration->pretty_paid(),
2295
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2296
-                    ];
2297
-                }
2298
-            }
2299
-        }
2300
-
2301
-        return $registration_payment_data;
2302
-    }
2303
-
2304
-
2305
-    /**
2306
-     * _maybe_send_notifications
2307
-     * determines whether or not the admin has indicated that notifications should be sent.
2308
-     * If so, will toggle a filter switch for delivering registration notices.
2309
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2310
-     *
2311
-     * @access protected
2312
-     * @param EE_Payment | null $payment
2313
-     */
2314
-    protected function _maybe_send_notifications($payment = null)
2315
-    {
2316
-        switch ($payment instanceof EE_Payment) {
2317
-            // payment notifications
2318
-            case true:
2319
-                if ($this->request->getRequestParam('txn_payments[send_notifications]', false, 'bool')) {
2320
-                    $this->_process_payment_notification($payment);
2321
-                }
2322
-                break;
2323
-            // registration notifications
2324
-            case false:
2325
-                if ($this->request->getRequestParam('txn_reg_status_change[send_notifications]', false, 'bool')) {
2326
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2327
-                }
2328
-                break;
2329
-        }
2330
-    }
2331
-
2332
-
2333
-    /**
2334
-     * _send_payment_reminder
2335
-     *    generates HTML for the View Transaction Details Admin page
2336
-     *
2337
-     * @access protected
2338
-     * @return void
2339
-     * @throws EE_Error
2340
-     * @throws InvalidArgumentException
2341
-     * @throws InvalidDataTypeException
2342
-     * @throws InvalidInterfaceException
2343
-     */
2344
-    protected function _send_payment_reminder()
2345
-    {
2346
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2347
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2348
-        $redirect_to = $this->request->getRequestParam('redirect_to');
2349
-        $query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2350
-        do_action(
2351
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2352
-            $transaction
2353
-        );
2354
-        $this->_redirect_after_action(
2355
-            false,
2356
-            esc_html__('payment reminder', 'event_espresso'),
2357
-            esc_html__('sent', 'event_espresso'),
2358
-            $query_args,
2359
-            true
2360
-        );
2361
-    }
2362
-
2363
-
2364
-    /**
2365
-     *  get_transactions
2366
-     *    get transactions for given parameters (used by list table)
2367
-     *
2368
-     * @param int     $per_page how many transactions displayed per page
2369
-     * @param boolean $count   return the count or objects
2370
-     * @param string  $view
2371
-     * @return EE_Transaction[]|int int = count || array of transaction objects
2372
-     * @throws EE_Error
2373
-     * @throws InvalidArgumentException
2374
-     * @throws InvalidDataTypeException
2375
-     * @throws InvalidInterfaceException
2376
-     */
2377
-    public function get_transactions($per_page, $count = false, $view = '')
2378
-    {
2379
-        $start_date = wp_strip_all_tags(
2380
-            $this->request->getRequestParam('txn-filter-start-date', date('m/d/Y', strtotime('-10 year')))
2381
-        );
2382
-        $end_date = wp_strip_all_tags(
2383
-            $this->request->getRequestParam('txn-filter-end-date', date('m/d/Y'))
2384
-        );
2385
-
2386
-        // make sure our timestamps start and end right at the boundaries for each day
2387
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2388
-        $end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2389
-
2390
-
2391
-        // convert to timestamps
2392
-        $start_date = strtotime($start_date);
2393
-        $end_date   = strtotime($end_date);
2394
-
2395
-        // makes sure start date is the lowest value and vice versa
2396
-        $start_date = min($start_date, $end_date);
2397
-        $end_date   = max($start_date, $end_date);
2398
-
2399
-        // convert to correct format for query
2400
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2401
-            'TXN_timestamp',
2402
-            date('Y-m-d H:i:s', $start_date),
2403
-            'Y-m-d H:i:s'
2404
-        );
2405
-        $end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2406
-            'TXN_timestamp',
2407
-            date('Y-m-d H:i:s', $end_date),
2408
-            'Y-m-d H:i:s'
2409
-        );
2410
-
2411
-
2412
-        // set orderby
2413
-        $orderby = $this->request->getRequestParam('orderby');
2414
-
2415
-        switch ($orderby) {
2416
-            case 'TXN_ID':
2417
-                break;
2418
-            case 'ATT_fname':
2419
-                $orderby = 'Registration.Attendee.ATT_fname';
2420
-                break;
2421
-            case 'event_name':
2422
-                $orderby = 'Registration.Event.EVT_name';
2423
-                break;
2424
-            default: // 'TXN_timestamp'
2425
-                $orderby = 'TXN_timestamp';
2426
-        }
2427
-
2428
-        $sort         = $this->request->getRequestParam('order', 'DESC');
2429
-        $current_page = $this->request->getRequestParam('paged', 1, 'int');
2430
-
2431
-        $per_page = absint($per_page) ? $per_page : 10;
2432
-        $per_page = $this->request->getRequestParam('perpage', $per_page, 'int');
2433
-
2434
-        $offset = ($current_page - 1) * $per_page;
2435
-        $limit  = [$offset, $per_page];
2436
-
2437
-        $_where = [
2438
-            'TXN_timestamp'          => ['BETWEEN', [$start_date, $end_date]],
2439
-            'Registration.REG_count' => 1,
2440
-        ];
2441
-
2442
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2443
-        if ($EVT_ID) {
2444
-            $_where['Registration.EVT_ID'] = $EVT_ID;
2445
-        }
2446
-
2447
-        $search_term = $this->request->getRequestParam('s');
2448
-        if ($search_term) {
2449
-            $search_term = '%' . $search_term . '%';
2450
-            $_where['OR']  = [
2451
-                'Registration.Event.EVT_name'         => ['LIKE', $search_term],
2452
-                'Registration.Event.EVT_desc'         => ['LIKE', $search_term],
2453
-                'Registration.Event.EVT_short_desc'   => ['LIKE', $search_term],
2454
-                'Registration.Attendee.ATT_full_name' => ['LIKE', $search_term],
2455
-                'Registration.Attendee.ATT_fname'     => ['LIKE', $search_term],
2456
-                'Registration.Attendee.ATT_lname'     => ['LIKE', $search_term],
2457
-                'Registration.Attendee.ATT_short_bio' => ['LIKE', $search_term],
2458
-                'Registration.Attendee.ATT_email'     => ['LIKE', $search_term],
2459
-                'Registration.Attendee.ATT_address'   => ['LIKE', $search_term],
2460
-                'Registration.Attendee.ATT_address2'  => ['LIKE', $search_term],
2461
-                'Registration.Attendee.ATT_city'      => ['LIKE', $search_term],
2462
-                'Registration.REG_final_price'        => ['LIKE', $search_term],
2463
-                'Registration.REG_code'               => ['LIKE', $search_term],
2464
-                'Registration.REG_count'              => ['LIKE', $search_term],
2465
-                'Registration.REG_group_size'         => ['LIKE', $search_term],
2466
-                'Registration.Ticket.TKT_name'        => ['LIKE', $search_term],
2467
-                'Registration.Ticket.TKT_description' => ['LIKE', $search_term],
2468
-                'Payment.PAY_source'                  => ['LIKE', $search_term],
2469
-                'Payment.Payment_Method.PMD_name'     => ['LIKE', $search_term],
2470
-                'TXN_session_data'                    => ['LIKE', $search_term],
2471
-                'Payment.PAY_txn_id_chq_nmbr'         => ['LIKE', $search_term],
2472
-            ];
2473
-        }
2474
-
2475
-        $status = $this->request->getRequestParam('status');
2476
-        // failed transactions
2477
-        $failed     = (! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2478
-        $abandoned  = (! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2479
-        $incomplete = (! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2480
-
2481
-        if ($failed) {
2482
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2483
-        } elseif ($abandoned) {
2484
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2485
-        } elseif ($incomplete) {
2486
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2487
-        } else {
2488
-            $_where['STS_ID']  = ['!=', EEM_Transaction::failed_status_code];
2489
-            $_where['STS_ID*'] = ['!=', EEM_Transaction::abandoned_status_code];
2490
-        }
2491
-
2492
-        $query_params = apply_filters(
2493
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2494
-            [
2495
-                $_where,
2496
-                'order_by'                 => [$orderby => $sort],
2497
-                'limit'                    => $limit,
2498
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2499
-            ],
2500
-            $this->request->requestParams(),
2501
-            $view,
2502
-            $count
2503
-        );
2504
-
2505
-        return $count
2506
-            ? EEM_Transaction::instance()->count([$query_params[0]], 'TXN_ID', true)
2507
-            : EEM_Transaction::instance()->get_all($query_params);
2508
-    }
2509
-
2510
-
2511
-    /**
2512
-     * @throws EE_Error
2513
-     * @throws InvalidArgumentException
2514
-     * @throws InvalidDataTypeException
2515
-     * @throws InvalidInterfaceException
2516
-     * @throws ReflectionException
2517
-     * @throws RuntimeException
2518
-     * @since 4.9.79.p
2519
-     */
2520
-    public function recalculateLineItems()
2521
-    {
2522
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2523
-        /** @var EE_Transaction $transaction */
2524
-        $transaction     = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2525
-        $success         = $transaction->recalculateLineItems();
2526
-        $redirect_to = $this->request->getRequestParam('redirect_to');
2527
-        $query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2528
-        $this->_redirect_after_action(
2529
-            $success,
2530
-            esc_html__('Transaction taxes and totals', 'event_espresso'),
2531
-            esc_html__('recalculated', 'event_espresso'),
2532
-            $query_args,
2533
-            true
2534
-        );
2535
-    }
15
+	/**
16
+	 * @var EE_Transaction
17
+	 */
18
+	private $_transaction;
19
+
20
+	/**
21
+	 * @var EE_Session
22
+	 */
23
+	private $_session;
24
+
25
+	/**
26
+	 * @var array $_txn_status
27
+	 */
28
+	private static $_txn_status;
29
+
30
+	/**
31
+	 * @var array $_pay_status
32
+	 */
33
+	private static $_pay_status;
34
+
35
+	/**
36
+	 * @var array $_existing_reg_payment_REG_IDs
37
+	 */
38
+	protected $_existing_reg_payment_REG_IDs;
39
+
40
+
41
+	/**
42
+	 *    _init_page_props
43
+	 *
44
+	 * @return void
45
+	 */
46
+	protected function _init_page_props()
47
+	{
48
+		$this->page_slug        = TXN_PG_SLUG;
49
+		$this->page_label       = esc_html__('Transactions', 'event_espresso');
50
+		$this->_admin_base_url  = TXN_ADMIN_URL;
51
+		$this->_admin_base_path = TXN_ADMIN;
52
+	}
53
+
54
+
55
+	/**
56
+	 *    _ajax_hooks
57
+	 *
58
+	 * @return void
59
+	 */
60
+	protected function _ajax_hooks()
61
+	{
62
+		add_action('wp_ajax_espresso_apply_payment', [$this, 'apply_payments_or_refunds']);
63
+		add_action('wp_ajax_espresso_apply_refund', [$this, 'apply_payments_or_refunds']);
64
+		add_action('wp_ajax_espresso_delete_payment', [$this, 'delete_payment']);
65
+	}
66
+
67
+
68
+	/**
69
+	 *    _define_page_props
70
+	 *
71
+	 * @return void
72
+	 */
73
+	protected function _define_page_props()
74
+	{
75
+		$this->_admin_page_title = $this->page_label;
76
+		$this->_labels           = [
77
+			'buttons' => [
78
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
79
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
80
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
81
+			],
82
+		];
83
+	}
84
+
85
+
86
+	/**
87
+	 *        grab url requests and route them
88
+	 *
89
+	 * @access private
90
+	 * @return void
91
+	 * @throws EE_Error
92
+	 * @throws InvalidArgumentException
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InvalidInterfaceException
95
+	 */
96
+	public function _set_page_routes()
97
+	{
98
+
99
+		$this->_set_transaction_status_array();
100
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
101
+
102
+		$this->_page_routes = [
103
+
104
+			'default' => [
105
+				'func'       => '_transactions_overview_list_table',
106
+				'capability' => 'ee_read_transactions',
107
+			],
108
+
109
+			'view_transaction' => [
110
+				'func'       => '_transaction_details',
111
+				'capability' => 'ee_read_transaction',
112
+				'obj_id'     => $TXN_ID,
113
+			],
114
+
115
+			'send_payment_reminder' => [
116
+				'func'       => '_send_payment_reminder',
117
+				'noheader'   => true,
118
+				'capability' => 'ee_send_message',
119
+			],
120
+
121
+			'espresso_apply_payment' => [
122
+				'func'       => 'apply_payments_or_refunds',
123
+				'noheader'   => true,
124
+				'capability' => 'ee_edit_payments',
125
+			],
126
+
127
+			'espresso_apply_refund' => [
128
+				'func'       => 'apply_payments_or_refunds',
129
+				'noheader'   => true,
130
+				'capability' => 'ee_edit_payments',
131
+			],
132
+
133
+			'espresso_delete_payment' => [
134
+				'func'       => 'delete_payment',
135
+				'noheader'   => true,
136
+				'capability' => 'ee_delete_payments',
137
+			],
138
+
139
+			'espresso_recalculate_line_items' => [
140
+				'func'       => 'recalculateLineItems',
141
+				'noheader'   => true,
142
+				'capability' => 'ee_edit_payments',
143
+			],
144
+
145
+		];
146
+	}
147
+
148
+
149
+	protected function _set_page_config()
150
+	{
151
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
152
+		$this->_page_config = [
153
+			'default'          => [
154
+				'nav'           => [
155
+					'label' => esc_html__('Overview', 'event_espresso'),
156
+					'order' => 10,
157
+				],
158
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
159
+				'help_tabs'     => [
160
+					'transactions_overview_help_tab'                       => [
161
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
162
+						'filename' => 'transactions_overview',
163
+					],
164
+					'transactions_overview_table_column_headings_help_tab' => [
165
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
166
+						'filename' => 'transactions_overview_table_column_headings',
167
+					],
168
+					'transactions_overview_views_filters_help_tab'         => [
169
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
170
+						'filename' => 'transactions_overview_views_filters_search',
171
+					],
172
+				],
173
+				/**
174
+				 * commented out because currently we are not displaying tips for transaction list table status but this
175
+				 * may change in a later iteration so want to keep the code for then.
176
+				 */
177
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
178
+				'require_nonce' => false,
179
+			],
180
+			'view_transaction' => [
181
+				'nav'       => [
182
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
183
+					'order'      => 5,
184
+					'url'        => $TXN_ID
185
+						? add_query_arg(['TXN_ID' => $TXN_ID], $this->_current_page_view_url)
186
+						: $this->_admin_base_url,
187
+					'persistent' => false,
188
+				],
189
+				'help_tabs' => [
190
+					'transactions_view_transaction_help_tab'                                              => [
191
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
192
+						'filename' => 'transactions_view_transaction',
193
+					],
194
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => [
195
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
196
+						'filename' => 'transactions_view_transaction_transaction_details_table',
197
+					],
198
+					'transactions_view_transaction_attendees_registered_help_tab'                         => [
199
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
200
+						'filename' => 'transactions_view_transaction_attendees_registered',
201
+					],
202
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => [
203
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
204
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
205
+					],
206
+				],
207
+				'qtips'     => ['Transaction_Details_Tips'],
208
+				'metaboxes' => ['_transaction_details_metaboxes'],
209
+
210
+				'require_nonce' => false,
211
+			],
212
+		];
213
+	}
214
+
215
+
216
+	/**
217
+	 * The below methods aren't used by this class currently
218
+	 */
219
+	protected function _add_screen_options()
220
+	{
221
+		// noop
222
+	}
223
+
224
+
225
+	protected function _add_feature_pointers()
226
+	{
227
+		// noop
228
+	}
229
+
230
+
231
+	public function admin_init()
232
+	{
233
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
234
+		$event_name = $this->request->getRequestParam('event_name');
235
+		$redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
236
+		// IF a registration was JUST added via the admin...
237
+		if ($EVT_ID && $event_name && $redirect_from) {
238
+			// then set a cookie so that we can block any attempts to use
239
+			// the back button as a way to enter another registration.
240
+			setcookie('ee_registration_added', $EVT_ID, time() + WEEK_IN_SECONDS, '/');
241
+			// and update the global
242
+			$_COOKIE['ee_registration_added'] = $EVT_ID;
243
+		}
244
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
245
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
246
+			'event_espresso'
247
+		);
248
+		EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
249
+			'An error occurred! Please refresh the page and try again.',
250
+			'event_espresso'
251
+		);
252
+		EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
253
+		EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
254
+		EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
255
+		EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__(
256
+			'This transaction has been overpaid ! Payments Total',
257
+			'event_espresso'
258
+		);
259
+	}
260
+
261
+
262
+	public function admin_notices()
263
+	{
264
+		// noop
265
+	}
266
+
267
+
268
+	public function admin_footer_scripts()
269
+	{
270
+		// noop
271
+	}
272
+
273
+
274
+	/**
275
+	 * _set_transaction_status_array
276
+	 * sets list of transaction statuses
277
+	 *
278
+	 * @access private
279
+	 * @return void
280
+	 * @throws EE_Error
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws InvalidInterfaceException
284
+	 */
285
+	private function _set_transaction_status_array()
286
+	{
287
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
288
+	}
289
+
290
+
291
+	/**
292
+	 * get_transaction_status_array
293
+	 * return the transaction status array for wp_list_table
294
+	 *
295
+	 * @access public
296
+	 * @return array
297
+	 */
298
+	public function get_transaction_status_array()
299
+	{
300
+		return self::$_txn_status;
301
+	}
302
+
303
+
304
+	/**
305
+	 *    get list of payment statuses
306
+	 *
307
+	 * @access private
308
+	 * @return void
309
+	 * @throws EE_Error
310
+	 * @throws InvalidArgumentException
311
+	 * @throws InvalidDataTypeException
312
+	 * @throws InvalidInterfaceException
313
+	 */
314
+	private function _get_payment_status_array()
315
+	{
316
+		self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
317
+		$this->_template_args['payment_status'] = self::$_pay_status;
318
+	}
319
+
320
+
321
+	/**
322
+	 *    _add_screen_options_default
323
+	 *
324
+	 * @access protected
325
+	 * @return void
326
+	 * @throws InvalidArgumentException
327
+	 * @throws InvalidDataTypeException
328
+	 * @throws InvalidInterfaceException
329
+	 */
330
+	protected function _add_screen_options_default()
331
+	{
332
+		$this->_per_page_screen_option();
333
+	}
334
+
335
+
336
+	/**
337
+	 * load_scripts_styles
338
+	 *
339
+	 * @access public
340
+	 * @return void
341
+	 */
342
+	public function load_scripts_styles()
343
+	{
344
+		// enqueue style
345
+		wp_register_style(
346
+			'espresso_txn',
347
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
348
+			[],
349
+			EVENT_ESPRESSO_VERSION
350
+		);
351
+		wp_enqueue_style('espresso_txn');
352
+		// scripts
353
+		wp_register_script(
354
+			'espresso_txn',
355
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
356
+			[
357
+				'ee_admin_js',
358
+				'ee-datepicker',
359
+				'jquery-ui-datepicker',
360
+				'jquery-ui-draggable',
361
+				'ee-dialog',
362
+				'ee-accounting',
363
+				'ee-serialize-full-array',
364
+			],
365
+			EVENT_ESPRESSO_VERSION,
366
+			true
367
+		);
368
+		wp_enqueue_script('espresso_txn');
369
+	}
370
+
371
+
372
+	/**
373
+	 *    load_scripts_styles_view_transaction
374
+	 *
375
+	 * @access public
376
+	 * @return void
377
+	 */
378
+	public function load_scripts_styles_view_transaction()
379
+	{
380
+		// styles
381
+		wp_enqueue_style('espresso-ui-theme');
382
+	}
383
+
384
+
385
+	/**
386
+	 *    load_scripts_styles_default
387
+	 *
388
+	 * @access public
389
+	 * @return void
390
+	 */
391
+	public function load_scripts_styles_default()
392
+	{
393
+		// styles
394
+		wp_enqueue_style('espresso-ui-theme');
395
+	}
396
+
397
+
398
+	/**
399
+	 *    _set_list_table_views_default
400
+	 *
401
+	 * @access protected
402
+	 * @return void
403
+	 */
404
+	protected function _set_list_table_views_default()
405
+	{
406
+		$this->_views = [
407
+			'all'        => [
408
+				'slug'  => 'all',
409
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
410
+				'count' => 0,
411
+			],
412
+			'abandoned'  => [
413
+				'slug'  => 'abandoned',
414
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
415
+				'count' => 0,
416
+			],
417
+			'incomplete' => [
418
+				'slug'  => 'incomplete',
419
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
420
+				'count' => 0,
421
+			],
422
+		];
423
+		if (
424
+			/**
425
+			 * Filters whether a link to the "Failed Transactions" list table
426
+			 * appears on the Transactions Admin Page list table.
427
+			 * List display can be turned back on via the following:
428
+			 * add_filter(
429
+			 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
430
+			 *     '__return_true'
431
+			 * );
432
+			 *
433
+			 * @param boolean                 $display_failed_txns_list
434
+			 * @param Transactions_Admin_Page $this
435
+			 * @since 4.9.70.p
436
+			 */
437
+			apply_filters(
438
+				'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
439
+				false,
440
+				$this
441
+			)
442
+		) {
443
+			$this->_views['failed'] = [
444
+				'slug'  => 'failed',
445
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
446
+				'count' => 0,
447
+			];
448
+		}
449
+	}
450
+
451
+
452
+	/**
453
+	 * _set_transaction_object
454
+	 * This sets the _transaction property for the transaction details screen
455
+	 *
456
+	 * @access private
457
+	 * @return void
458
+	 * @throws EE_Error
459
+	 * @throws InvalidArgumentException
460
+	 * @throws RuntimeException
461
+	 * @throws InvalidDataTypeException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws ReflectionException
464
+	 */
465
+	private function _set_transaction_object()
466
+	{
467
+		if ($this->_transaction instanceof EE_Transaction) {
468
+			return;
469
+		} //get out we've already set the object
470
+
471
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
472
+
473
+		// get transaction object
474
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
475
+		$this->_session     = $this->_transaction instanceof EE_Transaction
476
+			? $this->_transaction->session_data()
477
+			: null;
478
+		if ($this->_transaction instanceof EE_Transaction) {
479
+			$this->_transaction->verify_abandoned_transaction_status();
480
+		}
481
+
482
+		if (! $this->_transaction instanceof EE_Transaction) {
483
+			$error_msg = sprintf(
484
+				esc_html__(
485
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
486
+					'event_espresso'
487
+				),
488
+				$TXN_ID
489
+			);
490
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
491
+		}
492
+	}
493
+
494
+
495
+	/**
496
+	 *    _transaction_legend_items
497
+	 *
498
+	 * @access protected
499
+	 * @return array
500
+	 * @throws EE_Error
501
+	 * @throws InvalidArgumentException
502
+	 * @throws ReflectionException
503
+	 * @throws InvalidDataTypeException
504
+	 * @throws InvalidInterfaceException
505
+	 */
506
+	protected function _transaction_legend_items()
507
+	{
508
+		EE_Registry::instance()->load_helper('MSG_Template');
509
+		$items = [];
510
+
511
+		if (
512
+			EE_Registry::instance()->CAP->current_user_can(
513
+				'ee_read_global_messages',
514
+				'view_filtered_messages'
515
+			)
516
+		) {
517
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
518
+			if (
519
+				is_array($related_for_icon)
520
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
521
+			) {
522
+				$items['view_related_messages'] = [
523
+					'class' => $related_for_icon['css_class'],
524
+					'desc'  => $related_for_icon['label'],
525
+				];
526
+			}
527
+		}
528
+
529
+		$items = apply_filters(
530
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
531
+			array_merge(
532
+				$items,
533
+				[
534
+					'view_details'          => [
535
+						'class' => 'dashicons dashicons-cart',
536
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
537
+					],
538
+					'view_invoice'          => [
539
+						'class' => 'dashicons dashicons-media-spreadsheet',
540
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
541
+					],
542
+					'view_receipt'          => [
543
+						'class' => 'dashicons dashicons-media-default',
544
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
545
+					],
546
+					'view_registration'     => [
547
+						'class' => 'dashicons dashicons-clipboard',
548
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
549
+					],
550
+					'payment_overview_link' => [
551
+						'class' => 'dashicons dashicons-money',
552
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
553
+					],
554
+				]
555
+			)
556
+		);
557
+
558
+		if (
559
+			EEH_MSG_Template::is_mt_active('payment_reminder')
560
+			&& EE_Registry::instance()->CAP->current_user_can(
561
+				'ee_send_message',
562
+				'espresso_transactions_send_payment_reminder'
563
+			)
564
+		) {
565
+			$items['send_payment_reminder'] = [
566
+				'class' => 'dashicons dashicons-email-alt',
567
+				'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
568
+			];
569
+		} else {
570
+			$items['blank*'] = [
571
+				'class' => '',
572
+				'desc'  => '',
573
+			];
574
+		}
575
+		$more_items = apply_filters(
576
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
577
+			[
578
+				'overpaid'   => [
579
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
580
+					'desc'  => EEH_Template::pretty_status(
581
+						EEM_Transaction::overpaid_status_code,
582
+						false,
583
+						'sentence'
584
+					),
585
+				],
586
+				'complete'   => [
587
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
588
+					'desc'  => EEH_Template::pretty_status(
589
+						EEM_Transaction::complete_status_code,
590
+						false,
591
+						'sentence'
592
+					),
593
+				],
594
+				'incomplete' => [
595
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
596
+					'desc'  => EEH_Template::pretty_status(
597
+						EEM_Transaction::incomplete_status_code,
598
+						false,
599
+						'sentence'
600
+					),
601
+				],
602
+				'abandoned'  => [
603
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
604
+					'desc'  => EEH_Template::pretty_status(
605
+						EEM_Transaction::abandoned_status_code,
606
+						false,
607
+						'sentence'
608
+					),
609
+				],
610
+				'failed'     => [
611
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
612
+					'desc'  => EEH_Template::pretty_status(
613
+						EEM_Transaction::failed_status_code,
614
+						false,
615
+						'sentence'
616
+					),
617
+				],
618
+			]
619
+		);
620
+
621
+		return array_merge($items, $more_items);
622
+	}
623
+
624
+
625
+	/**
626
+	 *    _transactions_overview_list_table
627
+	 *
628
+	 * @access protected
629
+	 * @return void
630
+	 * @throws DomainException
631
+	 * @throws EE_Error
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidDataTypeException
634
+	 * @throws InvalidInterfaceException
635
+	 * @throws ReflectionException
636
+	 */
637
+	protected function _transactions_overview_list_table()
638
+	{
639
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
640
+
641
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
642
+		$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
643
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
644
+			? sprintf(
645
+				esc_html__('%sViewing Transactions for the Event: %s%s', 'event_espresso'),
646
+				'<h3>',
647
+				'<a href="'
648
+				. EE_Admin_Page::add_query_args_and_nonce(
649
+					['action' => 'edit', 'post' => $event->ID()],
650
+					EVENTS_ADMIN_URL
651
+				)
652
+				. '" aria-label="'
653
+				. esc_attr__('Click to Edit event', 'event_espresso')
654
+				. '">' . $event->name() . '</a>',
655
+				'</h3>'
656
+			)
657
+			: '';
658
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
659
+		$this->display_admin_list_table_page_with_no_sidebar();
660
+	}
661
+
662
+
663
+	/**
664
+	 *    _transaction_details
665
+	 * generates HTML for the View Transaction Details Admin page
666
+	 *
667
+	 * @access protected
668
+	 * @return void
669
+	 * @throws DomainException
670
+	 * @throws EE_Error
671
+	 * @throws InvalidArgumentException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws InvalidInterfaceException
674
+	 * @throws RuntimeException
675
+	 * @throws ReflectionException
676
+	 */
677
+	protected function _transaction_details()
678
+	{
679
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
680
+
681
+		$this->_set_transaction_status_array();
682
+
683
+		$this->_template_args                      = [];
684
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
685
+
686
+		$this->_set_transaction_object();
687
+
688
+		if (! $this->_transaction instanceof EE_Transaction) {
689
+			return;
690
+		}
691
+
692
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
693
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
694
+
695
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
696
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
697
+
698
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
699
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
700
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
701
+
702
+		$this->_template_args['grand_total'] = $this->_transaction->total();
703
+		$this->_template_args['total_paid']  = $this->_transaction->paid();
704
+
705
+		$amount_due                         = $this->_transaction->total() - $this->_transaction->paid();
706
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
707
+			$amount_due,
708
+			true
709
+		);
710
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
711
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
712
+												  . $this->_template_args['amount_due'];
713
+		} else {
714
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
715
+		}
716
+		$this->_template_args['amount_due_class'] = '';
717
+
718
+		if ($this->_transaction->paid() === $this->_transaction->total()) {
719
+			// paid in full
720
+			$this->_template_args['amount_due'] = false;
721
+		} elseif ($this->_transaction->paid() > $this->_transaction->total()) {
722
+			// overpaid
723
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
724
+		} elseif ($this->_transaction->total() > (float) 0) {
725
+			if ($this->_transaction->paid() > (float) 0) {
726
+				// monies owing
727
+				$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
728
+			} elseif ($this->_transaction->paid() === (float) 0) {
729
+				// no payments made yet
730
+				$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
731
+			}
732
+		} elseif ($this->_transaction->total() === (float) 0) {
733
+			// free event
734
+			$this->_template_args['amount_due'] = false;
735
+		}
736
+
737
+		$payment_method = $this->_transaction->payment_method();
738
+
739
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
740
+			? $payment_method->admin_name()
741
+			: esc_html__('Unknown', 'event_espresso');
742
+
743
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
744
+		// link back to overview
745
+		$this->_template_args['txn_overview_url'] = $this->request->getServerParam(
746
+			'HTTP_REFERER',
747
+			TXN_ADMIN_URL
748
+		);
749
+
750
+
751
+		// next link
752
+		$next_txn                                 = $this->_transaction->next(
753
+			null,
754
+			[['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
755
+			'TXN_ID'
756
+		);
757
+		$this->_template_args['next_transaction'] = $next_txn
758
+			? $this->_next_link(
759
+				EE_Admin_Page::add_query_args_and_nonce(
760
+					['action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']],
761
+					TXN_ADMIN_URL
762
+				),
763
+				'dashicons dashicons-arrow-right ee-icon-size-22'
764
+			)
765
+			: '';
766
+		// previous link
767
+		$previous_txn                                 = $this->_transaction->previous(
768
+			null,
769
+			[['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
770
+			'TXN_ID'
771
+		);
772
+		$this->_template_args['previous_transaction'] = $previous_txn
773
+			? $this->_previous_link(
774
+				EE_Admin_Page::add_query_args_and_nonce(
775
+					['action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']],
776
+					TXN_ADMIN_URL
777
+				),
778
+				'dashicons dashicons-arrow-left ee-icon-size-22'
779
+			)
780
+			: '';
781
+
782
+		$EVT_ID        = $this->request->getRequestParam('EVT_ID', 0, 'int');
783
+		$event_name    = $this->request->getRequestParam('event_name');
784
+		$redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
785
+
786
+		// were we just redirected here after adding a new registration ???
787
+		if ($EVT_ID && $event_name && $redirect_from) {
788
+			if (
789
+				EE_Registry::instance()->CAP->current_user_can(
790
+					'ee_edit_registrations',
791
+					'espresso_registrations_new_registration',
792
+					$EVT_ID
793
+				)
794
+			) {
795
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
796
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
797
+					[
798
+						'page'     => 'espresso_registrations',
799
+						'action'   => 'new_registration',
800
+						'return'   => 'default',
801
+						'TXN_ID'   => $this->_transaction->ID(),
802
+						'event_id' => $EVT_ID,
803
+					],
804
+					REG_ADMIN_URL
805
+				);
806
+				$this->_admin_page_title .= '">';
807
+
808
+				$this->_admin_page_title .= sprintf(
809
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
810
+					htmlentities(urldecode($event_name), ENT_QUOTES, 'UTF-8')
811
+				);
812
+				$this->_admin_page_title .= '</a>';
813
+			}
814
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
815
+		}
816
+		// grab messages at the last second
817
+		$this->_template_args['notices'] = EE_Error::get_notices();
818
+		// path to template
819
+		$template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
820
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
821
+			$template_path,
822
+			$this->_template_args,
823
+			true
824
+		);
825
+
826
+		// the details template wrapper
827
+		$this->display_admin_page_with_sidebar();
828
+	}
829
+
830
+
831
+	/**
832
+	 *        _transaction_details_metaboxes
833
+	 *
834
+	 * @access protected
835
+	 * @return void
836
+	 * @throws EE_Error
837
+	 * @throws InvalidArgumentException
838
+	 * @throws InvalidDataTypeException
839
+	 * @throws InvalidInterfaceException
840
+	 * @throws RuntimeException
841
+	 * @throws ReflectionException
842
+	 */
843
+	protected function _transaction_details_metaboxes()
844
+	{
845
+
846
+		$this->_set_transaction_object();
847
+
848
+		if (! $this->_transaction instanceof EE_Transaction) {
849
+			return;
850
+		}
851
+		add_meta_box(
852
+			'edit-txn-details-mbox',
853
+			esc_html__('Transaction Details', 'event_espresso'),
854
+			[$this, 'txn_details_meta_box'],
855
+			$this->_wp_page_slug,
856
+			'normal',
857
+			'high'
858
+		);
859
+		add_meta_box(
860
+			'edit-txn-attendees-mbox',
861
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
862
+			[$this, 'txn_attendees_meta_box'],
863
+			$this->_wp_page_slug,
864
+			'normal',
865
+			'high',
866
+			['TXN_ID' => $this->_transaction->ID()]
867
+		);
868
+		add_meta_box(
869
+			'edit-txn-registrant-mbox',
870
+			esc_html__('Primary Contact', 'event_espresso'),
871
+			[$this, 'txn_registrant_side_meta_box'],
872
+			$this->_wp_page_slug,
873
+			'side',
874
+			'high'
875
+		);
876
+		add_meta_box(
877
+			'edit-txn-billing-info-mbox',
878
+			esc_html__('Billing Information', 'event_espresso'),
879
+			[$this, 'txn_billing_info_side_meta_box'],
880
+			$this->_wp_page_slug,
881
+			'side',
882
+			'high'
883
+		);
884
+	}
885
+
886
+
887
+	/**
888
+	 * Callback for transaction actions metabox.
889
+	 *
890
+	 * @param EE_Transaction|null $transaction
891
+	 * @return string
892
+	 * @throws DomainException
893
+	 * @throws EE_Error
894
+	 * @throws InvalidArgumentException
895
+	 * @throws InvalidDataTypeException
896
+	 * @throws InvalidInterfaceException
897
+	 * @throws ReflectionException
898
+	 * @throws RuntimeException
899
+	 */
900
+	public function getActionButtons(EE_Transaction $transaction = null)
901
+	{
902
+		$content = '';
903
+		$actions = [];
904
+		if (! $transaction instanceof EE_Transaction) {
905
+			return $content;
906
+		}
907
+		/** @var EE_Registration $primary_registration */
908
+		$primary_registration = $transaction->primary_registration();
909
+		$attendee             = $primary_registration instanceof EE_Registration
910
+			? $primary_registration->attendee()
911
+			: null;
912
+
913
+		if (
914
+			$attendee instanceof EE_Attendee
915
+			&& EE_Registry::instance()->CAP->current_user_can(
916
+				'ee_send_message',
917
+				'espresso_transactions_send_payment_reminder'
918
+			)
919
+		) {
920
+			$actions['payment_reminder'] =
921
+				EEH_MSG_Template::is_mt_active('payment_reminder')
922
+				&& $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
923
+				&& $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
924
+					? EEH_Template::get_button_or_link(
925
+						EE_Admin_Page::add_query_args_and_nonce(
926
+							[
927
+							'action'      => 'send_payment_reminder',
928
+							'TXN_ID'      => $this->_transaction->ID(),
929
+							'redirect_to' => 'view_transaction',
930
+							],
931
+							TXN_ADMIN_URL
932
+						),
933
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
934
+						'button secondary-button',
935
+						'dashicons dashicons-email-alt'
936
+					)
937
+					: '';
938
+		}
939
+
940
+		if (
941
+			EE_Registry::instance()->CAP->current_user_can(
942
+				'ee_edit_payments',
943
+				'espresso_transactions_recalculate_line_items'
944
+			)
945
+		) {
946
+			$actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
947
+				EE_Admin_Page::add_query_args_and_nonce(
948
+					[
949
+						'action'      => 'espresso_recalculate_line_items',
950
+						'TXN_ID'      => $this->_transaction->ID(),
951
+						'redirect_to' => 'view_transaction',
952
+					],
953
+					TXN_ADMIN_URL
954
+				),
955
+				esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
956
+				'button secondary-button',
957
+				'dashicons dashicons-update'
958
+			);
959
+		}
960
+
961
+		if (
962
+			$primary_registration instanceof EE_Registration
963
+			&& EEH_MSG_Template::is_mt_active('receipt')
964
+		) {
965
+			$actions['receipt'] = EEH_Template::get_button_or_link(
966
+				$primary_registration->receipt_url(),
967
+				esc_html__('View Receipt', 'event_espresso'),
968
+				'button secondary-button',
969
+				'dashicons dashicons-media-default'
970
+			);
971
+		}
972
+
973
+		if (
974
+			$primary_registration instanceof EE_Registration
975
+			&& EEH_MSG_Template::is_mt_active('invoice')
976
+		) {
977
+			$actions['invoice'] = EEH_Template::get_button_or_link(
978
+				$primary_registration->invoice_url(),
979
+				esc_html__('View Invoice', 'event_espresso'),
980
+				'button secondary-button',
981
+				'dashicons dashicons-media-spreadsheet'
982
+			);
983
+		}
984
+		$actions = array_filter(
985
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
986
+		);
987
+		if ($actions) {
988
+			$content = '<ul>';
989
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
990
+			$content .= '</uL>';
991
+		}
992
+		return $content;
993
+	}
994
+
995
+
996
+	/**
997
+	 * txn_details_meta_box
998
+	 * generates HTML for the Transaction main meta box
999
+	 *
1000
+	 * @return void
1001
+	 * @throws DomainException
1002
+	 * @throws EE_Error
1003
+	 * @throws InvalidArgumentException
1004
+	 * @throws InvalidDataTypeException
1005
+	 * @throws InvalidInterfaceException
1006
+	 * @throws RuntimeException
1007
+	 * @throws ReflectionException
1008
+	 */
1009
+	public function txn_details_meta_box()
1010
+	{
1011
+		$this->_set_transaction_object();
1012
+		$this->_template_args['TXN_ID']              = $this->_transaction->ID();
1013
+		$this->_template_args['attendee']            =
1014
+			$this->_transaction->primary_registration() instanceof EE_Registration
1015
+				? $this->_transaction->primary_registration()->attendee()
1016
+				: null;
1017
+		$this->_template_args['can_edit_payments']   = EE_Registry::instance()->CAP->current_user_can(
1018
+			'ee_edit_payments',
1019
+			'apply_payment_or_refund_from_registration_details'
1020
+		);
1021
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
+			'ee_delete_payments',
1023
+			'delete_payment_from_registration_details'
1024
+		);
1025
+
1026
+		// get line table
1027
+		EEH_Autoloader::register_line_item_display_autoloaders();
1028
+		$Line_Item_Display                       = new EE_Line_Item_Display(
1029
+			'admin_table',
1030
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1031
+		);
1032
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1033
+			$this->_transaction->total_line_item()
1034
+		);
1035
+		$this->_template_args['REG_code']        =
1036
+			$this->_transaction->primary_registration() instanceof EE_Registration
1037
+				? $this->_transaction->primary_registration()->reg_code()
1038
+				: null;
1039
+		// process taxes
1040
+		$taxes                         = $this->_transaction->line_items([['LIN_type' => EEM_Line_Item::type_tax]]);
1041
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1042
+
1043
+		$this->_template_args['grand_total']     = EEH_Template::format_currency(
1044
+			$this->_transaction->total(),
1045
+			false,
1046
+			false
1047
+		);
1048
+		$this->_template_args['grand_raw_total'] = $this->_transaction->total();
1049
+		$this->_template_args['TXN_status']      = $this->_transaction->status_ID();
1050
+
1051
+		// process payment details
1052
+		$payments = $this->_transaction->payments();
1053
+		if (! empty($payments)) {
1054
+			$this->_template_args['payments']              = $payments;
1055
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1056
+		} else {
1057
+			$this->_template_args['payments']              = false;
1058
+			$this->_template_args['existing_reg_payments'] = [];
1059
+		}
1060
+
1061
+		$this->_template_args['edit_payment_url']   = add_query_arg(['action' => 'edit_payment'], TXN_ADMIN_URL);
1062
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1063
+			['action' => 'espresso_delete_payment'],
1064
+			TXN_ADMIN_URL
1065
+		);
1066
+
1067
+		if (isset($txn_details['invoice_number'])) {
1068
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1069
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1070
+				'Invoice Number',
1071
+				'event_espresso'
1072
+			);
1073
+		}
1074
+
1075
+		$this->_template_args['txn_details']['registration_session']['value'] =
1076
+			$this->_transaction->primary_registration() instanceof EE_Registration
1077
+				? $this->_transaction->primary_registration()->session_ID()
1078
+				: null;
1079
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1080
+			'Registration Session',
1081
+			'event_espresso'
1082
+		);
1083
+
1084
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1085
+			? $this->_session['ip_address']
1086
+			: '';
1087
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1088
+			'Transaction placed from IP',
1089
+			'event_espresso'
1090
+		);
1091
+
1092
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1093
+			? $this->_session['user_agent']
1094
+			: '';
1095
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1096
+			'Registrant User Agent',
1097
+			'event_espresso'
1098
+		);
1099
+
1100
+		$reg_steps = '<ul>';
1101
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1102
+			if ($reg_step_status === true) {
1103
+				$reg_steps .= '<li style="color:#70cc50">'
1104
+							  . sprintf(
1105
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1106
+								  ucwords(str_replace('_', ' ', $reg_step))
1107
+							  )
1108
+							  . '</li>';
1109
+			} elseif ($reg_step_status !== false && is_numeric($reg_step_status)) {
1110
+				$reg_steps .= '<li style="color:#2EA2CC">'
1111
+							  . sprintf(
1112
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1113
+								  ucwords(str_replace('_', ' ', $reg_step)),
1114
+								  date(
1115
+									  get_option('date_format') . ' ' . get_option('time_format'),
1116
+									  $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1117
+								  )
1118
+							  )
1119
+							  . '</li>';
1120
+			} else {
1121
+				$reg_steps .= '<li style="color:#E76700">'
1122
+							  . sprintf(
1123
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1124
+								  ucwords(str_replace('_', ' ', $reg_step))
1125
+							  )
1126
+							  . '</li>';
1127
+			}
1128
+		}
1129
+		$reg_steps                                                 .= '</ul>';
1130
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1131
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1132
+			'Registration Step Progress',
1133
+			'event_espresso'
1134
+		);
1135
+
1136
+
1137
+		$this->_get_registrations_to_apply_payment_to();
1138
+		$this->_get_payment_methods($payments);
1139
+		$this->_get_payment_status_array();
1140
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1141
+
1142
+		$this->_template_args['transaction_form_url']    = add_query_arg(
1143
+			[
1144
+				'action'  => 'edit_transaction',
1145
+				'process' => 'transaction',
1146
+			],
1147
+			TXN_ADMIN_URL
1148
+		);
1149
+		$this->_template_args['apply_payment_form_url']  = add_query_arg(
1150
+			[
1151
+				'page'   => 'espresso_transactions',
1152
+				'action' => 'espresso_apply_payment',
1153
+			],
1154
+			WP_AJAX_URL
1155
+		);
1156
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1157
+			[
1158
+				'page'   => 'espresso_transactions',
1159
+				'action' => 'espresso_delete_payment',
1160
+			],
1161
+			WP_AJAX_URL
1162
+		);
1163
+
1164
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1165
+
1166
+		// 'espresso_delete_payment_nonce'
1167
+
1168
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1169
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1170
+	}
1171
+
1172
+
1173
+	/**
1174
+	 * _get_registration_payment_IDs
1175
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1176
+	 *
1177
+	 * @access protected
1178
+	 * @param EE_Payment[] $payments
1179
+	 * @return array
1180
+	 * @throws EE_Error
1181
+	 * @throws InvalidArgumentException
1182
+	 * @throws InvalidDataTypeException
1183
+	 * @throws InvalidInterfaceException
1184
+	 * @throws ReflectionException
1185
+	 */
1186
+	protected function _get_registration_payment_IDs($payments = [])
1187
+	{
1188
+		$existing_reg_payments = [];
1189
+		// get all reg payments for these payments
1190
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1191
+			[
1192
+				[
1193
+					'PAY_ID' => [
1194
+						'IN',
1195
+						array_keys($payments),
1196
+					],
1197
+				],
1198
+			]
1199
+		);
1200
+		if (! empty($reg_payments)) {
1201
+			foreach ($payments as $payment) {
1202
+				if (! $payment instanceof EE_Payment) {
1203
+					continue;
1204
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1205
+					$existing_reg_payments[ $payment->ID() ] = [];
1206
+				}
1207
+				foreach ($reg_payments as $reg_payment) {
1208
+					if (
1209
+						$reg_payment instanceof EE_Registration_Payment
1210
+						&& $reg_payment->payment_ID() === $payment->ID()
1211
+					) {
1212
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1213
+					}
1214
+				}
1215
+			}
1216
+		}
1217
+
1218
+		return $existing_reg_payments;
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * _get_registrations_to_apply_payment_to
1224
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1225
+	 * which allows the admin to only apply the payment to the specific registrations
1226
+	 *
1227
+	 * @access protected
1228
+	 * @return void
1229
+	 * @throws EE_Error
1230
+	 * @throws InvalidArgumentException
1231
+	 * @throws InvalidDataTypeException
1232
+	 * @throws InvalidInterfaceException
1233
+	 * @throws ReflectionException
1234
+	 */
1235
+	protected function _get_registrations_to_apply_payment_to()
1236
+	{
1237
+		// we want any registration with an active status (ie: not deleted or cancelled)
1238
+		$query_params                      = [
1239
+			[
1240
+				'STS_ID' => [
1241
+					'IN',
1242
+					[
1243
+						EEM_Registration::status_id_approved,
1244
+						EEM_Registration::status_id_pending_payment,
1245
+						EEM_Registration::status_id_not_approved,
1246
+					],
1247
+				],
1248
+			],
1249
+		];
1250
+		$registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1251
+			'',
1252
+			'txn-admin-apply-payment-to-registrations-dv',
1253
+			'',
1254
+			'clear: both; margin: 1.5em 0 0; display: none;'
1255
+		);
1256
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1257
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1258
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1259
+			EEH_HTML::tr(
1260
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1261
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1262
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1263
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1264
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1265
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1266
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1267
+			)
1268
+		);
1269
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1270
+		// get registrations for TXN
1271
+		$registrations         = $this->_transaction->registrations($query_params);
1272
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1273
+		foreach ($registrations as $registration) {
1274
+			if ($registration instanceof EE_Registration) {
1275
+				$attendee_name                     = $registration->attendee() instanceof EE_Attendee
1276
+					? $registration->attendee()->full_name()
1277
+					: esc_html__('Unknown Attendee', 'event_espresso');
1278
+				$owing                             = $registration->final_price() - $registration->paid();
1279
+				$taxable                           = $registration->ticket()->taxable()
1280
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1281
+					: '';
1282
+				$checked                           = empty($existing_reg_payments)
1283
+													 || in_array($registration->ID(), $existing_reg_payments, true)
1284
+					? ' checked'
1285
+					: '';
1286
+				$disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1287
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
+					EEH_HTML::td($registration->ID()) .
1289
+					EEH_HTML::td($attendee_name) .
1290
+					EEH_HTML::td(
1291
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
+					) .
1293
+					EEH_HTML::td($registration->event_name()) .
1294
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
+					EEH_HTML::td(
1296
+						EEH_Template::format_currency($owing),
1297
+						'',
1298
+						'txn-admin-payment-owing-td jst-cntr'
1299
+					) .
1300
+					EEH_HTML::td(
1301
+						'<input type="checkbox" value="' . $registration->ID()
1302
+						. '" name="txn_admin_payment[registrations]"'
1303
+						. $checked . $disabled . '>',
1304
+						'',
1305
+						'jst-cntr'
1306
+					),
1307
+					'apply-payment-registration-row-' . $registration->ID()
1308
+				);
1309
+			}
1310
+		}
1311
+		$registrations_to_apply_payment_to                         .= EEH_HTML::tbodyx();
1312
+		$registrations_to_apply_payment_to                         .= EEH_HTML::tablex();
1313
+		$registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1314
+		$registrations_to_apply_payment_to                         .= EEH_HTML::p(
1315
+			esc_html__(
1316
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1317
+				'event_espresso'
1318
+			),
1319
+			'',
1320
+			'clear description'
1321
+		);
1322
+		$registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1323
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * _get_reg_status_selection
1329
+	 *
1330
+	 * @return void
1331
+	 * @throws EE_Error
1332
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1333
+	 *         instead of events.
1334
+	 * @access protected
1335
+	 */
1336
+	protected function _get_reg_status_selection()
1337
+	{
1338
+		// first get all possible statuses
1339
+		$statuses = EEM_Registration::reg_status_array([], true);
1340
+		// let's add a "don't change" option.
1341
+		$status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1342
+		$status_array                                        = array_merge($status_array, $statuses);
1343
+		$this->_template_args['status_change_select']        = EEH_Form_Fields::select_input(
1344
+			'txn_reg_status_change[reg_status]',
1345
+			$status_array,
1346
+			'NAN',
1347
+			'id="txn-admin-payment-reg-status-inp"',
1348
+			'txn-reg-status-change-reg-status'
1349
+		);
1350
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1351
+			'delete_txn_reg_status_change[reg_status]',
1352
+			$status_array,
1353
+			'NAN',
1354
+			'delete-txn-admin-payment-reg-status-inp',
1355
+			'delete-txn-reg-status-change-reg-status'
1356
+		);
1357
+	}
1358
+
1359
+
1360
+	/**
1361
+	 *    _get_payment_methods
1362
+	 * Gets all the payment methods available generally, or the ones that are already
1363
+	 * selected on these payments (in case their payment methods are no longer active).
1364
+	 * Has the side-effect of updating the template args' payment_methods item
1365
+	 *
1366
+	 * @access private
1367
+	 * @param EE_Payment[] to show on this page
1368
+	 * @return void
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	private function _get_payment_methods($payments = [])
1376
+	{
1377
+		$payment_methods_of_payments = [];
1378
+		foreach ($payments as $payment) {
1379
+			if ($payment instanceof EE_Payment) {
1380
+				$payment_methods_of_payments[] = $payment->ID();
1381
+			}
1382
+		}
1383
+		if ($payment_methods_of_payments) {
1384
+			$query_args = [
1385
+				[
1386
+					'OR*payment_method_for_payment' => [
1387
+						'PMD_ID'    => ['IN', $payment_methods_of_payments],
1388
+						'PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%'],
1389
+					],
1390
+				],
1391
+			];
1392
+		} else {
1393
+			$query_args = [['PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%']]];
1394
+		}
1395
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1396
+	}
1397
+
1398
+
1399
+	/**
1400
+	 * txn_attendees_meta_box
1401
+	 *    generates HTML for the Attendees Transaction main meta box
1402
+	 *
1403
+	 * @access public
1404
+	 * @param WP_Post $post
1405
+	 * @param array   $metabox
1406
+	 * @return void
1407
+	 * @throws DomainException
1408
+	 * @throws EE_Error
1409
+	 * @throws InvalidArgumentException
1410
+	 * @throws InvalidDataTypeException
1411
+	 * @throws InvalidInterfaceException
1412
+	 * @throws ReflectionException
1413
+	 */
1414
+	public function txn_attendees_meta_box($post, $metabox = ['args' => []])
1415
+	{
1416
+
1417
+		/** @noinspection NonSecureExtractUsageInspection */
1418
+		extract($metabox['args']);
1419
+		$this->_template_args['post']            = $post;
1420
+		$this->_template_args['event_attendees'] = [];
1421
+		// process items in cart
1422
+		$line_items = $this->_transaction->get_many_related(
1423
+			'Line_Item',
1424
+			[['LIN_type' => 'line-item']]
1425
+		);
1426
+		if (! empty($line_items)) {
1427
+			foreach ($line_items as $item) {
1428
+				if ($item instanceof EE_Line_Item) {
1429
+					switch ($item->OBJ_type()) {
1430
+						case 'Event':
1431
+							break;
1432
+						case 'Ticket':
1433
+							$ticket = $item->ticket();
1434
+							// right now we're only handling tickets here.
1435
+							// Cause its expected that only tickets will have attendees right?
1436
+							if (! $ticket instanceof EE_Ticket) {
1437
+								break;
1438
+							}
1439
+							try {
1440
+								$event_name = $ticket->get_event_name();
1441
+							} catch (Exception $e) {
1442
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1443
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1444
+							}
1445
+							$event_name   .= ' - ' . $item->name();
1446
+							$ticket_price = EEH_Template::format_currency($item->unit_price());
1447
+							// now get all of the registrations for this transaction that use this ticket
1448
+							$registrations = $ticket->registrations(
1449
+								[['TXN_ID' => $this->_transaction->ID()]]
1450
+							);
1451
+							foreach ($registrations as $registration) {
1452
+								if (! $registration instanceof EE_Registration) {
1453
+									break;
1454
+								}
1455
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1456
+									= $registration->status_ID();
1457
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1458
+									= $registration->count();
1459
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1460
+									= $event_name;
1461
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1462
+									= $ticket_price;
1463
+								// attendee info
1464
+								$attendee = $registration->get_first_related('Attendee');
1465
+								if ($attendee instanceof EE_Attendee) {
1466
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1467
+										= $attendee->ID();
1468
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1469
+										= $attendee->full_name();
1470
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1471
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1472
+										  . esc_html__(
1473
+											  ' Event',
1474
+											  'event_espresso'
1475
+										  )
1476
+										  . '">' . $attendee->email() . '</a>';
1477
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1478
+										= EEH_Address::format($attendee, 'inline', false, false);
1479
+								} else {
1480
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']   = '';
1481
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1482
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']    = '';
1483
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']  = '';
1484
+								}
1485
+							}
1486
+							break;
1487
+					}
1488
+				}
1489
+			}
1490
+
1491
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1492
+				[
1493
+					'action'  => 'edit_transaction',
1494
+					'process' => 'attendees',
1495
+				],
1496
+				TXN_ADMIN_URL
1497
+			);
1498
+			echo EEH_Template::display_template(
1499
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1500
+				$this->_template_args,
1501
+				true
1502
+			);
1503
+		} else {
1504
+			printf(
1505
+				esc_html__(
1506
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1507
+					'event_espresso'
1508
+				),
1509
+				'<p class="important-notice">',
1510
+				'</p>'
1511
+			);
1512
+		}
1513
+	}
1514
+
1515
+
1516
+	/**
1517
+	 * txn_registrant_side_meta_box
1518
+	 * generates HTML for the Edit Transaction side meta box
1519
+	 *
1520
+	 * @access public
1521
+	 * @return void
1522
+	 * @throws DomainException
1523
+	 * @throws EE_Error
1524
+	 * @throws InvalidArgumentException
1525
+	 * @throws InvalidDataTypeException
1526
+	 * @throws InvalidInterfaceException
1527
+	 * @throws ReflectionException
1528
+	 */
1529
+	public function txn_registrant_side_meta_box()
1530
+	{
1531
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1532
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1533
+			: null;
1534
+		if (! $primary_att instanceof EE_Attendee) {
1535
+			$this->_template_args['no_attendee_message'] = esc_html__(
1536
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1537
+				'event_espresso'
1538
+			);
1539
+			$primary_att                           = EEM_Attendee::instance()->create_default_object();
1540
+		}
1541
+		$this->_template_args['ATT_ID']            = $primary_att->ID();
1542
+		$this->_template_args['prime_reg_fname']   = $primary_att->fname();
1543
+		$this->_template_args['prime_reg_lname']   = $primary_att->lname();
1544
+		$this->_template_args['prime_reg_email']   = $primary_att->email();
1545
+		$this->_template_args['prime_reg_phone']   = $primary_att->phone();
1546
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1547
+			[
1548
+				'action' => 'edit_attendee',
1549
+				'post'   => $primary_att->ID(),
1550
+			],
1551
+			REG_ADMIN_URL
1552
+		);
1553
+		// get formatted address for registrant
1554
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1555
+		echo EEH_Template::display_template(
1556
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1557
+			$this->_template_args,
1558
+			true
1559
+		);
1560
+	}
1561
+
1562
+
1563
+	/**
1564
+	 * txn_billing_info_side_meta_box
1565
+	 *    generates HTML for the Edit Transaction side meta box
1566
+	 *
1567
+	 * @access public
1568
+	 * @return void
1569
+	 * @throws DomainException
1570
+	 * @throws EE_Error
1571
+	 * @throws ReflectionException
1572
+	 */
1573
+	public function txn_billing_info_side_meta_box()
1574
+	{
1575
+
1576
+		$this->_template_args['billing_form']     = $this->_transaction->billing_info();
1577
+		$this->_template_args['billing_form_url'] = add_query_arg(
1578
+			['action' => 'edit_transaction', 'process' => 'billing'],
1579
+			TXN_ADMIN_URL
1580
+		);
1581
+
1582
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1583
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1584
+	}
1585
+
1586
+
1587
+	/**
1588
+	 * apply_payments_or_refunds
1589
+	 *    registers a payment or refund made towards a transaction
1590
+	 *
1591
+	 * @access public
1592
+	 * @return void
1593
+	 * @throws EE_Error
1594
+	 * @throws InvalidArgumentException
1595
+	 * @throws ReflectionException
1596
+	 * @throws RuntimeException
1597
+	 * @throws InvalidDataTypeException
1598
+	 * @throws InvalidInterfaceException
1599
+	 */
1600
+	public function apply_payments_or_refunds()
1601
+	{
1602
+		$json_response_data = ['return_data' => false];
1603
+		$valid_data         = $this->_validate_payment_request_data();
1604
+		$has_access         = EE_Registry::instance()->CAP->current_user_can(
1605
+			'ee_edit_payments',
1606
+			'apply_payment_or_refund_from_registration_details'
1607
+		);
1608
+		if (! empty($valid_data) && $has_access) {
1609
+			$PAY_ID = $valid_data['PAY_ID'];
1610
+			// save  the new payment
1611
+			$payment = $this->_create_payment_from_request_data($valid_data);
1612
+			// get the TXN for this payment
1613
+			$transaction = $payment->transaction();
1614
+			// verify transaction
1615
+			if ($transaction instanceof EE_Transaction) {
1616
+				// calculate_total_payments_and_update_status
1617
+				$this->_process_transaction_payments($transaction);
1618
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1619
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1620
+				// apply payment to registrations (if applicable)
1621
+				if (! empty($REG_IDs)) {
1622
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1623
+					$this->_maybe_send_notifications();
1624
+					// now process status changes for the same registrations
1625
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1626
+				}
1627
+				$this->_maybe_send_notifications($payment);
1628
+				// prepare to render page
1629
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1630
+				do_action(
1631
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1632
+					$transaction,
1633
+					$payment
1634
+				);
1635
+			} else {
1636
+				EE_Error::add_error(
1637
+					esc_html__(
1638
+						'A valid Transaction for this payment could not be retrieved.',
1639
+						'event_espresso'
1640
+					),
1641
+					__FILE__,
1642
+					__FUNCTION__,
1643
+					__LINE__
1644
+				);
1645
+			}
1646
+		} elseif ($has_access) {
1647
+			EE_Error::add_error(
1648
+				esc_html__(
1649
+					'The payment form data could not be processed. Please try again.',
1650
+					'event_espresso'
1651
+				),
1652
+				__FILE__,
1653
+				__FUNCTION__,
1654
+				__LINE__
1655
+			);
1656
+		} else {
1657
+			EE_Error::add_error(
1658
+				esc_html__(
1659
+					'You do not have access to apply payments or refunds to a registration.',
1660
+					'event_espresso'
1661
+				),
1662
+				__FILE__,
1663
+				__FUNCTION__,
1664
+				__LINE__
1665
+			);
1666
+		}
1667
+		$notices              = EE_Error::get_notices(
1668
+			false,
1669
+			false,
1670
+			false
1671
+		);
1672
+		$this->_template_args = [
1673
+			'data'    => $json_response_data,
1674
+			'error'   => $notices['errors'],
1675
+			'success' => $notices['success'],
1676
+		];
1677
+		$this->_return_json();
1678
+	}
1679
+
1680
+
1681
+	/**
1682
+	 * _validate_payment_request_data
1683
+	 *
1684
+	 * @return array
1685
+	 * @throws EE_Error
1686
+	 * @throws InvalidArgumentException
1687
+	 * @throws InvalidDataTypeException
1688
+	 * @throws InvalidInterfaceException
1689
+	 */
1690
+	protected function _validate_payment_request_data()
1691
+	{
1692
+		if (! $this->request->requestParamIsSet('txn_admin_payment')) {
1693
+			return [];
1694
+		}
1695
+		$payment_form = $this->_generate_payment_form_section();
1696
+		try {
1697
+			if ($payment_form->was_submitted()) {
1698
+				$payment_form->receive_form_submission();
1699
+				if (! $payment_form->is_valid()) {
1700
+					$submission_error_messages = [];
1701
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1702
+						if ($validation_error instanceof EE_Validation_Error) {
1703
+							$form_input = $validation_error->get_form_section();
1704
+							$submission_error_messages[] = sprintf(
1705
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1706
+								$form_input instanceof EE_Form_Input_Base ? $form_input->html_label_text() : '',
1707
+								$validation_error->getMessage()
1708
+							);
1709
+						}
1710
+					}
1711
+					EE_Error::add_error(
1712
+						implode('<br />', $submission_error_messages),
1713
+						__FILE__,
1714
+						__FUNCTION__,
1715
+						__LINE__
1716
+					);
1717
+					return [];
1718
+				}
1719
+			}
1720
+		} catch (EE_Error $e) {
1721
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1722
+			return [];
1723
+		}
1724
+
1725
+		return $payment_form->valid_data();
1726
+	}
1727
+
1728
+
1729
+	/**
1730
+	 * _generate_payment_form_section
1731
+	 *
1732
+	 * @return EE_Form_Section_Proper
1733
+	 * @throws EE_Error
1734
+	 */
1735
+	protected function _generate_payment_form_section()
1736
+	{
1737
+		return new EE_Form_Section_Proper(
1738
+			[
1739
+				'name'        => 'txn_admin_payment',
1740
+				'subsections' => [
1741
+					'PAY_ID'          => new EE_Text_Input(
1742
+						[
1743
+							'default'               => 0,
1744
+							'required'              => false,
1745
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1746
+							'validation_strategies' => [new EE_Int_Normalization()],
1747
+						]
1748
+					),
1749
+					'TXN_ID'          => new EE_Text_Input(
1750
+						[
1751
+							'default'               => 0,
1752
+							'required'              => true,
1753
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1754
+							'validation_strategies' => [new EE_Int_Normalization()],
1755
+						]
1756
+					),
1757
+					'type'            => new EE_Text_Input(
1758
+						[
1759
+							'default'               => 1,
1760
+							'required'              => true,
1761
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1762
+							'validation_strategies' => [new EE_Int_Normalization()],
1763
+						]
1764
+					),
1765
+					'amount'          => new EE_Text_Input(
1766
+						[
1767
+							'default'               => 0,
1768
+							'required'              => true,
1769
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1770
+							'validation_strategies' => [new EE_Float_Normalization()],
1771
+						]
1772
+					),
1773
+					'status'          => new EE_Text_Input(
1774
+						[
1775
+							'default'         => EEM_Payment::status_id_approved,
1776
+							'required'        => true,
1777
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1778
+						]
1779
+					),
1780
+					'PMD_ID'          => new EE_Text_Input(
1781
+						[
1782
+							'default'               => 2,
1783
+							'required'              => true,
1784
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1785
+							'validation_strategies' => [new EE_Int_Normalization()],
1786
+						]
1787
+					),
1788
+					'date'            => new EE_Text_Input(
1789
+						[
1790
+							'default'         => time(),
1791
+							'required'        => true,
1792
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1793
+						]
1794
+					),
1795
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1796
+						[
1797
+							'default'               => '',
1798
+							'required'              => false,
1799
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1800
+							'validation_strategies' => [
1801
+								new EE_Max_Length_Validation_Strategy(
1802
+									esc_html__('Input too long', 'event_espresso'),
1803
+									100
1804
+								),
1805
+							],
1806
+						]
1807
+					),
1808
+					'po_number'       => new EE_Text_Input(
1809
+						[
1810
+							'default'               => '',
1811
+							'required'              => false,
1812
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1813
+							'validation_strategies' => [
1814
+								new EE_Max_Length_Validation_Strategy(
1815
+									esc_html__('Input too long', 'event_espresso'),
1816
+									100
1817
+								),
1818
+							],
1819
+						]
1820
+					),
1821
+					'accounting'      => new EE_Text_Input(
1822
+						[
1823
+							'default'               => '',
1824
+							'required'              => false,
1825
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1826
+							'validation_strategies' => [
1827
+								new EE_Max_Length_Validation_Strategy(
1828
+									esc_html__('Input too long', 'event_espresso'),
1829
+									100
1830
+								),
1831
+							],
1832
+						]
1833
+					),
1834
+				],
1835
+			]
1836
+		);
1837
+	}
1838
+
1839
+
1840
+	/**
1841
+	 * _create_payment_from_request_data
1842
+	 *
1843
+	 * @param array $valid_data
1844
+	 * @return EE_Payment
1845
+	 * @throws EE_Error
1846
+	 * @throws InvalidArgumentException
1847
+	 * @throws InvalidDataTypeException
1848
+	 * @throws InvalidInterfaceException
1849
+	 * @throws ReflectionException
1850
+	 */
1851
+	protected function _create_payment_from_request_data($valid_data)
1852
+	{
1853
+		$PAY_ID = $valid_data['PAY_ID'];
1854
+		// get payment amount
1855
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1856
+		// payments have a type value of 1 and refunds have a type value of -1
1857
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1858
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1859
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1860
+		$date    = $valid_data['date']
1861
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1862
+			: date('Y-m-d g:i a', current_time('timestamp'));
1863
+		$payment = EE_Payment::new_instance(
1864
+			[
1865
+				'TXN_ID'              => $valid_data['TXN_ID'],
1866
+				'STS_ID'              => $valid_data['status'],
1867
+				'PAY_timestamp'       => $date,
1868
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1869
+				'PMD_ID'              => $valid_data['PMD_ID'],
1870
+				'PAY_amount'          => $amount,
1871
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1872
+				'PAY_po_number'       => $valid_data['po_number'],
1873
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1874
+				'PAY_details'         => $valid_data,
1875
+				'PAY_ID'              => $PAY_ID,
1876
+			],
1877
+			'',
1878
+			['Y-m-d', 'g:i a']
1879
+		);
1880
+
1881
+		if (! $payment->save()) {
1882
+			EE_Error::add_error(
1883
+				sprintf(
1884
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1885
+					$payment->ID()
1886
+				),
1887
+				__FILE__,
1888
+				__FUNCTION__,
1889
+				__LINE__
1890
+			);
1891
+		}
1892
+
1893
+		return $payment;
1894
+	}
1895
+
1896
+
1897
+	/**
1898
+	 * _process_transaction_payments
1899
+	 *
1900
+	 * @param EE_Transaction $transaction
1901
+	 * @return void
1902
+	 * @throws EE_Error
1903
+	 * @throws InvalidArgumentException
1904
+	 * @throws ReflectionException
1905
+	 * @throws InvalidDataTypeException
1906
+	 * @throws InvalidInterfaceException
1907
+	 */
1908
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1909
+	{
1910
+		/** @type EE_Transaction_Payments $transaction_payments */
1911
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1912
+		// update the transaction with this payment
1913
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1914
+			EE_Error::add_success(
1915
+				esc_html__(
1916
+					'The payment has been processed successfully.',
1917
+					'event_espresso'
1918
+				),
1919
+				__FILE__,
1920
+				__FUNCTION__,
1921
+				__LINE__
1922
+			);
1923
+		} else {
1924
+			EE_Error::add_error(
1925
+				esc_html__(
1926
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1927
+					'event_espresso'
1928
+				),
1929
+				__FILE__,
1930
+				__FUNCTION__,
1931
+				__LINE__
1932
+			);
1933
+		}
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * _get_REG_IDs_to_apply_payment_to
1939
+	 * returns a list of registration IDs that the payment will apply to
1940
+	 *
1941
+	 * @param EE_Payment $payment
1942
+	 * @return array
1943
+	 * @throws EE_Error
1944
+	 * @throws InvalidArgumentException
1945
+	 * @throws InvalidDataTypeException
1946
+	 * @throws InvalidInterfaceException
1947
+	 * @throws ReflectionException
1948
+	 */
1949
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1950
+	{
1951
+		// grab array of IDs for specific registrations to apply changes to
1952
+		$REG_IDs = $this->request->getRequestParam('txn_admin_payment[registrations]', [], 'int', true);
1953
+		// nothing specified ? then get all reg IDs
1954
+		if (empty($REG_IDs)) {
1955
+			$registrations = $payment->transaction()->registrations();
1956
+			$REG_IDs       = ! empty($registrations)
1957
+				? array_keys($registrations)
1958
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1959
+		}
1960
+
1961
+		// ensure that REG_IDs are integers and NOT strings
1962
+		return array_map('intval', $REG_IDs);
1963
+	}
1964
+
1965
+
1966
+	/**
1967
+	 * @return array
1968
+	 */
1969
+	public function existing_reg_payment_REG_IDs()
1970
+	{
1971
+		return $this->_existing_reg_payment_REG_IDs;
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * @param array $existing_reg_payment_REG_IDs
1977
+	 */
1978
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1979
+	{
1980
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1981
+	}
1982
+
1983
+
1984
+	/**
1985
+	 * _get_existing_reg_payment_REG_IDs
1986
+	 * returns a list of registration IDs that the payment is currently related to
1987
+	 * as recorded in the database
1988
+	 *
1989
+	 * @param EE_Payment $payment
1990
+	 * @return array
1991
+	 * @throws EE_Error
1992
+	 * @throws InvalidArgumentException
1993
+	 * @throws InvalidDataTypeException
1994
+	 * @throws InvalidInterfaceException
1995
+	 * @throws ReflectionException
1996
+	 */
1997
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1998
+	{
1999
+		if ($this->existing_reg_payment_REG_IDs() === null) {
2000
+			// let's get any existing reg payment records for this payment
2001
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2002
+			// but we only want the REG IDs, so grab the array keys
2003
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2004
+				? array_keys($existing_reg_payment_REG_IDs)
2005
+				: [];
2006
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2007
+		}
2008
+
2009
+		return $this->existing_reg_payment_REG_IDs();
2010
+	}
2011
+
2012
+
2013
+	/**
2014
+	 * _remove_existing_registration_payments
2015
+	 * this calculates the difference between existing relations
2016
+	 * to the supplied payment and the new list registration IDs,
2017
+	 * removes any related registrations that no longer apply,
2018
+	 * and then updates the registration paid fields
2019
+	 *
2020
+	 * @param EE_Payment $payment
2021
+	 * @param int        $PAY_ID
2022
+	 * @return bool;
2023
+	 * @throws EE_Error
2024
+	 * @throws InvalidArgumentException
2025
+	 * @throws ReflectionException
2026
+	 * @throws InvalidDataTypeException
2027
+	 * @throws InvalidInterfaceException
2028
+	 */
2029
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2030
+	{
2031
+		// newly created payments will have nothing recorded for $PAY_ID
2032
+		if (absint($PAY_ID) === 0) {
2033
+			return false;
2034
+		}
2035
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2036
+		if (empty($existing_reg_payment_REG_IDs)) {
2037
+			return false;
2038
+		}
2039
+		/** @type EE_Transaction_Payments $transaction_payments */
2040
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2041
+
2042
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2043
+			$payment,
2044
+			[
2045
+				[
2046
+					'PAY_ID' => $payment->ID(),
2047
+					'REG_ID' => ['IN', $existing_reg_payment_REG_IDs],
2048
+				],
2049
+			]
2050
+		);
2051
+	}
2052
+
2053
+
2054
+	/**
2055
+	 * _update_registration_payments
2056
+	 * this applies the payments to the selected registrations
2057
+	 * but only if they have not already been paid for
2058
+	 *
2059
+	 * @param EE_Transaction $transaction
2060
+	 * @param EE_Payment     $payment
2061
+	 * @param array          $REG_IDs
2062
+	 * @return void
2063
+	 * @throws EE_Error
2064
+	 * @throws InvalidArgumentException
2065
+	 * @throws ReflectionException
2066
+	 * @throws RuntimeException
2067
+	 * @throws InvalidDataTypeException
2068
+	 * @throws InvalidInterfaceException
2069
+	 */
2070
+	protected function _update_registration_payments(
2071
+		EE_Transaction $transaction,
2072
+		EE_Payment $payment,
2073
+		$REG_IDs = []
2074
+	) {
2075
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2076
+		// so let's do that using our set of REG_IDs from the form
2077
+		$registration_query_where_params = [
2078
+			'REG_ID' => ['IN', $REG_IDs],
2079
+		];
2080
+		// but add in some conditions regarding payment,
2081
+		// so that we don't apply payments to registrations that are free or have already been paid for
2082
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2083
+		if (! $payment->is_a_refund()) {
2084
+			$registration_query_where_params['REG_final_price']  = ['!=', 0];
2085
+			$registration_query_where_params['REG_final_price*'] = ['!=', 'REG_paid', true];
2086
+		}
2087
+		$registrations = $transaction->registrations([$registration_query_where_params]);
2088
+		if (! empty($registrations)) {
2089
+			/** @type EE_Payment_Processor $payment_processor */
2090
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2091
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2092
+		}
2093
+	}
2094
+
2095
+
2096
+	/**
2097
+	 * _process_registration_status_change
2098
+	 * This processes requested registration status changes for all the registrations
2099
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2100
+	 *
2101
+	 * @param EE_Transaction $transaction
2102
+	 * @param array          $REG_IDs
2103
+	 * @return bool
2104
+	 * @throws EE_Error
2105
+	 * @throws InvalidArgumentException
2106
+	 * @throws ReflectionException
2107
+	 * @throws InvalidDataTypeException
2108
+	 * @throws InvalidInterfaceException
2109
+	 */
2110
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = [])
2111
+	{
2112
+		// first if there is no change in status then we get out.
2113
+		$reg_status = $this->request->getRequestParam('txn_reg_status_change[reg_status]', 'NAN');
2114
+		if ($reg_status === 'NAN') {
2115
+			// no error message, no change requested, just nothing to do man.
2116
+			return false;
2117
+		}
2118
+		/** @type EE_Transaction_Processor $transaction_processor */
2119
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2120
+
2121
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2122
+		return $transaction_processor->manually_update_registration_statuses(
2123
+			$transaction,
2124
+			$reg_status,
2125
+			[['REG_ID' => ['IN', $REG_IDs]]]
2126
+		);
2127
+	}
2128
+
2129
+
2130
+	/**
2131
+	 * _build_payment_json_response
2132
+	 *
2133
+	 * @access public
2134
+	 * @param EE_Payment  $payment
2135
+	 * @param array       $REG_IDs
2136
+	 * @param bool | null $delete_txn_reg_status_change
2137
+	 * @return array
2138
+	 * @throws EE_Error
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws InvalidDataTypeException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws ReflectionException
2143
+	 */
2144
+	protected function _build_payment_json_response(
2145
+		EE_Payment $payment,
2146
+		$REG_IDs = [],
2147
+		$delete_txn_reg_status_change = null
2148
+	) {
2149
+		// was the payment deleted ?
2150
+		if (is_bool($delete_txn_reg_status_change)) {
2151
+			return [
2152
+				'PAY_ID'                       => $payment->ID(),
2153
+				'amount'                       => $payment->amount(),
2154
+				'total_paid'                   => $payment->transaction()->paid(),
2155
+				'txn_status'                   => $payment->transaction()->status_ID(),
2156
+				'pay_status'                   => $payment->STS_ID(),
2157
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2158
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2159
+			];
2160
+		}
2161
+
2162
+		$this->_get_payment_status_array();
2163
+		return [
2164
+			'amount'           => $payment->amount(),
2165
+			'total_paid'       => $payment->transaction()->paid(),
2166
+			'txn_status'       => $payment->transaction()->status_ID(),
2167
+			'pay_status'       => $payment->STS_ID(),
2168
+			'PAY_ID'           => $payment->ID(),
2169
+			'STS_ID'           => $payment->STS_ID(),
2170
+			'status'           => self::$_pay_status[ $payment->STS_ID() ],
2171
+			'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2172
+			'method'           => strtoupper($payment->source()),
2173
+			'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2174
+			'gateway'          => $payment->payment_method()
2175
+				? $payment->payment_method()->admin_name()
2176
+				: esc_html__('Unknown', 'event_espresso'),
2177
+			'gateway_response' => $payment->gateway_response(),
2178
+			'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2179
+			'po_number'        => $payment->po_number(),
2180
+			'extra_accntng'    => $payment->extra_accntng(),
2181
+			'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2182
+		];
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * delete_payment
2188
+	 *    delete a payment or refund made towards a transaction
2189
+	 *
2190
+	 * @access public
2191
+	 * @return void
2192
+	 * @throws EE_Error
2193
+	 * @throws InvalidArgumentException
2194
+	 * @throws ReflectionException
2195
+	 * @throws InvalidDataTypeException
2196
+	 * @throws InvalidInterfaceException
2197
+	 */
2198
+	public function delete_payment()
2199
+	{
2200
+		$json_response_data = ['return_data' => false];
2201
+		$PAY_ID = $this->request->getRequestParam('delete_txn_admin_payment[PAY_ID]', 0, 'int');
2202
+
2203
+		$can_delete         = EE_Registry::instance()->CAP->current_user_can(
2204
+			'ee_delete_payments',
2205
+			'delete_payment_from_registration_details'
2206
+		);
2207
+		if ($PAY_ID && $can_delete) {
2208
+			$delete_txn_reg_status_change = $this->request->getRequestParam(
2209
+				'delete_txn_reg_status_change',
2210
+				false,
2211
+				'bool'
2212
+			);
2213
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2214
+			if ($payment instanceof EE_Payment) {
2215
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2216
+				/** @type EE_Transaction_Payments $transaction_payments */
2217
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2218
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2219
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2220
+						$payment,
2221
+						$REG_IDs,
2222
+						$delete_txn_reg_status_change
2223
+					);
2224
+					if ($delete_txn_reg_status_change) {
2225
+						// MAKE sure we also add the delete_txn_req_status_change to the
2226
+						// request data because that's how messages will be looking for it.
2227
+						$this->request->setRequestParam('txn_reg_status_change', $delete_txn_reg_status_change);
2228
+						$this->_maybe_send_notifications();
2229
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2230
+					}
2231
+				}
2232
+			} else {
2233
+				EE_Error::add_error(
2234
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2235
+					__FILE__,
2236
+					__FUNCTION__,
2237
+					__LINE__
2238
+				);
2239
+			}
2240
+		} elseif ($can_delete) {
2241
+			EE_Error::add_error(
2242
+				esc_html__(
2243
+					'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2244
+					'event_espresso'
2245
+				),
2246
+				__FILE__,
2247
+				__FUNCTION__,
2248
+				__LINE__
2249
+			);
2250
+		} else {
2251
+			EE_Error::add_error(
2252
+				esc_html__(
2253
+					'You do not have access to delete a payment.',
2254
+					'event_espresso'
2255
+				),
2256
+				__FILE__,
2257
+				__FUNCTION__,
2258
+				__LINE__
2259
+			);
2260
+		}
2261
+		$notices              = EE_Error::get_notices(false, false, false);
2262
+		$this->_template_args = [
2263
+			'data'      => $json_response_data,
2264
+			'success'   => $notices['success'],
2265
+			'error'     => $notices['errors'],
2266
+			'attention' => $notices['attention'],
2267
+		];
2268
+		$this->_return_json();
2269
+	}
2270
+
2271
+
2272
+	/**
2273
+	 * _registration_payment_data_array
2274
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2275
+	 *
2276
+	 * @access protected
2277
+	 * @param array $REG_IDs
2278
+	 * @return array
2279
+	 * @throws EE_Error
2280
+	 * @throws InvalidArgumentException
2281
+	 * @throws InvalidDataTypeException
2282
+	 * @throws InvalidInterfaceException
2283
+	 * @throws ReflectionException
2284
+	 */
2285
+	protected function _registration_payment_data_array($REG_IDs)
2286
+	{
2287
+		$registration_payment_data = [];
2288
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2289
+		if (! empty($REG_IDs)) {
2290
+			$registrations = EEM_Registration::instance()->get_all([['REG_ID' => ['IN', $REG_IDs]]]);
2291
+			foreach ($registrations as $registration) {
2292
+				if ($registration instanceof EE_Registration) {
2293
+					$registration_payment_data[ $registration->ID() ] = [
2294
+						'paid'  => $registration->pretty_paid(),
2295
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2296
+					];
2297
+				}
2298
+			}
2299
+		}
2300
+
2301
+		return $registration_payment_data;
2302
+	}
2303
+
2304
+
2305
+	/**
2306
+	 * _maybe_send_notifications
2307
+	 * determines whether or not the admin has indicated that notifications should be sent.
2308
+	 * If so, will toggle a filter switch for delivering registration notices.
2309
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2310
+	 *
2311
+	 * @access protected
2312
+	 * @param EE_Payment | null $payment
2313
+	 */
2314
+	protected function _maybe_send_notifications($payment = null)
2315
+	{
2316
+		switch ($payment instanceof EE_Payment) {
2317
+			// payment notifications
2318
+			case true:
2319
+				if ($this->request->getRequestParam('txn_payments[send_notifications]', false, 'bool')) {
2320
+					$this->_process_payment_notification($payment);
2321
+				}
2322
+				break;
2323
+			// registration notifications
2324
+			case false:
2325
+				if ($this->request->getRequestParam('txn_reg_status_change[send_notifications]', false, 'bool')) {
2326
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2327
+				}
2328
+				break;
2329
+		}
2330
+	}
2331
+
2332
+
2333
+	/**
2334
+	 * _send_payment_reminder
2335
+	 *    generates HTML for the View Transaction Details Admin page
2336
+	 *
2337
+	 * @access protected
2338
+	 * @return void
2339
+	 * @throws EE_Error
2340
+	 * @throws InvalidArgumentException
2341
+	 * @throws InvalidDataTypeException
2342
+	 * @throws InvalidInterfaceException
2343
+	 */
2344
+	protected function _send_payment_reminder()
2345
+	{
2346
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2347
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2348
+		$redirect_to = $this->request->getRequestParam('redirect_to');
2349
+		$query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2350
+		do_action(
2351
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2352
+			$transaction
2353
+		);
2354
+		$this->_redirect_after_action(
2355
+			false,
2356
+			esc_html__('payment reminder', 'event_espresso'),
2357
+			esc_html__('sent', 'event_espresso'),
2358
+			$query_args,
2359
+			true
2360
+		);
2361
+	}
2362
+
2363
+
2364
+	/**
2365
+	 *  get_transactions
2366
+	 *    get transactions for given parameters (used by list table)
2367
+	 *
2368
+	 * @param int     $per_page how many transactions displayed per page
2369
+	 * @param boolean $count   return the count or objects
2370
+	 * @param string  $view
2371
+	 * @return EE_Transaction[]|int int = count || array of transaction objects
2372
+	 * @throws EE_Error
2373
+	 * @throws InvalidArgumentException
2374
+	 * @throws InvalidDataTypeException
2375
+	 * @throws InvalidInterfaceException
2376
+	 */
2377
+	public function get_transactions($per_page, $count = false, $view = '')
2378
+	{
2379
+		$start_date = wp_strip_all_tags(
2380
+			$this->request->getRequestParam('txn-filter-start-date', date('m/d/Y', strtotime('-10 year')))
2381
+		);
2382
+		$end_date = wp_strip_all_tags(
2383
+			$this->request->getRequestParam('txn-filter-end-date', date('m/d/Y'))
2384
+		);
2385
+
2386
+		// make sure our timestamps start and end right at the boundaries for each day
2387
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2388
+		$end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2389
+
2390
+
2391
+		// convert to timestamps
2392
+		$start_date = strtotime($start_date);
2393
+		$end_date   = strtotime($end_date);
2394
+
2395
+		// makes sure start date is the lowest value and vice versa
2396
+		$start_date = min($start_date, $end_date);
2397
+		$end_date   = max($start_date, $end_date);
2398
+
2399
+		// convert to correct format for query
2400
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2401
+			'TXN_timestamp',
2402
+			date('Y-m-d H:i:s', $start_date),
2403
+			'Y-m-d H:i:s'
2404
+		);
2405
+		$end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2406
+			'TXN_timestamp',
2407
+			date('Y-m-d H:i:s', $end_date),
2408
+			'Y-m-d H:i:s'
2409
+		);
2410
+
2411
+
2412
+		// set orderby
2413
+		$orderby = $this->request->getRequestParam('orderby');
2414
+
2415
+		switch ($orderby) {
2416
+			case 'TXN_ID':
2417
+				break;
2418
+			case 'ATT_fname':
2419
+				$orderby = 'Registration.Attendee.ATT_fname';
2420
+				break;
2421
+			case 'event_name':
2422
+				$orderby = 'Registration.Event.EVT_name';
2423
+				break;
2424
+			default: // 'TXN_timestamp'
2425
+				$orderby = 'TXN_timestamp';
2426
+		}
2427
+
2428
+		$sort         = $this->request->getRequestParam('order', 'DESC');
2429
+		$current_page = $this->request->getRequestParam('paged', 1, 'int');
2430
+
2431
+		$per_page = absint($per_page) ? $per_page : 10;
2432
+		$per_page = $this->request->getRequestParam('perpage', $per_page, 'int');
2433
+
2434
+		$offset = ($current_page - 1) * $per_page;
2435
+		$limit  = [$offset, $per_page];
2436
+
2437
+		$_where = [
2438
+			'TXN_timestamp'          => ['BETWEEN', [$start_date, $end_date]],
2439
+			'Registration.REG_count' => 1,
2440
+		];
2441
+
2442
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2443
+		if ($EVT_ID) {
2444
+			$_where['Registration.EVT_ID'] = $EVT_ID;
2445
+		}
2446
+
2447
+		$search_term = $this->request->getRequestParam('s');
2448
+		if ($search_term) {
2449
+			$search_term = '%' . $search_term . '%';
2450
+			$_where['OR']  = [
2451
+				'Registration.Event.EVT_name'         => ['LIKE', $search_term],
2452
+				'Registration.Event.EVT_desc'         => ['LIKE', $search_term],
2453
+				'Registration.Event.EVT_short_desc'   => ['LIKE', $search_term],
2454
+				'Registration.Attendee.ATT_full_name' => ['LIKE', $search_term],
2455
+				'Registration.Attendee.ATT_fname'     => ['LIKE', $search_term],
2456
+				'Registration.Attendee.ATT_lname'     => ['LIKE', $search_term],
2457
+				'Registration.Attendee.ATT_short_bio' => ['LIKE', $search_term],
2458
+				'Registration.Attendee.ATT_email'     => ['LIKE', $search_term],
2459
+				'Registration.Attendee.ATT_address'   => ['LIKE', $search_term],
2460
+				'Registration.Attendee.ATT_address2'  => ['LIKE', $search_term],
2461
+				'Registration.Attendee.ATT_city'      => ['LIKE', $search_term],
2462
+				'Registration.REG_final_price'        => ['LIKE', $search_term],
2463
+				'Registration.REG_code'               => ['LIKE', $search_term],
2464
+				'Registration.REG_count'              => ['LIKE', $search_term],
2465
+				'Registration.REG_group_size'         => ['LIKE', $search_term],
2466
+				'Registration.Ticket.TKT_name'        => ['LIKE', $search_term],
2467
+				'Registration.Ticket.TKT_description' => ['LIKE', $search_term],
2468
+				'Payment.PAY_source'                  => ['LIKE', $search_term],
2469
+				'Payment.Payment_Method.PMD_name'     => ['LIKE', $search_term],
2470
+				'TXN_session_data'                    => ['LIKE', $search_term],
2471
+				'Payment.PAY_txn_id_chq_nmbr'         => ['LIKE', $search_term],
2472
+			];
2473
+		}
2474
+
2475
+		$status = $this->request->getRequestParam('status');
2476
+		// failed transactions
2477
+		$failed     = (! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2478
+		$abandoned  = (! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2479
+		$incomplete = (! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2480
+
2481
+		if ($failed) {
2482
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2483
+		} elseif ($abandoned) {
2484
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2485
+		} elseif ($incomplete) {
2486
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2487
+		} else {
2488
+			$_where['STS_ID']  = ['!=', EEM_Transaction::failed_status_code];
2489
+			$_where['STS_ID*'] = ['!=', EEM_Transaction::abandoned_status_code];
2490
+		}
2491
+
2492
+		$query_params = apply_filters(
2493
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2494
+			[
2495
+				$_where,
2496
+				'order_by'                 => [$orderby => $sort],
2497
+				'limit'                    => $limit,
2498
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2499
+			],
2500
+			$this->request->requestParams(),
2501
+			$view,
2502
+			$count
2503
+		);
2504
+
2505
+		return $count
2506
+			? EEM_Transaction::instance()->count([$query_params[0]], 'TXN_ID', true)
2507
+			: EEM_Transaction::instance()->get_all($query_params);
2508
+	}
2509
+
2510
+
2511
+	/**
2512
+	 * @throws EE_Error
2513
+	 * @throws InvalidArgumentException
2514
+	 * @throws InvalidDataTypeException
2515
+	 * @throws InvalidInterfaceException
2516
+	 * @throws ReflectionException
2517
+	 * @throws RuntimeException
2518
+	 * @since 4.9.79.p
2519
+	 */
2520
+	public function recalculateLineItems()
2521
+	{
2522
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2523
+		/** @var EE_Transaction $transaction */
2524
+		$transaction     = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2525
+		$success         = $transaction->recalculateLineItems();
2526
+		$redirect_to = $this->request->getRequestParam('redirect_to');
2527
+		$query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2528
+		$this->_redirect_after_action(
2529
+			$success,
2530
+			esc_html__('Transaction taxes and totals', 'event_espresso'),
2531
+			esc_html__('recalculated', 'event_espresso'),
2532
+			$query_args,
2533
+			true
2534
+		);
2535
+	}
2536 2536
 }
Please login to merge, or discard this patch.
Spacing   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
             'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
246 246
             'event_espresso'
247 247
         );
248
-        EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
248
+        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
249 249
             'An error occurred! Please refresh the page and try again.',
250 250
             'event_espresso'
251 251
         );
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
         // enqueue style
345 345
         wp_register_style(
346 346
             'espresso_txn',
347
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
347
+            TXN_ASSETS_URL.'espresso_transactions_admin.css',
348 348
             [],
349 349
             EVENT_ESPRESSO_VERSION
350 350
         );
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
         // scripts
353 353
         wp_register_script(
354 354
             'espresso_txn',
355
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
355
+            TXN_ASSETS_URL.'espresso_transactions_admin.js',
356 356
             [
357 357
                 'ee_admin_js',
358 358
                 'ee-datepicker',
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
             $this->_transaction->verify_abandoned_transaction_status();
480 480
         }
481 481
 
482
-        if (! $this->_transaction instanceof EE_Transaction) {
482
+        if ( ! $this->_transaction instanceof EE_Transaction) {
483 483
             $error_msg = sprintf(
484 484
                 esc_html__(
485 485
                     'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
             'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
577 577
             [
578 578
                 'overpaid'   => [
579
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
579
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::overpaid_status_code,
580 580
                     'desc'  => EEH_Template::pretty_status(
581 581
                         EEM_Transaction::overpaid_status_code,
582 582
                         false,
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
                     ),
585 585
                 ],
586 586
                 'complete'   => [
587
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
587
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::complete_status_code,
588 588
                     'desc'  => EEH_Template::pretty_status(
589 589
                         EEM_Transaction::complete_status_code,
590 590
                         false,
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
                     ),
593 593
                 ],
594 594
                 'incomplete' => [
595
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
595
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::incomplete_status_code,
596 596
                     'desc'  => EEH_Template::pretty_status(
597 597
                         EEM_Transaction::incomplete_status_code,
598 598
                         false,
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
                     ),
601 601
                 ],
602 602
                 'abandoned'  => [
603
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
603
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::abandoned_status_code,
604 604
                     'desc'  => EEH_Template::pretty_status(
605 605
                         EEM_Transaction::abandoned_status_code,
606 606
                         false,
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
                     ),
609 609
                 ],
610 610
                 'failed'     => [
611
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
611
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::failed_status_code,
612 612
                     'desc'  => EEH_Template::pretty_status(
613 613
                         EEM_Transaction::failed_status_code,
614 614
                         false,
@@ -651,11 +651,11 @@  discard block
 block discarded – undo
651 651
                 )
652 652
                 . '" aria-label="'
653 653
                 . esc_attr__('Click to Edit event', 'event_espresso')
654
-                . '">' . $event->name() . '</a>',
654
+                . '">'.$event->name().'</a>',
655 655
                 '</h3>'
656 656
             )
657 657
             : '';
658
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
658
+        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
659 659
         $this->display_admin_list_table_page_with_no_sidebar();
660 660
     }
661 661
 
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 
686 686
         $this->_set_transaction_object();
687 687
 
688
-        if (! $this->_transaction instanceof EE_Transaction) {
688
+        if ( ! $this->_transaction instanceof EE_Transaction) {
689 689
             return;
690 690
         }
691 691
 
@@ -695,9 +695,9 @@  discard block
 block discarded – undo
695 695
         $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
696 696
         $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
697 697
 
698
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
698
+        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->status_ID()];
699 699
         $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
700
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
700
+        $this->_template_args['txn_status']['class'] = 'status-'.$this->_transaction->status_ID();
701 701
 
702 702
         $this->_template_args['grand_total'] = $this->_transaction->total();
703 703
         $this->_template_args['total_paid']  = $this->_transaction->paid();
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 
750 750
 
751 751
         // next link
752
-        $next_txn                                 = $this->_transaction->next(
752
+        $next_txn = $this->_transaction->next(
753 753
             null,
754 754
             [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
755 755
             'TXN_ID'
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
             )
765 765
             : '';
766 766
         // previous link
767
-        $previous_txn                                 = $this->_transaction->previous(
767
+        $previous_txn = $this->_transaction->previous(
768 768
             null,
769 769
             [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
770 770
             'TXN_ID'
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
         // grab messages at the last second
817 817
         $this->_template_args['notices'] = EE_Error::get_notices();
818 818
         // path to template
819
-        $template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
819
+        $template_path                             = TXN_TEMPLATE_PATH.'txn_admin_details_header.template.php';
820 820
         $this->_template_args['admin_page_header'] = EEH_Template::display_template(
821 821
             $template_path,
822 822
             $this->_template_args,
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 
846 846
         $this->_set_transaction_object();
847 847
 
848
-        if (! $this->_transaction instanceof EE_Transaction) {
848
+        if ( ! $this->_transaction instanceof EE_Transaction) {
849 849
             return;
850 850
         }
851 851
         add_meta_box(
@@ -901,7 +901,7 @@  discard block
 block discarded – undo
901 901
     {
902 902
         $content = '';
903 903
         $actions = [];
904
-        if (! $transaction instanceof EE_Transaction) {
904
+        if ( ! $transaction instanceof EE_Transaction) {
905 905
             return $content;
906 906
         }
907 907
         /** @var EE_Registration $primary_registration */
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
         );
987 987
         if ($actions) {
988 988
             $content = '<ul>';
989
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
989
+            $content .= '<li>'.implode('</li><li>', $actions).'</li>';
990 990
             $content .= '</uL>';
991 991
         }
992 992
         return $content;
@@ -1014,7 +1014,7 @@  discard block
 block discarded – undo
1014 1014
             $this->_transaction->primary_registration() instanceof EE_Registration
1015 1015
                 ? $this->_transaction->primary_registration()->attendee()
1016 1016
                 : null;
1017
-        $this->_template_args['can_edit_payments']   = EE_Registry::instance()->CAP->current_user_can(
1017
+        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1018 1018
             'ee_edit_payments',
1019 1019
             'apply_payment_or_refund_from_registration_details'
1020 1020
         );
@@ -1025,7 +1025,7 @@  discard block
 block discarded – undo
1025 1025
 
1026 1026
         // get line table
1027 1027
         EEH_Autoloader::register_line_item_display_autoloaders();
1028
-        $Line_Item_Display                       = new EE_Line_Item_Display(
1028
+        $Line_Item_Display = new EE_Line_Item_Display(
1029 1029
             'admin_table',
1030 1030
             'EE_Admin_Table_Line_Item_Display_Strategy'
1031 1031
         );
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
         $taxes                         = $this->_transaction->line_items([['LIN_type' => EEM_Line_Item::type_tax]]);
1041 1041
         $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1042 1042
 
1043
-        $this->_template_args['grand_total']     = EEH_Template::format_currency(
1043
+        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1044 1044
             $this->_transaction->total(),
1045 1045
             false,
1046 1046
             false
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
 
1051 1051
         // process payment details
1052 1052
         $payments = $this->_transaction->payments();
1053
-        if (! empty($payments)) {
1053
+        if ( ! empty($payments)) {
1054 1054
             $this->_template_args['payments']              = $payments;
1055 1055
             $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1056 1056
         } else {
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
                                   esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1113 1113
                                   ucwords(str_replace('_', ' ', $reg_step)),
1114 1114
                                   date(
1115
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1115
+                                      get_option('date_format').' '.get_option('time_format'),
1116 1116
                                       $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1117 1117
                                   )
1118 1118
                               )
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
                               . '</li>';
1127 1127
             }
1128 1128
         }
1129
-        $reg_steps                                                 .= '</ul>';
1129
+        $reg_steps .= '</ul>';
1130 1130
         $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1131 1131
         $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1132 1132
             'Registration Step Progress',
@@ -1139,14 +1139,14 @@  discard block
 block discarded – undo
1139 1139
         $this->_get_payment_status_array();
1140 1140
         $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1141 1141
 
1142
-        $this->_template_args['transaction_form_url']    = add_query_arg(
1142
+        $this->_template_args['transaction_form_url'] = add_query_arg(
1143 1143
             [
1144 1144
                 'action'  => 'edit_transaction',
1145 1145
                 'process' => 'transaction',
1146 1146
             ],
1147 1147
             TXN_ADMIN_URL
1148 1148
         );
1149
-        $this->_template_args['apply_payment_form_url']  = add_query_arg(
1149
+        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1150 1150
             [
1151 1151
                 'page'   => 'espresso_transactions',
1152 1152
                 'action' => 'espresso_apply_payment',
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
 
1166 1166
         // 'espresso_delete_payment_nonce'
1167 1167
 
1168
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1168
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_txn_details.template.php';
1169 1169
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1170 1170
     }
1171 1171
 
@@ -1197,19 +1197,19 @@  discard block
 block discarded – undo
1197 1197
                 ],
1198 1198
             ]
1199 1199
         );
1200
-        if (! empty($reg_payments)) {
1200
+        if ( ! empty($reg_payments)) {
1201 1201
             foreach ($payments as $payment) {
1202
-                if (! $payment instanceof EE_Payment) {
1202
+                if ( ! $payment instanceof EE_Payment) {
1203 1203
                     continue;
1204
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1205
-                    $existing_reg_payments[ $payment->ID() ] = [];
1204
+                } elseif ( ! isset($existing_reg_payments[$payment->ID()])) {
1205
+                    $existing_reg_payments[$payment->ID()] = [];
1206 1206
                 }
1207 1207
                 foreach ($reg_payments as $reg_payment) {
1208 1208
                     if (
1209 1209
                         $reg_payment instanceof EE_Registration_Payment
1210 1210
                         && $reg_payment->payment_ID() === $payment->ID()
1211 1211
                     ) {
1212
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1212
+                        $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
1213 1213
                     }
1214 1214
                 }
1215 1215
             }
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
     protected function _get_registrations_to_apply_payment_to()
1236 1236
     {
1237 1237
         // we want any registration with an active status (ie: not deleted or cancelled)
1238
-        $query_params                      = [
1238
+        $query_params = [
1239 1239
             [
1240 1240
                 'STS_ID' => [
1241 1241
                     'IN',
@@ -1247,22 +1247,22 @@  discard block
 block discarded – undo
1247 1247
                 ],
1248 1248
             ],
1249 1249
         ];
1250
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1250
+        $registrations_to_apply_payment_to = EEH_HTML::br().EEH_HTML::div(
1251 1251
             '',
1252 1252
             'txn-admin-apply-payment-to-registrations-dv',
1253 1253
             '',
1254 1254
             'clear: both; margin: 1.5em 0 0; display: none;'
1255 1255
         );
1256
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1256
+        $registrations_to_apply_payment_to .= EEH_HTML::br().EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1257 1257
         $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1258 1258
         $registrations_to_apply_payment_to .= EEH_HTML::thead(
1259 1259
             EEH_HTML::tr(
1260
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1261
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1262
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1263
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1264
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1265
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1260
+                EEH_HTML::th(esc_html__('ID', 'event_espresso')).
1261
+                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')).
1262
+                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')).
1263
+                EEH_HTML::th(esc_html__('Event', 'event_espresso')).
1264
+                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr').
1265
+                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr').
1266 1266
                 EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1267 1267
             )
1268 1268
         );
@@ -1277,34 +1277,34 @@  discard block
 block discarded – undo
1277 1277
                     : esc_html__('Unknown Attendee', 'event_espresso');
1278 1278
                 $owing                             = $registration->final_price() - $registration->paid();
1279 1279
                 $taxable                           = $registration->ticket()->taxable()
1280
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1280
+                    ? ' <span class="smaller-text lt-grey-text"> '.esc_html__('+ tax', 'event_espresso').'</span>'
1281 1281
                     : '';
1282 1282
                 $checked                           = empty($existing_reg_payments)
1283 1283
                                                      || in_array($registration->ID(), $existing_reg_payments, true)
1284 1284
                     ? ' checked'
1285 1285
                     : '';
1286
-                $disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1286
+                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1287 1287
                 $registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
-                    EEH_HTML::td($registration->ID()) .
1289
-                    EEH_HTML::td($attendee_name) .
1288
+                    EEH_HTML::td($registration->ID()).
1289
+                    EEH_HTML::td($attendee_name).
1290 1290
                     EEH_HTML::td(
1291
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
-                    ) .
1293
-                    EEH_HTML::td($registration->event_name()) .
1294
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1291
+                        $registration->ticket()->name().' : '.$registration->ticket()->pretty_price().$taxable
1292
+                    ).
1293
+                    EEH_HTML::td($registration->event_name()).
1294
+                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr').
1295 1295
                     EEH_HTML::td(
1296 1296
                         EEH_Template::format_currency($owing),
1297 1297
                         '',
1298 1298
                         'txn-admin-payment-owing-td jst-cntr'
1299
-                    ) .
1299
+                    ).
1300 1300
                     EEH_HTML::td(
1301
-                        '<input type="checkbox" value="' . $registration->ID()
1301
+                        '<input type="checkbox" value="'.$registration->ID()
1302 1302
                         . '" name="txn_admin_payment[registrations]"'
1303
-                        . $checked . $disabled . '>',
1303
+                        . $checked.$disabled.'>',
1304 1304
                         '',
1305 1305
                         'jst-cntr'
1306 1306
                     ),
1307
-                    'apply-payment-registration-row-' . $registration->ID()
1307
+                    'apply-payment-registration-row-'.$registration->ID()
1308 1308
                 );
1309 1309
             }
1310 1310
         }
@@ -1319,7 +1319,7 @@  discard block
 block discarded – undo
1319 1319
             '',
1320 1320
             'clear description'
1321 1321
         );
1322
-        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1322
+        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1323 1323
         $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1324 1324
     }
1325 1325
 
@@ -1385,12 +1385,12 @@  discard block
 block discarded – undo
1385 1385
                 [
1386 1386
                     'OR*payment_method_for_payment' => [
1387 1387
                         'PMD_ID'    => ['IN', $payment_methods_of_payments],
1388
-                        'PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%'],
1388
+                        'PMD_scope' => ['LIKE', '%'.EEM_Payment_Method::scope_admin.'%'],
1389 1389
                     ],
1390 1390
                 ],
1391 1391
             ];
1392 1392
         } else {
1393
-            $query_args = [['PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%']]];
1393
+            $query_args = [['PMD_scope' => ['LIKE', '%'.EEM_Payment_Method::scope_admin.'%']]];
1394 1394
         }
1395 1395
         $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1396 1396
     }
@@ -1423,7 +1423,7 @@  discard block
 block discarded – undo
1423 1423
             'Line_Item',
1424 1424
             [['LIN_type' => 'line-item']]
1425 1425
         );
1426
-        if (! empty($line_items)) {
1426
+        if ( ! empty($line_items)) {
1427 1427
             foreach ($line_items as $item) {
1428 1428
                 if ($item instanceof EE_Line_Item) {
1429 1429
                     switch ($item->OBJ_type()) {
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                             $ticket = $item->ticket();
1434 1434
                             // right now we're only handling tickets here.
1435 1435
                             // Cause its expected that only tickets will have attendees right?
1436
-                            if (! $ticket instanceof EE_Ticket) {
1436
+                            if ( ! $ticket instanceof EE_Ticket) {
1437 1437
                                 break;
1438 1438
                             }
1439 1439
                             try {
@@ -1442,45 +1442,45 @@  discard block
 block discarded – undo
1442 1442
                                 EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1443 1443
                                 $event_name = esc_html__('Unknown Event', 'event_espresso');
1444 1444
                             }
1445
-                            $event_name   .= ' - ' . $item->name();
1445
+                            $event_name   .= ' - '.$item->name();
1446 1446
                             $ticket_price = EEH_Template::format_currency($item->unit_price());
1447 1447
                             // now get all of the registrations for this transaction that use this ticket
1448 1448
                             $registrations = $ticket->registrations(
1449 1449
                                 [['TXN_ID' => $this->_transaction->ID()]]
1450 1450
                             );
1451 1451
                             foreach ($registrations as $registration) {
1452
-                                if (! $registration instanceof EE_Registration) {
1452
+                                if ( ! $registration instanceof EE_Registration) {
1453 1453
                                     break;
1454 1454
                                 }
1455
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1455
+                                $this->_template_args['event_attendees'][$registration->ID()]['STS_ID']
1456 1456
                                     = $registration->status_ID();
1457
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1457
+                                $this->_template_args['event_attendees'][$registration->ID()]['att_num']
1458 1458
                                     = $registration->count();
1459
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1459
+                                $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name']
1460 1460
                                     = $event_name;
1461
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1461
+                                $this->_template_args['event_attendees'][$registration->ID()]['ticket_price']
1462 1462
                                     = $ticket_price;
1463 1463
                                 // attendee info
1464 1464
                                 $attendee = $registration->get_first_related('Attendee');
1465 1465
                                 if ($attendee instanceof EE_Attendee) {
1466
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1466
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']
1467 1467
                                         = $attendee->ID();
1468
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1468
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee']
1469 1469
                                         = $attendee->full_name();
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1471
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1470
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email']
1471
+                                        = '<a href="mailto:'.$attendee->email().'?subject='.$event_name
1472 1472
                                           . esc_html__(
1473 1473
                                               ' Event',
1474 1474
                                               'event_espresso'
1475 1475
                                           )
1476
-                                          . '">' . $attendee->email() . '</a>';
1477
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1476
+                                          . '">'.$attendee->email().'</a>';
1477
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address']
1478 1478
                                         = EEH_Address::format($attendee, 'inline', false, false);
1479 1479
                                 } else {
1480
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']   = '';
1481
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1482
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']    = '';
1483
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']  = '';
1480
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']   = '';
1481
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1482
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email']    = '';
1483
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address']  = '';
1484 1484
                                 }
1485 1485
                             }
1486 1486
                             break;
@@ -1496,7 +1496,7 @@  discard block
 block discarded – undo
1496 1496
                 TXN_ADMIN_URL
1497 1497
             );
1498 1498
             echo EEH_Template::display_template(
1499
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1499
+                TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_attendees.template.php',
1500 1500
                 $this->_template_args,
1501 1501
                 true
1502 1502
             );
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
         $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1532 1532
             ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1533 1533
             : null;
1534
-        if (! $primary_att instanceof EE_Attendee) {
1534
+        if ( ! $primary_att instanceof EE_Attendee) {
1535 1535
             $this->_template_args['no_attendee_message'] = esc_html__(
1536 1536
                 'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1537 1537
                 'event_espresso'
@@ -1553,7 +1553,7 @@  discard block
 block discarded – undo
1553 1553
         // get formatted address for registrant
1554 1554
         $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1555 1555
         echo EEH_Template::display_template(
1556
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1556
+            TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_registrant.template.php',
1557 1557
             $this->_template_args,
1558 1558
             true
1559 1559
         );
@@ -1579,7 +1579,7 @@  discard block
 block discarded – undo
1579 1579
             TXN_ADMIN_URL
1580 1580
         );
1581 1581
 
1582
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1582
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_billing_info.template.php';
1583 1583
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1584 1584
     }
1585 1585
 
@@ -1605,7 +1605,7 @@  discard block
 block discarded – undo
1605 1605
             'ee_edit_payments',
1606 1606
             'apply_payment_or_refund_from_registration_details'
1607 1607
         );
1608
-        if (! empty($valid_data) && $has_access) {
1608
+        if ( ! empty($valid_data) && $has_access) {
1609 1609
             $PAY_ID = $valid_data['PAY_ID'];
1610 1610
             // save  the new payment
1611 1611
             $payment = $this->_create_payment_from_request_data($valid_data);
@@ -1618,7 +1618,7 @@  discard block
 block discarded – undo
1618 1618
                 $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1619 1619
                 $this->_remove_existing_registration_payments($payment, $PAY_ID);
1620 1620
                 // apply payment to registrations (if applicable)
1621
-                if (! empty($REG_IDs)) {
1621
+                if ( ! empty($REG_IDs)) {
1622 1622
                     $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1623 1623
                     $this->_maybe_send_notifications();
1624 1624
                     // now process status changes for the same registrations
@@ -1664,7 +1664,7 @@  discard block
 block discarded – undo
1664 1664
                 __LINE__
1665 1665
             );
1666 1666
         }
1667
-        $notices              = EE_Error::get_notices(
1667
+        $notices = EE_Error::get_notices(
1668 1668
             false,
1669 1669
             false,
1670 1670
             false
@@ -1689,14 +1689,14 @@  discard block
 block discarded – undo
1689 1689
      */
1690 1690
     protected function _validate_payment_request_data()
1691 1691
     {
1692
-        if (! $this->request->requestParamIsSet('txn_admin_payment')) {
1692
+        if ( ! $this->request->requestParamIsSet('txn_admin_payment')) {
1693 1693
             return [];
1694 1694
         }
1695 1695
         $payment_form = $this->_generate_payment_form_section();
1696 1696
         try {
1697 1697
             if ($payment_form->was_submitted()) {
1698 1698
                 $payment_form->receive_form_submission();
1699
-                if (! $payment_form->is_valid()) {
1699
+                if ( ! $payment_form->is_valid()) {
1700 1700
                     $submission_error_messages = [];
1701 1701
                     foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1702 1702
                         if ($validation_error instanceof EE_Validation_Error) {
@@ -1878,7 +1878,7 @@  discard block
 block discarded – undo
1878 1878
             ['Y-m-d', 'g:i a']
1879 1879
         );
1880 1880
 
1881
-        if (! $payment->save()) {
1881
+        if ( ! $payment->save()) {
1882 1882
             EE_Error::add_error(
1883 1883
                 sprintf(
1884 1884
                     esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
@@ -2080,12 +2080,12 @@  discard block
 block discarded – undo
2080 2080
         // but add in some conditions regarding payment,
2081 2081
         // so that we don't apply payments to registrations that are free or have already been paid for
2082 2082
         // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2083
-        if (! $payment->is_a_refund()) {
2083
+        if ( ! $payment->is_a_refund()) {
2084 2084
             $registration_query_where_params['REG_final_price']  = ['!=', 0];
2085 2085
             $registration_query_where_params['REG_final_price*'] = ['!=', 'REG_paid', true];
2086 2086
         }
2087 2087
         $registrations = $transaction->registrations([$registration_query_where_params]);
2088
-        if (! empty($registrations)) {
2088
+        if ( ! empty($registrations)) {
2089 2089
             /** @type EE_Payment_Processor $payment_processor */
2090 2090
             $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2091 2091
             $payment_processor->process_registration_payments($transaction, $payment, $registrations);
@@ -2167,7 +2167,7 @@  discard block
 block discarded – undo
2167 2167
             'pay_status'       => $payment->STS_ID(),
2168 2168
             'PAY_ID'           => $payment->ID(),
2169 2169
             'STS_ID'           => $payment->STS_ID(),
2170
-            'status'           => self::$_pay_status[ $payment->STS_ID() ],
2170
+            'status'           => self::$_pay_status[$payment->STS_ID()],
2171 2171
             'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2172 2172
             'method'           => strtoupper($payment->source()),
2173 2173
             'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
@@ -2286,11 +2286,11 @@  discard block
 block discarded – undo
2286 2286
     {
2287 2287
         $registration_payment_data = [];
2288 2288
         // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2289
-        if (! empty($REG_IDs)) {
2289
+        if ( ! empty($REG_IDs)) {
2290 2290
             $registrations = EEM_Registration::instance()->get_all([['REG_ID' => ['IN', $REG_IDs]]]);
2291 2291
             foreach ($registrations as $registration) {
2292 2292
                 if ($registration instanceof EE_Registration) {
2293
-                    $registration_payment_data[ $registration->ID() ] = [
2293
+                    $registration_payment_data[$registration->ID()] = [
2294 2294
                         'paid'  => $registration->pretty_paid(),
2295 2295
                         'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2296 2296
                     ];
@@ -2346,7 +2346,7 @@  discard block
 block discarded – undo
2346 2346
         $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2347 2347
         $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2348 2348
         $redirect_to = $this->request->getRequestParam('redirect_to');
2349
-        $query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2349
+        $query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID, ] : [];
2350 2350
         do_action(
2351 2351
             'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2352 2352
             $transaction
@@ -2384,8 +2384,8 @@  discard block
 block discarded – undo
2384 2384
         );
2385 2385
 
2386 2386
         // make sure our timestamps start and end right at the boundaries for each day
2387
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2388
-        $end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2387
+        $start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00';
2388
+        $end_date   = date('Y-m-d', strtotime($end_date)).' 23:59:59';
2389 2389
 
2390 2390
 
2391 2391
         // convert to timestamps
@@ -2402,7 +2402,7 @@  discard block
 block discarded – undo
2402 2402
             date('Y-m-d H:i:s', $start_date),
2403 2403
             'Y-m-d H:i:s'
2404 2404
         );
2405
-        $end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2405
+        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2406 2406
             'TXN_timestamp',
2407 2407
             date('Y-m-d H:i:s', $end_date),
2408 2408
             'Y-m-d H:i:s'
@@ -2446,8 +2446,8 @@  discard block
 block discarded – undo
2446 2446
 
2447 2447
         $search_term = $this->request->getRequestParam('s');
2448 2448
         if ($search_term) {
2449
-            $search_term = '%' . $search_term . '%';
2450
-            $_where['OR']  = [
2449
+            $search_term = '%'.$search_term.'%';
2450
+            $_where['OR'] = [
2451 2451
                 'Registration.Event.EVT_name'         => ['LIKE', $search_term],
2452 2452
                 'Registration.Event.EVT_desc'         => ['LIKE', $search_term],
2453 2453
                 'Registration.Event.EVT_short_desc'   => ['LIKE', $search_term],
@@ -2474,9 +2474,9 @@  discard block
 block discarded – undo
2474 2474
 
2475 2475
         $status = $this->request->getRequestParam('status');
2476 2476
         // failed transactions
2477
-        $failed     = (! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2478
-        $abandoned  = (! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2479
-        $incomplete = (! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2477
+        $failed     = ( ! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2478
+        $abandoned  = ( ! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2479
+        $incomplete = ( ! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2480 2480
 
2481 2481
         if ($failed) {
2482 2482
             $_where['STS_ID'] = EEM_Transaction::failed_status_code;
@@ -2524,7 +2524,7 @@  discard block
 block discarded – undo
2524 2524
         $transaction     = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2525 2525
         $success         = $transaction->recalculateLineItems();
2526 2526
         $redirect_to = $this->request->getRequestParam('redirect_to');
2527
-        $query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2527
+        $query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID, ] : [];
2528 2528
         $this->_redirect_after_action(
2529 2529
             $success,
2530 2530
             esc_html__('Transaction taxes and totals', 'event_espresso'),
Please login to merge, or discard this patch.
templates/txn_admin_details_side_meta_box_registrant.template.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -54,14 +54,14 @@
 block discarded – undo
54 54
     </div> <!-- end #admin-side-mbox-primary-registrant-dv -->
55 55
 
56 56
     <?php
57
-    // only show if logged-in user has access
58
-    if (
59
-        EE_Registry::instance()->CAP->current_user_can(
60
-            'ee_edit_contact',
61
-            'view_or_edit_contact_button',
62
-            $ATT_ID
63
-        )
64
-    ) : ?>
57
+	// only show if logged-in user has access
58
+	if (
59
+		EE_Registry::instance()->CAP->current_user_can(
60
+			'ee_edit_contact',
61
+			'view_or_edit_contact_button',
62
+			$ATT_ID
63
+		)
64
+	) : ?>
65 65
         <p style="text-align:right;">
66 66
             <a class="button button-small" href="<?php echo esc_url_raw($edit_attendee_url); ?>"
67 67
                aria-label="<?php esc_attr_e('View details for this contact.', 'event_espresso'); ?>"
Please login to merge, or discard this patch.