Completed
Branch dev (f8b79a)
by
unknown
12:18 queued 04:53
created
admin_pages/events/Events_Admin_Page.core.php 2 patches
Indentation   +2921 added lines, -2921 removed lines patch added patch discarded remove patch
@@ -16,2928 +16,2928 @@
 block discarded – undo
16 16
  */
17 17
 class Events_Admin_Page extends EE_Admin_Page_CPT
18 18
 {
19
-    /**
20
-     * This will hold the event object for event_details screen.
19
+	/**
20
+	 * This will hold the event object for event_details screen.
21
+	 *
22
+	 * @var EE_Event $_event
23
+	 */
24
+	protected $_event;
25
+
26
+
27
+	/**
28
+	 * This will hold the category object for category_details screen.
29
+	 *
30
+	 * @var stdClass $_category
31
+	 */
32
+	protected $_category;
33
+
34
+
35
+	/**
36
+	 * This will hold the event model instance
37
+	 *
38
+	 * @var EEM_Event $_event_model
39
+	 */
40
+	protected $_event_model;
41
+
42
+
43
+	/**
44
+	 * @var EE_Event
45
+	 */
46
+	protected $_cpt_model_obj = false;
47
+
48
+
49
+	/**
50
+	 * @var NodeGroupDao
51
+	 */
52
+	protected $model_obj_node_group_persister;
53
+
54
+	/**
55
+	 * @var AdvancedEditorAdminFormSection
56
+	 */
57
+	protected $advanced_editor_admin_form;
58
+
59
+
60
+	/**
61
+	 * Initialize page props for this admin page group.
62
+	 */
63
+	protected function _init_page_props()
64
+	{
65
+		$this->page_slug        = EVENTS_PG_SLUG;
66
+		$this->page_label       = EVENTS_LABEL;
67
+		$this->_admin_base_url  = EVENTS_ADMIN_URL;
68
+		$this->_admin_base_path = EVENTS_ADMIN;
69
+		$this->_cpt_model_names = [
70
+			'create_new' => 'EEM_Event',
71
+			'edit'       => 'EEM_Event',
72
+		];
73
+		$this->_cpt_edit_routes = [
74
+			'espresso_events' => 'edit',
75
+		];
76
+		add_action(
77
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
78
+			[$this, 'verify_event_edit'],
79
+			10,
80
+			2
81
+		);
82
+	}
83
+
84
+
85
+	/**
86
+	 * Sets the ajax hooks used for this admin page group.
87
+	 */
88
+	protected function _ajax_hooks()
89
+	{
90
+		add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Sets the page properties for this admin page group.
96
+	 */
97
+	protected function _define_page_props()
98
+	{
99
+		$this->_admin_page_title = EVENTS_LABEL;
100
+		$this->_labels           = [
101
+			'buttons'      => [
102
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
103
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
104
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
105
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
106
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
107
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
108
+			],
109
+			'editor_title' => [
110
+				'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
111
+			],
112
+			'publishbox'   => [
113
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
114
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
115
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
116
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
117
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
118
+			],
119
+		];
120
+	}
121
+
122
+
123
+	/**
124
+	 * Sets the page routes property for this admin page group.
125
+	 */
126
+	protected function _set_page_routes()
127
+	{
128
+		// load formatter helper
129
+		// load field generator helper
130
+		// is there a evt_id in the request?
131
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
132
+		$EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
133
+
134
+		$this->_page_routes = [
135
+			'default'                       => [
136
+				'func'       => '_events_overview_list_table',
137
+				'capability' => 'ee_read_events',
138
+			],
139
+			'create_new'                    => [
140
+				'func'       => '_create_new_cpt_item',
141
+				'capability' => 'ee_edit_events',
142
+			],
143
+			'edit'                          => [
144
+				'func'       => '_edit_cpt_item',
145
+				'capability' => 'ee_edit_event',
146
+				'obj_id'     => $EVT_ID,
147
+			],
148
+			'copy_event'                    => [
149
+				'func'       => '_copy_events',
150
+				'capability' => 'ee_edit_event',
151
+				'obj_id'     => $EVT_ID,
152
+				'noheader'   => true,
153
+			],
154
+			'trash_event'                   => [
155
+				'func'       => '_trash_or_restore_event',
156
+				'args'       => ['event_status' => 'trash'],
157
+				'capability' => 'ee_delete_event',
158
+				'obj_id'     => $EVT_ID,
159
+				'noheader'   => true,
160
+			],
161
+			'trash_events'                  => [
162
+				'func'       => '_trash_or_restore_events',
163
+				'args'       => ['event_status' => 'trash'],
164
+				'capability' => 'ee_delete_events',
165
+				'noheader'   => true,
166
+			],
167
+			'restore_event'                 => [
168
+				'func'       => '_trash_or_restore_event',
169
+				'args'       => ['event_status' => 'draft'],
170
+				'capability' => 'ee_delete_event',
171
+				'obj_id'     => $EVT_ID,
172
+				'noheader'   => true,
173
+			],
174
+			'restore_events'                => [
175
+				'func'       => '_trash_or_restore_events',
176
+				'args'       => ['event_status' => 'draft'],
177
+				'capability' => 'ee_delete_events',
178
+				'noheader'   => true,
179
+			],
180
+			'delete_event'                  => [
181
+				'func'       => '_delete_event',
182
+				'capability' => 'ee_delete_event',
183
+				'obj_id'     => $EVT_ID,
184
+				'noheader'   => true,
185
+			],
186
+			'delete_events'                 => [
187
+				'func'       => '_delete_events',
188
+				'capability' => 'ee_delete_events',
189
+				'noheader'   => true,
190
+			],
191
+			'view_report'                   => [
192
+				'func'       => '_view_report',
193
+				'capability' => 'ee_edit_events',
194
+			],
195
+			'default_event_settings'        => [
196
+				'func'       => '_default_event_settings',
197
+				'capability' => 'manage_options',
198
+			],
199
+			'update_default_event_settings' => [
200
+				'func'       => '_update_default_event_settings',
201
+				'capability' => 'manage_options',
202
+				'noheader'   => true,
203
+			],
204
+			'template_settings'             => [
205
+				'func'       => '_template_settings',
206
+				'capability' => 'manage_options',
207
+			],
208
+			// event category tab related
209
+			'add_category'                  => [
210
+				'func'       => '_category_details',
211
+				'capability' => 'ee_edit_event_category',
212
+				'args'       => ['add'],
213
+			],
214
+			'edit_category'                 => [
215
+				'func'       => '_category_details',
216
+				'capability' => 'ee_edit_event_category',
217
+				'args'       => ['edit'],
218
+			],
219
+			'delete_categories'             => [
220
+				'func'       => '_delete_categories',
221
+				'capability' => 'ee_delete_event_category',
222
+				'noheader'   => true,
223
+			],
224
+			'delete_category'               => [
225
+				'func'       => '_delete_categories',
226
+				'capability' => 'ee_delete_event_category',
227
+				'noheader'   => true,
228
+			],
229
+			'insert_category'               => [
230
+				'func'       => '_insert_or_update_category',
231
+				'args'       => ['new_category' => true],
232
+				'capability' => 'ee_edit_event_category',
233
+				'noheader'   => true,
234
+			],
235
+			'update_category'               => [
236
+				'func'       => '_insert_or_update_category',
237
+				'args'       => ['new_category' => false],
238
+				'capability' => 'ee_edit_event_category',
239
+				'noheader'   => true,
240
+			],
241
+			'category_list'                 => [
242
+				'func'       => '_category_list_table',
243
+				'capability' => 'ee_manage_event_categories',
244
+			],
245
+			'preview_deletion'              => [
246
+				'func'       => 'previewDeletion',
247
+				'capability' => 'ee_delete_events',
248
+			],
249
+			'confirm_deletion'              => [
250
+				'func'       => 'confirmDeletion',
251
+				'capability' => 'ee_delete_events',
252
+				'noheader'   => true,
253
+			],
254
+		];
255
+	}
256
+
257
+
258
+	/**
259
+	 * Set the _page_config property for this admin page group.
260
+	 */
261
+	protected function _set_page_config()
262
+	{
263
+		$post_id            = $this->request->getRequestParam('post', 0, 'int');
264
+		$EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
265
+		$this->_page_config = [
266
+			'default'                => [
267
+				'nav'           => [
268
+					'label' => esc_html__('Overview', 'event_espresso'),
269
+					'icon' => 'dashicons-list-view',
270
+					'order' => 10,
271
+				],
272
+				'list_table'    => 'Events_Admin_List_Table',
273
+				'help_tabs'     => [
274
+					'events_overview_help_tab'                       => [
275
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
276
+						'filename' => 'events_overview',
277
+					],
278
+					'events_overview_table_column_headings_help_tab' => [
279
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
280
+						'filename' => 'events_overview_table_column_headings',
281
+					],
282
+					'events_overview_filters_help_tab'               => [
283
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
284
+						'filename' => 'events_overview_filters',
285
+					],
286
+					'events_overview_view_help_tab'                  => [
287
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
288
+						'filename' => 'events_overview_views',
289
+					],
290
+					'events_overview_other_help_tab'                 => [
291
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
292
+						'filename' => 'events_overview_other',
293
+					],
294
+				],
295
+				'require_nonce' => false,
296
+			],
297
+			'create_new'             => [
298
+				'nav'           => [
299
+					'label'      => esc_html__('Add New Event', 'event_espresso'),
300
+					'icon' => 'dashicons-plus-alt',
301
+					'order'      => 15,
302
+					'persistent' => false,
303
+				],
304
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
305
+				'help_tabs'     => [
306
+					'event_editor_help_tab'                            => [
307
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
308
+						'filename' => 'event_editor',
309
+					],
310
+					'event_editor_title_richtexteditor_help_tab'       => [
311
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
312
+						'filename' => 'event_editor_title_richtexteditor',
313
+					],
314
+					'event_editor_venue_details_help_tab'              => [
315
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
316
+						'filename' => 'event_editor_venue_details',
317
+					],
318
+					'event_editor_event_datetimes_help_tab'            => [
319
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
320
+						'filename' => 'event_editor_event_datetimes',
321
+					],
322
+					'event_editor_event_tickets_help_tab'              => [
323
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
324
+						'filename' => 'event_editor_event_tickets',
325
+					],
326
+					'event_editor_event_registration_options_help_tab' => [
327
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
328
+						'filename' => 'event_editor_event_registration_options',
329
+					],
330
+					'event_editor_tags_categories_help_tab'            => [
331
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
332
+						'filename' => 'event_editor_tags_categories',
333
+					],
334
+					'event_editor_questions_registrants_help_tab'      => [
335
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
336
+						'filename' => 'event_editor_questions_registrants',
337
+					],
338
+					'event_editor_save_new_event_help_tab'             => [
339
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
340
+						'filename' => 'event_editor_save_new_event',
341
+					],
342
+					'event_editor_other_help_tab'                      => [
343
+						'title'    => esc_html__('Event Other', 'event_espresso'),
344
+						'filename' => 'event_editor_other',
345
+					],
346
+				],
347
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
348
+				'require_nonce' => false,
349
+			],
350
+			'edit'                   => [
351
+				'nav'           => [
352
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
353
+					'icon' => 'dashicons-edit',
354
+					'order'      => 15,
355
+					'persistent' => false,
356
+					'url'        => $post_id
357
+						? EE_Admin_Page::add_query_args_and_nonce(
358
+							['post' => $post_id, 'action' => 'edit'],
359
+							$this->_current_page_view_url
360
+						)
361
+						: $this->_admin_base_url,
362
+				],
363
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
364
+				'help_tabs'     => [
365
+					'event_editor_help_tab'                            => [
366
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
367
+						'filename' => 'event_editor',
368
+					],
369
+					'event_editor_title_richtexteditor_help_tab'       => [
370
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
371
+						'filename' => 'event_editor_title_richtexteditor',
372
+					],
373
+					'event_editor_venue_details_help_tab'              => [
374
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
375
+						'filename' => 'event_editor_venue_details',
376
+					],
377
+					'event_editor_event_datetimes_help_tab'            => [
378
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
379
+						'filename' => 'event_editor_event_datetimes',
380
+					],
381
+					'event_editor_event_tickets_help_tab'              => [
382
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
383
+						'filename' => 'event_editor_event_tickets',
384
+					],
385
+					'event_editor_event_registration_options_help_tab' => [
386
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
387
+						'filename' => 'event_editor_event_registration_options',
388
+					],
389
+					'event_editor_tags_categories_help_tab'            => [
390
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
391
+						'filename' => 'event_editor_tags_categories',
392
+					],
393
+					'event_editor_questions_registrants_help_tab'      => [
394
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
395
+						'filename' => 'event_editor_questions_registrants',
396
+					],
397
+					'event_editor_save_new_event_help_tab'             => [
398
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
399
+						'filename' => 'event_editor_save_new_event',
400
+					],
401
+					'event_editor_other_help_tab'                      => [
402
+						'title'    => esc_html__('Event Other', 'event_espresso'),
403
+						'filename' => 'event_editor_other',
404
+					],
405
+				],
406
+				'require_nonce' => false,
407
+			],
408
+			'default_event_settings' => [
409
+				'nav'           => [
410
+					'label' => esc_html__('Default Settings', 'event_espresso'),
411
+					'icon' => 'dashicons-admin-generic',
412
+					'order' => 40,
413
+				],
414
+				'metaboxes'     => array_merge(['_publish_post_box'], $this->_default_espresso_metaboxes),
415
+				'labels'        => [
416
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
417
+				],
418
+				'help_tabs'     => [
419
+					'default_settings_help_tab'        => [
420
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
421
+						'filename' => 'events_default_settings',
422
+					],
423
+					'default_settings_status_help_tab' => [
424
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
425
+						'filename' => 'events_default_settings_status',
426
+					],
427
+					'default_maximum_tickets_help_tab' => [
428
+						'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
429
+						'filename' => 'events_default_settings_max_tickets',
430
+					],
431
+				],
432
+				'require_nonce' => false,
433
+			],
434
+			// template settings
435
+			'template_settings'      => [
436
+				'nav'           => [
437
+					'label' => esc_html__('Templates', 'event_espresso'),
438
+					'icon' => 'dashicons-layout',
439
+					'order' => 30,
440
+				],
441
+				'metaboxes'     => $this->_default_espresso_metaboxes,
442
+				'help_tabs'     => [
443
+					'general_settings_templates_help_tab' => [
444
+						'title'    => esc_html__('Templates', 'event_espresso'),
445
+						'filename' => 'general_settings_templates',
446
+					],
447
+				],
448
+				'require_nonce' => false,
449
+			],
450
+			// event category stuff
451
+			'add_category'           => [
452
+				'nav'           => [
453
+					'label'      => esc_html__('Add Category', 'event_espresso'),
454
+					'icon' => 'dashicons-plus-alt',
455
+					'order'      => 25,
456
+					'persistent' => false,
457
+				],
458
+				'help_tabs'     => [
459
+					'add_category_help_tab' => [
460
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
461
+						'filename' => 'events_add_category',
462
+					],
463
+				],
464
+				'metaboxes'     => ['_publish_post_box'],
465
+				'require_nonce' => false,
466
+			],
467
+			'edit_category'          => [
468
+				'nav'           => [
469
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
470
+					'icon' => 'dashicons-edit',
471
+					'order'      => 25,
472
+					'persistent' => false,
473
+					'url'        => $EVT_CAT_ID
474
+						? add_query_arg(
475
+							['EVT_CAT_ID' => $EVT_CAT_ID],
476
+							$this->_current_page_view_url
477
+						)
478
+						: $this->_admin_base_url,
479
+				],
480
+				'help_tabs'     => [
481
+					'edit_category_help_tab' => [
482
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
483
+						'filename' => 'events_edit_category',
484
+					],
485
+				],
486
+				'metaboxes'     => ['_publish_post_box'],
487
+				'require_nonce' => false,
488
+			],
489
+			'category_list'          => [
490
+				'nav'           => [
491
+					'label' => esc_html__('Categories', 'event_espresso'),
492
+					'icon' => 'dashicons-networking',
493
+					'order' => 20,
494
+				],
495
+				'list_table'    => 'Event_Categories_Admin_List_Table',
496
+				'help_tabs'     => [
497
+					'events_categories_help_tab'                       => [
498
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
499
+						'filename' => 'events_categories',
500
+					],
501
+					'events_categories_table_column_headings_help_tab' => [
502
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
503
+						'filename' => 'events_categories_table_column_headings',
504
+					],
505
+					'events_categories_view_help_tab'                  => [
506
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
507
+						'filename' => 'events_categories_views',
508
+					],
509
+					'events_categories_other_help_tab'                 => [
510
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
511
+						'filename' => 'events_categories_other',
512
+					],
513
+				],
514
+				'metaboxes'     => $this->_default_espresso_metaboxes,
515
+				'require_nonce' => false,
516
+			],
517
+			'preview_deletion'       => [
518
+				'nav'           => [
519
+					'label'      => esc_html__('Preview Deletion', 'event_espresso'),
520
+					'icon' => 'dashicons-remove',
521
+					'order'      => 15,
522
+					'persistent' => false,
523
+					'url'        => '',
524
+				],
525
+				'require_nonce' => false,
526
+			],
527
+		];
528
+	}
529
+
530
+
531
+	/**
532
+	 * Used to register any global screen options if necessary for every route in this admin page group.
533
+	 */
534
+	protected function _add_screen_options()
535
+	{
536
+	}
537
+
538
+
539
+	/**
540
+	 * Implementing the screen options for the 'default' route.
541
+	 *
542
+	 * @throws InvalidArgumentException
543
+	 * @throws InvalidDataTypeException
544
+	 * @throws InvalidInterfaceException
545
+	 */
546
+	protected function _add_screen_options_default()
547
+	{
548
+		$this->_per_page_screen_option();
549
+	}
550
+
551
+
552
+	/**
553
+	 * Implementing screen options for the category list route.
554
+	 *
555
+	 * @throws InvalidArgumentException
556
+	 * @throws InvalidDataTypeException
557
+	 * @throws InvalidInterfaceException
558
+	 */
559
+	protected function _add_screen_options_category_list()
560
+	{
561
+		$page_title              = $this->_admin_page_title;
562
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
563
+		$this->_per_page_screen_option();
564
+		$this->_admin_page_title = $page_title;
565
+	}
566
+
567
+
568
+	/**
569
+	 * Used to register any global feature pointers for the admin page group.
570
+	 */
571
+	protected function _add_feature_pointers()
572
+	{
573
+	}
574
+
575
+
576
+	/**
577
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
578
+	 */
579
+	public function load_scripts_styles()
580
+	{
581
+		wp_register_style(
582
+			'events-admin-css',
583
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
584
+			[],
585
+			EVENT_ESPRESSO_VERSION
586
+		);
587
+		wp_register_style(
588
+			'ee-cat-admin',
589
+			EVENTS_ASSETS_URL . 'ee-cat-admin.css',
590
+			[],
591
+			EVENT_ESPRESSO_VERSION
592
+		);
593
+		wp_enqueue_style('events-admin-css');
594
+		wp_enqueue_style('ee-cat-admin');
595
+		// scripts
596
+		wp_register_script(
597
+			'event_editor_js',
598
+			EVENTS_ASSETS_URL . 'event_editor.js',
599
+			['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
600
+			EVENT_ESPRESSO_VERSION,
601
+			true
602
+		);
603
+	}
604
+
605
+
606
+	/**
607
+	 * Enqueuing scripts and styles specific to this view
608
+	 */
609
+	public function load_scripts_styles_create_new()
610
+	{
611
+		$this->load_scripts_styles_edit();
612
+	}
613
+
614
+
615
+	/**
616
+	 * Enqueuing scripts and styles specific to this view
617
+	 */
618
+	public function load_scripts_styles_edit()
619
+	{
620
+		// styles
621
+		wp_enqueue_style('espresso-ui-theme');
622
+		wp_register_style(
623
+			'event-editor-css',
624
+			EVENTS_ASSETS_URL . 'event-editor.css',
625
+			['ee-admin-css'],
626
+			EVENT_ESPRESSO_VERSION
627
+		);
628
+		wp_enqueue_style('event-editor-css');
629
+		// scripts
630
+		if (! $this->admin_config->useAdvancedEditor()) {
631
+			wp_register_script(
632
+				'event-datetime-metabox',
633
+				EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
634
+				['event_editor_js', 'ee-datepicker'],
635
+				EVENT_ESPRESSO_VERSION
636
+			);
637
+			wp_enqueue_script('event-datetime-metabox');
638
+		}
639
+	}
640
+
641
+
642
+	/**
643
+	 * Populating the _views property for the category list table view.
644
+	 */
645
+	protected function _set_list_table_views_category_list()
646
+	{
647
+		$this->_views = [
648
+			'all' => [
649
+				'slug'        => 'all',
650
+				'label'       => esc_html__('All', 'event_espresso'),
651
+				'count'       => 0,
652
+				'bulk_action' => [
653
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
654
+				],
655
+			],
656
+		];
657
+	}
658
+
659
+
660
+	/**
661
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
662
+	 */
663
+	public function admin_init()
664
+	{
665
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
666
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
667
+			'event_espresso'
668
+		);
669
+	}
670
+
671
+
672
+	/**
673
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
674
+	 * group.
675
+	 */
676
+	public function admin_notices()
677
+	{
678
+	}
679
+
680
+
681
+	/**
682
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
683
+	 * this admin page group.
684
+	 */
685
+	public function admin_footer_scripts()
686
+	{
687
+	}
688
+
689
+
690
+	/**
691
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
692
+	 * warning (via EE_Error::add_error());
693
+	 *
694
+	 * @param EE_Event $event Event object
695
+	 * @param string   $req_type
696
+	 * @return void
697
+	 * @throws EE_Error
698
+	 * @throws ReflectionException
699
+	 */
700
+	public function verify_event_edit($event = null, $req_type = '')
701
+	{
702
+		// don't need to do this when processing
703
+		if (! empty($req_type)) {
704
+			return;
705
+		}
706
+		// no event?
707
+		if (! $event instanceof EE_Event) {
708
+			$event = $this->_cpt_model_obj;
709
+		}
710
+		// STILL no event?
711
+		if (! $event instanceof EE_Event) {
712
+			return;
713
+		}
714
+		$orig_status = $event->status();
715
+		// first check if event is active.
716
+		if (
717
+			$orig_status === EEM_Event::cancelled
718
+			|| $orig_status === EEM_Event::postponed
719
+			|| $event->is_expired()
720
+			|| $event->is_inactive()
721
+		) {
722
+			return;
723
+		}
724
+		// made it here so it IS active... next check that any of the tickets are sold.
725
+		if ($event->is_sold_out(true)) {
726
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
727
+				EE_Error::add_attention(
728
+					sprintf(
729
+						esc_html__(
730
+							'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.',
731
+							'event_espresso'
732
+						),
733
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
734
+					)
735
+				);
736
+			}
737
+			return;
738
+		}
739
+		if ($orig_status === EEM_Event::sold_out) {
740
+			EE_Error::add_attention(
741
+				sprintf(
742
+					esc_html__(
743
+						'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.',
744
+						'event_espresso'
745
+					),
746
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
747
+				)
748
+			);
749
+		}
750
+		// now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
751
+		if (! $event->tickets_on_sale()) {
752
+			return;
753
+		}
754
+		// made it here so show warning
755
+		$this->_edit_event_warning();
756
+	}
757
+
758
+
759
+	/**
760
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
761
+	 * When needed, hook this into a EE_Error::add_error() notice.
762
+	 *
763
+	 * @access protected
764
+	 * @return void
765
+	 */
766
+	protected function _edit_event_warning()
767
+	{
768
+		// we don't want to add warnings during these requests
769
+		if ($this->request->getRequestParam('action') === 'editpost') {
770
+			return;
771
+		}
772
+		EE_Error::add_attention(
773
+			sprintf(
774
+				esc_html__(
775
+					'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
776
+					'event_espresso'
777
+				),
778
+				'<a class="espresso-help-tab-lnk ee-help-tab-link">',
779
+				'</a>'
780
+			)
781
+		);
782
+	}
783
+
784
+
785
+	/**
786
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
787
+	 * Otherwise, do the normal logic
788
+	 *
789
+	 * @return void
790
+	 * @throws EE_Error
791
+	 * @throws InvalidArgumentException
792
+	 * @throws InvalidDataTypeException
793
+	 * @throws InvalidInterfaceException
794
+	 */
795
+	protected function _create_new_cpt_item()
796
+	{
797
+		$has_timezone_string = get_option('timezone_string');
798
+		// only nag them about setting their timezone if it's their first event, and they haven't already done it
799
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
800
+			EE_Error::add_attention(
801
+				sprintf(
802
+					esc_html__(
803
+						'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',
804
+						'event_espresso'
805
+					),
806
+					'<br>',
807
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
808
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
809
+					. '</select>',
810
+					'<button class="button button--secondary timezone-submit">',
811
+					'</button><span class="spinner"></span>'
812
+				),
813
+				__FILE__,
814
+				__FUNCTION__,
815
+				__LINE__
816
+			);
817
+		}
818
+		parent::_create_new_cpt_item();
819
+	}
820
+
821
+
822
+	/**
823
+	 * Sets the _views property for the default route in this admin page group.
824
+	 */
825
+	protected function _set_list_table_views_default()
826
+	{
827
+		$this->_views = [
828
+			'all'   => [
829
+				'slug'        => 'all',
830
+				'label'       => esc_html__('View All Events', 'event_espresso'),
831
+				'count'       => 0,
832
+				'bulk_action' => [
833
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
834
+				],
835
+			],
836
+			'draft' => [
837
+				'slug'        => 'draft',
838
+				'label'       => esc_html__('Draft', 'event_espresso'),
839
+				'count'       => 0,
840
+				'bulk_action' => [
841
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
842
+				],
843
+			],
844
+		];
845
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
846
+			$this->_views['trash'] = [
847
+				'slug'        => 'trash',
848
+				'label'       => esc_html__('Trash', 'event_espresso'),
849
+				'count'       => 0,
850
+				'bulk_action' => [
851
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
852
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
853
+				],
854
+			];
855
+		}
856
+	}
857
+
858
+
859
+	/**
860
+	 * Provides the legend item array for the default list table view.
861
+	 *
862
+	 * @return array
863
+	 * @throws EE_Error
864
+	 * @throws EE_Error
865
+	 */
866
+	protected function _event_legend_items()
867
+	{
868
+		$items    = [
869
+			'view_details'   => [
870
+				'class' => 'dashicons dashicons-visibility',
871
+				'desc'  => esc_html__('View Event', 'event_espresso'),
872
+			],
873
+			'edit_event'     => [
874
+				'class' => 'dashicons dashicons-calendar-alt',
875
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
876
+			],
877
+			'view_attendees' => [
878
+				'class' => 'dashicons dashicons-groups',
879
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
880
+			],
881
+		];
882
+		$items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
883
+		$statuses = [
884
+			'sold_out_status'  => [
885
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::sold_out,
886
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
887
+			],
888
+			'active_status'    => [
889
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::active,
890
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
891
+			],
892
+			'upcoming_status'  => [
893
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::upcoming,
894
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
895
+			],
896
+			'postponed_status' => [
897
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::postponed,
898
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
899
+			],
900
+			'cancelled_status' => [
901
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::cancelled,
902
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
903
+			],
904
+			'expired_status'   => [
905
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::expired,
906
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
907
+			],
908
+			'inactive_status'  => [
909
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::inactive,
910
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
911
+			],
912
+		];
913
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
914
+		return array_merge($items, $statuses);
915
+	}
916
+
917
+
918
+	/**
919
+	 * @return EEM_Event
920
+	 * @throws EE_Error
921
+	 * @throws InvalidArgumentException
922
+	 * @throws InvalidDataTypeException
923
+	 * @throws InvalidInterfaceException
924
+	 * @throws ReflectionException
925
+	 */
926
+	private function _event_model()
927
+	{
928
+		if (! $this->_event_model instanceof EEM_Event) {
929
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
930
+		}
931
+		return $this->_event_model;
932
+	}
933
+
934
+
935
+	/**
936
+	 * Adds extra buttons to the WP CPT permalink field row.
937
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
938
+	 *
939
+	 * @param string $return    the current html
940
+	 * @param int    $id        the post id for the page
941
+	 * @param string $new_title What the title is
942
+	 * @param string $new_slug  what the slug is
943
+	 * @return string            The new html string for the permalink area
944
+	 */
945
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
946
+	{
947
+		// make sure this is only when editing
948
+		if (! empty($id)) {
949
+			$post = get_post($id);
950
+			$return .= '<a class="button button--small button--secondary" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
951
+					   . esc_html__('Shortcode', 'event_espresso')
952
+					   . '</a> ';
953
+			$return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
954
+					   . $post->ID
955
+					   . ']">';
956
+		}
957
+		return $return;
958
+	}
959
+
960
+
961
+	/**
962
+	 * _events_overview_list_table
963
+	 * This contains the logic for showing the events_overview list
964
+	 *
965
+	 * @access protected
966
+	 * @return void
967
+	 * @throws DomainException
968
+	 * @throws EE_Error
969
+	 * @throws InvalidArgumentException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws InvalidInterfaceException
972
+	 */
973
+	protected function _events_overview_list_table()
974
+	{
975
+		$after_list_table                           = [];
976
+		$links_html = EEH_HTML::div('', '', 'ee-admin-section ee-layout-stack');
977
+		$links_html .= EEH_HTML::h3(esc_html__('Links', 'event_espresso'));
978
+		$links_html .= EEH_HTML::div(
979
+			EEH_Template::get_button_or_link(
980
+				get_post_type_archive_link('espresso_events'),
981
+				esc_html__('View Event Archive Page', 'event_espresso'),
982
+				'button button--small button--secondary'
983
+			),
984
+			'',
985
+			'ee-admin-button-row ee-admin-button-row--align-start'
986
+		);
987
+		$links_html .= EEH_HTML::divx();
988
+
989
+		$after_list_table['view_event_list_button'] = $links_html;
990
+
991
+		$after_list_table['legend'] = $this->_display_legend($this->_event_legend_items());
992
+		$this->_admin_page_title                    .= ' ' . $this->get_action_link_or_button(
993
+			'create_new',
994
+			'add',
995
+			[],
996
+			'add-new-h2'
997
+		);
998
+
999
+		$this->_template_args['after_list_table']   = array_merge(
1000
+			(array) $this->_template_args['after_list_table'],
1001
+			$after_list_table
1002
+		);
1003
+		$this->display_admin_list_table_page_with_no_sidebar();
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * this allows for extra misc actions in the default WP publish box
1009
+	 *
1010
+	 * @return void
1011
+	 * @throws DomainException
1012
+	 * @throws EE_Error
1013
+	 * @throws InvalidArgumentException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws InvalidInterfaceException
1016
+	 * @throws ReflectionException
1017
+	 */
1018
+	public function extra_misc_actions_publish_box()
1019
+	{
1020
+		$this->_generate_publish_box_extra_content();
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1026
+	 * saved.
1027
+	 * Typically you would use this to save any additional data.
1028
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
1029
+	 * ALSO very important.  When a post transitions from scheduled to published,
1030
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1031
+	 * other meta saves. So MAKE sure that you handle this accordingly.
1032
+	 *
1033
+	 * @access protected
1034
+	 * @abstract
1035
+	 * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
1036
+	 * @param WP_Post $post    The post object of the cpt that was saved.
1037
+	 * @return void
1038
+	 * @throws EE_Error
1039
+	 * @throws InvalidArgumentException
1040
+	 * @throws InvalidDataTypeException
1041
+	 * @throws InvalidInterfaceException
1042
+	 * @throws ReflectionException
1043
+	 */
1044
+	protected function _insert_update_cpt_item($post_id, $post)
1045
+	{
1046
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1047
+			// get out we're not processing an event save.
1048
+			return;
1049
+		}
1050
+		$event_values = [
1051
+			'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1052
+			'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1053
+			'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1054
+		];
1055
+		// check if the new EDTR reg options meta box is being used, and if so, don't run updates for legacy version
1056
+		if (! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1057
+			$event_values['EVT_display_ticket_selector']     = $this->request->getRequestParam(
1058
+				'display_ticket_selector',
1059
+				false,
1060
+				'bool'
1061
+			);
1062
+			$event_values['EVT_additional_limit']            = min(
1063
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1064
+				$this->request->getRequestParam(
1065
+					'additional_limit',
1066
+					EEM_Event::get_default_additional_limit(),
1067
+					'int'
1068
+				)
1069
+			);
1070
+			$event_values['EVT_default_registration_status'] = $this->request->getRequestParam(
1071
+				'EVT_default_registration_status',
1072
+				EE_Registry::instance()->CFG->registration->default_STS_ID
1073
+			);
1074
+
1075
+			$event_values['EVT_external_URL'] = $this->request->getRequestParam('externalURL');
1076
+			$event_values['EVT_phone']        = $this->request->getRequestParam('event_phone');
1077
+			$event_values['EVT_display_desc'] = $this->request->getRequestParam('display_desc', false, 'bool');
1078
+		}
1079
+		// update event
1080
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1081
+		// get event_object for other metaboxes...
1082
+		// though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1083
+		// i have to setup where conditions to override the filters in the model
1084
+		// that filter out auto-draft and inherit statuses so we GET the inherit id!
1085
+		/** @var EE_Event $event */
1086
+		$event = $this->_event_model()->get_one(
1087
+			[
1088
+				[
1089
+					$this->_event_model()->primary_key_name() => $post_id,
1090
+					'OR'                                      => [
1091
+						'status'   => $post->post_status,
1092
+						// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1093
+						// but the returned object here has a status of "publish", so use the original post status as well
1094
+						'status*1' => $this->request->getRequestParam('original_post_status'),
1095
+					],
1096
+				],
1097
+			]
1098
+		);
1099
+
1100
+		// the following are default callbacks for event attachment updates
1101
+		// that can be overridden by caffeinated functionality and/or addons.
1102
+		$event_update_callbacks = [];
1103
+		if (! $this->admin_config->useAdvancedEditor()) {
1104
+			$event_update_callbacks['_default_venue_update']   = [$this, '_default_venue_update'];
1105
+			$event_update_callbacks['_default_tickets_update'] = [$this, '_default_tickets_update'];
1106
+		}
1107
+		$event_update_callbacks = apply_filters(
1108
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1109
+			$event_update_callbacks
1110
+		);
1111
+
1112
+		$att_success = true;
1113
+		foreach ($event_update_callbacks as $e_callback) {
1114
+			$_success = is_callable($e_callback)
1115
+				? $e_callback($event, $this->request->requestParams())
1116
+				: false;
1117
+			// if ANY of these updates fail then we want the appropriate global error message
1118
+			$att_success = $_success !== false ? $att_success : false;
1119
+		}
1120
+		// any errors?
1121
+		if ($success && $att_success === false) {
1122
+			EE_Error::add_error(
1123
+				esc_html__(
1124
+					'Event Details saved successfully but something went wrong with saving attachments.',
1125
+					'event_espresso'
1126
+				),
1127
+				__FILE__,
1128
+				__FUNCTION__,
1129
+				__LINE__
1130
+			);
1131
+		} elseif ($success === false) {
1132
+			EE_Error::add_error(
1133
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1134
+				__FILE__,
1135
+				__FUNCTION__,
1136
+				__LINE__
1137
+			);
1138
+		}
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * @param int $post_id
1144
+	 * @param int $revision_id
1145
+	 * @throws EE_Error
1146
+	 * @throws EE_Error
1147
+	 * @throws ReflectionException
1148
+	 * @see parent::restore_item()
1149
+	 */
1150
+	protected function _restore_cpt_item($post_id, $revision_id)
1151
+	{
1152
+		// copy existing event meta to new post
1153
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1154
+		if ($post_evt instanceof EE_Event) {
1155
+			// meta revision restore
1156
+			$post_evt->restore_revision($revision_id);
1157
+			// related objs restore
1158
+			$post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1159
+		}
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * Attach the venue to the Event
1165
+	 *
1166
+	 * @param EE_Event $event Event Object to add the venue to
1167
+	 * @param array    $data  The request data from the form
1168
+	 * @return bool           Success or fail.
1169
+	 * @throws EE_Error
1170
+	 * @throws ReflectionException
1171
+	 */
1172
+	protected function _default_venue_update(EE_Event $event, $data)
1173
+	{
1174
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1175
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1176
+		$venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1177
+		// very important.  If we don't have a venue name...
1178
+		// then we'll get out because not necessary to create empty venue
1179
+		if (empty($data['venue_title'])) {
1180
+			return false;
1181
+		}
1182
+		$venue_array = [
1183
+			'VNU_wp_user'         => $event->get('EVT_wp_user'),
1184
+			'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1185
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1186
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1187
+			'VNU_short_desc'      => ! empty($data['venue_short_description'])
1188
+				? $data['venue_short_description']
1189
+				: null,
1190
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1191
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1192
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1193
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1194
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1195
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1196
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1197
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1198
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1199
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1200
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1201
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1202
+			'status'              => 'publish',
1203
+		];
1204
+		// if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1205
+		if (! empty($venue_id)) {
1206
+			$update_where  = [$venue_model->primary_key_name() => $venue_id];
1207
+			$rows_affected = $venue_model->update($venue_array, [$update_where]);
1208
+			// we've gotta make sure that the venue is always attached to a revision..
1209
+			// add_relation_to should take care of making sure that the relation is already present.
1210
+			$event->_add_relation_to($venue_id, 'Venue');
1211
+			return $rows_affected > 0;
1212
+		}
1213
+		// we insert the venue
1214
+		$venue_id = $venue_model->insert($venue_array);
1215
+		$event->_add_relation_to($venue_id, 'Venue');
1216
+		return ! empty($venue_id);
1217
+		// when we have the ancestor come in it's already been handled by the revision save.
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1223
+	 *
1224
+	 * @param EE_Event $event The Event object we're attaching data to
1225
+	 * @param array    $data  The request data from the form
1226
+	 * @return array
1227
+	 * @throws EE_Error
1228
+	 * @throws ReflectionException
1229
+	 * @throws Exception
1230
+	 */
1231
+	protected function _default_tickets_update(EE_Event $event, $data)
1232
+	{
1233
+		if ($this->admin_config->useAdvancedEditor()) {
1234
+			return [];
1235
+		}
1236
+		$datetime       = null;
1237
+		$saved_tickets  = [];
1238
+		$event_timezone = $event->get_timezone();
1239
+		$date_formats   = ['Y-m-d', 'h:i a'];
1240
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1241
+			// trim all values to ensure any excess whitespace is removed.
1242
+			$datetime_data                = array_map('trim', $datetime_data);
1243
+			$datetime_data['DTT_EVT_end'] =
1244
+				isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1245
+					? $datetime_data['DTT_EVT_end']
1246
+					: $datetime_data['DTT_EVT_start'];
1247
+			$datetime_values              = [
1248
+				'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1249
+				'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1250
+				'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1251
+				'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1252
+				'DTT_order'     => $row,
1253
+			];
1254
+			// if we have an id then let's get existing object first and then set the new values.
1255
+			//  Otherwise we instantiate a new object for save.
1256
+			if (! empty($datetime_data['DTT_ID'])) {
1257
+				$datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1258
+				if (! $datetime instanceof EE_Datetime) {
1259
+					throw new RuntimeException(
1260
+						sprintf(
1261
+							esc_html__(
1262
+								'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1263
+								'event_espresso'
1264
+							),
1265
+							$datetime_data['DTT_ID']
1266
+						)
1267
+					);
1268
+				}
1269
+				$datetime->set_date_format($date_formats[0]);
1270
+				$datetime->set_time_format($date_formats[1]);
1271
+				foreach ($datetime_values as $field => $value) {
1272
+					$datetime->set($field, $value);
1273
+				}
1274
+			} else {
1275
+				$datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1276
+			}
1277
+			if (! $datetime instanceof EE_Datetime) {
1278
+				throw new RuntimeException(
1279
+					sprintf(
1280
+						esc_html__(
1281
+							'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1282
+							'event_espresso'
1283
+						),
1284
+						print_r($datetime_values, true)
1285
+					)
1286
+				);
1287
+			}
1288
+			// before going any further make sure our dates are setup correctly
1289
+			// so that the end date is always equal or greater than the start date.
1290
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1291
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1292
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1293
+			}
1294
+			$datetime->save();
1295
+			$event->_add_relation_to($datetime, 'Datetime');
1296
+		}
1297
+		// no datetimes get deleted so we don't do any of that logic here.
1298
+		// update tickets next
1299
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1300
+
1301
+		// set up some default start and end dates in case those are not present in the incoming data
1302
+		$default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1303
+		$default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1304
+		// use the start date of the first datetime for the end date
1305
+		$first_datetime   = $event->first_datetime();
1306
+		$default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1307
+
1308
+		// now process the incoming data
1309
+		foreach ($data['edit_tickets'] as $row => $ticket_data) {
1310
+			$update_prices = false;
1311
+			$ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1312
+				? $data['edit_prices'][ $row ][1]['PRC_amount']
1313
+				: 0;
1314
+			// trim inputs to ensure any excess whitespace is removed.
1315
+			$ticket_data   = array_map('trim', $ticket_data);
1316
+			$ticket_values = [
1317
+				'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1318
+				'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1319
+				'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1320
+				'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1321
+				'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1322
+					? $ticket_data['TKT_start_date']
1323
+					: $default_start_date,
1324
+				'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1325
+					? $ticket_data['TKT_end_date']
1326
+					: $default_end_date,
1327
+				'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1328
+									 || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1329
+					? $ticket_data['TKT_qty']
1330
+					: EE_INF,
1331
+				'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1332
+									 || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1333
+					? $ticket_data['TKT_uses']
1334
+					: EE_INF,
1335
+				'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1336
+				'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1337
+				'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1338
+				'TKT_price'       => $ticket_price,
1339
+				'TKT_row'         => $row,
1340
+			];
1341
+			// if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1342
+			// which means in turn that the prices will become new prices as well.
1343
+			if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1344
+				$ticket_values['TKT_ID']         = 0;
1345
+				$ticket_values['TKT_is_default'] = 0;
1346
+				$update_prices                   = true;
1347
+			}
1348
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
1349
+			// we actually do our saves ahead of adding any relations because its entirely possible that this
1350
+			// ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1351
+			// keep in mind that if the ticket has been sold (and we have changed pricing information),
1352
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1353
+			if (! empty($ticket_data['TKT_ID'])) {
1354
+				$existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1355
+				if (! $existing_ticket instanceof EE_Ticket) {
1356
+					throw new RuntimeException(
1357
+						sprintf(
1358
+							esc_html__(
1359
+								'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1360
+								'event_espresso'
1361
+							),
1362
+							$ticket_data['TKT_ID']
1363
+						)
1364
+					);
1365
+				}
1366
+				$ticket_sold = $existing_ticket->count_related(
1367
+					'Registration',
1368
+					[
1369
+							[
1370
+								'STS_ID' => [
1371
+									'NOT IN',
1372
+									[EEM_Registration::status_id_incomplete],
1373
+								],
1374
+							],
1375
+						]
1376
+				) > 0;
1377
+				// let's just check the total price for the existing ticket and determine if it matches the new total price.
1378
+				// if they are different then we create a new ticket (if $ticket_sold)
1379
+				// if they aren't different then we go ahead and modify existing ticket.
1380
+				$create_new_ticket = $ticket_sold
1381
+									 && $ticket_price !== $existing_ticket->price()
1382
+									 && ! $existing_ticket->deleted();
1383
+				$existing_ticket->set_date_format($date_formats[0]);
1384
+				$existing_ticket->set_time_format($date_formats[1]);
1385
+				// set new values
1386
+				foreach ($ticket_values as $field => $value) {
1387
+					if ($field == 'TKT_qty') {
1388
+						$existing_ticket->set_qty($value);
1389
+					} elseif ($field == 'TKT_price') {
1390
+						$existing_ticket->set('TKT_price', $ticket_price);
1391
+					} else {
1392
+						$existing_ticket->set($field, $value);
1393
+					}
1394
+				}
1395
+				$ticket = $existing_ticket;
1396
+				// if $create_new_ticket is false then we can safely update the existing ticket.
1397
+				//  Otherwise we have to create a new ticket.
1398
+				if ($create_new_ticket) {
1399
+					// archive the old ticket first
1400
+					$existing_ticket->set('TKT_deleted', 1);
1401
+					$existing_ticket->save();
1402
+					// make sure this ticket is still recorded in our $saved_tickets
1403
+					// so we don't run it through the regular trash routine.
1404
+					$saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1405
+					// create new ticket that's a copy of the existing except,
1406
+					// (a new id of course and not archived) AND has the new TKT_price associated with it.
1407
+					$new_ticket = clone $existing_ticket;
1408
+					$new_ticket->set('TKT_ID', 0);
1409
+					$new_ticket->set('TKT_deleted', 0);
1410
+					$new_ticket->set('TKT_sold', 0);
1411
+					// now we need to make sure that $new prices are created as well and attached to new ticket.
1412
+					$update_prices = true;
1413
+					$ticket        = $new_ticket;
1414
+				}
1415
+			} else {
1416
+				// no TKT_id so a new ticket
1417
+				$ticket_values['TKT_price'] = $ticket_price;
1418
+				$ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1419
+				$update_prices              = true;
1420
+			}
1421
+			if (! $ticket instanceof EE_Ticket) {
1422
+				throw new RuntimeException(
1423
+					sprintf(
1424
+						esc_html__(
1425
+							'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1426
+							'event_espresso'
1427
+						),
1428
+						print_r($ticket_values, true)
1429
+					)
1430
+				);
1431
+			}
1432
+			// cap ticket qty by datetime reg limits
1433
+			$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1434
+			// update ticket.
1435
+			$ticket->save();
1436
+			// before going any further make sure our dates are setup correctly
1437
+			// so that the end date is always equal or greater than the start date.
1438
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1439
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1440
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1441
+				$ticket->save();
1442
+			}
1443
+			// initially let's add the ticket to the datetime
1444
+			$datetime->_add_relation_to($ticket, 'Ticket');
1445
+			$saved_tickets[ $ticket->ID() ] = $ticket;
1446
+			// add prices to ticket
1447
+			$prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1448
+				? $data['edit_prices'][ $row ]
1449
+				: [];
1450
+			$this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1451
+		}
1452
+		// however now we need to handle permanently deleting tickets via the ui.
1453
+		// Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1454
+		// However, it does allow for deleting tickets that have no tickets sold,
1455
+		// in which case we want to get rid of permanently because there is no need to save in db.
1456
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? [] : $old_tickets;
1457
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1458
+		foreach ($tickets_removed as $id) {
1459
+			$id = absint($id);
1460
+			// get the ticket for this id
1461
+			$ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1462
+			if (! $ticket_to_remove instanceof EE_Ticket) {
1463
+				continue;
1464
+			}
1465
+			// need to get all the related datetimes on this ticket and remove from every single one of them
1466
+			// (remember this process can ONLY kick off if there are NO tickets sold)
1467
+			$related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1468
+			foreach ($related_datetimes as $related_datetime) {
1469
+				$ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1470
+			}
1471
+			// need to do the same for prices (except these prices can also be deleted because again,
1472
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1473
+			$ticket_to_remove->delete_related_permanently('Price');
1474
+			// finally let's delete this ticket
1475
+			// (which should not be blocked at this point b/c we've removed all our relationships)
1476
+			$ticket_to_remove->delete_permanently();
1477
+		}
1478
+		return [$datetime, $saved_tickets];
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * This attaches a list of given prices to a ticket.
1484
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices)
1485
+	 * because if there is a change in price information on a ticket, a new ticket is created anyways
1486
+	 * so the archived ticket will retain the old price info and prices are automatically "archived" via the ticket.
1487
+	 *
1488
+	 * @access  private
1489
+	 * @param array     $prices_data Array of prices from the form.
1490
+	 * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1491
+	 * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1492
+	 * @return  void
1493
+	 * @throws EE_Error
1494
+	 * @throws ReflectionException
1495
+	 */
1496
+	private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1497
+	{
1498
+		$timezone = $ticket->get_timezone();
1499
+		foreach ($prices_data as $row => $price_data) {
1500
+			$price_values = [
1501
+				'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1502
+				'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1503
+				'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1504
+				'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1505
+				'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1506
+				'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1507
+				'PRC_order'      => $row,
1508
+			];
1509
+			if ($new_prices || empty($price_values['PRC_ID'])) {
1510
+				$price_values['PRC_ID'] = 0;
1511
+				$price                  = EE_Price::new_instance($price_values, $timezone);
1512
+			} else {
1513
+				$price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1514
+				// update this price with new values
1515
+				foreach ($price_values as $field => $new_price) {
1516
+					$price->set($field, $new_price);
1517
+				}
1518
+			}
1519
+			if (! $price instanceof EE_Price) {
1520
+				throw new RuntimeException(
1521
+					sprintf(
1522
+						esc_html__(
1523
+							'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1524
+							'event_espresso'
1525
+						),
1526
+						print_r($price_values, true)
1527
+					)
1528
+				);
1529
+			}
1530
+			$price->save();
1531
+			$ticket->_add_relation_to($price, 'Price');
1532
+		}
1533
+	}
1534
+
1535
+
1536
+	/**
1537
+	 * Add in our autosave ajax handlers
1538
+	 *
1539
+	 */
1540
+	protected function _ee_autosave_create_new()
1541
+	{
1542
+	}
1543
+
1544
+
1545
+	/**
1546
+	 * More autosave handlers.
1547
+	 */
1548
+	protected function _ee_autosave_edit()
1549
+	{
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * @throws EE_Error
1555
+	 * @throws ReflectionException
1556
+	 */
1557
+	private function _generate_publish_box_extra_content()
1558
+	{
1559
+		// load formatter helper
1560
+		// args for getting related registrations
1561
+		$approved_query_args        = [
1562
+			[
1563
+				'REG_deleted' => 0,
1564
+				'STS_ID'      => EEM_Registration::status_id_approved,
1565
+			],
1566
+		];
1567
+		$not_approved_query_args    = [
1568
+			[
1569
+				'REG_deleted' => 0,
1570
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1571
+			],
1572
+		];
1573
+		$pending_payment_query_args = [
1574
+			[
1575
+				'REG_deleted' => 0,
1576
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1577
+			],
1578
+		];
1579
+		// publish box
1580
+		$publish_box_extra_args = [
1581
+			'view_approved_reg_url'        => add_query_arg(
1582
+				[
1583
+					'action'      => 'default',
1584
+					'event_id'    => $this->_cpt_model_obj->ID(),
1585
+					'_reg_status' => EEM_Registration::status_id_approved,
1586
+				],
1587
+				REG_ADMIN_URL
1588
+			),
1589
+			'view_not_approved_reg_url'    => add_query_arg(
1590
+				[
1591
+					'action'      => 'default',
1592
+					'event_id'    => $this->_cpt_model_obj->ID(),
1593
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1594
+				],
1595
+				REG_ADMIN_URL
1596
+			),
1597
+			'view_pending_payment_reg_url' => add_query_arg(
1598
+				[
1599
+					'action'      => 'default',
1600
+					'event_id'    => $this->_cpt_model_obj->ID(),
1601
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1602
+				],
1603
+				REG_ADMIN_URL
1604
+			),
1605
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1606
+				'Registration',
1607
+				$approved_query_args
1608
+			),
1609
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1610
+				'Registration',
1611
+				$not_approved_query_args
1612
+			),
1613
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1614
+				'Registration',
1615
+				$pending_payment_query_args
1616
+			),
1617
+			'misc_pub_section_class'       => apply_filters(
1618
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1619
+				'misc-pub-section'
1620
+			),
1621
+		];
1622
+		ob_start();
1623
+		do_action(
1624
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1625
+			$this->_cpt_model_obj
1626
+		);
1627
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1628
+		// load template
1629
+		EEH_Template::display_template(
1630
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1631
+			$publish_box_extra_args
1632
+		);
1633
+	}
1634
+
1635
+
1636
+	/**
1637
+	 * @return EE_Event
1638
+	 */
1639
+	public function get_event_object()
1640
+	{
1641
+		return $this->_cpt_model_obj;
1642
+	}
1643
+
1644
+
1645
+
1646
+
1647
+	/** METABOXES * */
1648
+	/**
1649
+	 * _register_event_editor_meta_boxes
1650
+	 * add all metaboxes related to the event_editor
1651
+	 *
1652
+	 * @return void
1653
+	 * @throws EE_Error
1654
+	 * @throws ReflectionException
1655
+	 */
1656
+	protected function _register_event_editor_meta_boxes()
1657
+	{
1658
+		$this->verify_cpt_object();
1659
+		$use_advanced_editor = $this->admin_config->useAdvancedEditor();
1660
+		// check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
1661
+		if (! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1662
+			$this->addMetaBox(
1663
+				'espresso_event_editor_event_options',
1664
+				esc_html__('Event Registration Options', 'event_espresso'),
1665
+				[$this, 'registration_options_meta_box'],
1666
+				$this->page_slug,
1667
+				'side'
1668
+			);
1669
+		}
1670
+		if (! $use_advanced_editor) {
1671
+			$this->addMetaBox(
1672
+				'espresso_event_editor_tickets',
1673
+				esc_html__('Event Datetime & Ticket', 'event_espresso'),
1674
+				[$this, 'ticket_metabox'],
1675
+				$this->page_slug,
1676
+				'normal',
1677
+				'high'
1678
+			);
1679
+		} elseif ($this->feature->allowed('use_reg_options_meta_box')) {
1680
+			add_action(
1681
+				'add_meta_boxes_espresso_events',
1682
+				function () {
1683
+					global $current_screen;
1684
+					remove_meta_box('authordiv', $current_screen, 'normal');
1685
+				},
1686
+				99
1687
+			);
1688
+		}
1689
+		// NOTE: if you're looking for other metaboxes in here,
1690
+		// where a metabox has a related management page in the admin
1691
+		// you will find it setup in the related management page's "_Hooks" file.
1692
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1693
+	}
1694
+
1695
+
1696
+	/**
1697
+	 * @throws DomainException
1698
+	 * @throws EE_Error
1699
+	 * @throws ReflectionException
1700
+	 */
1701
+	public function ticket_metabox()
1702
+	{
1703
+		$existing_datetime_ids = $existing_ticket_ids = [];
1704
+		// defaults for template args
1705
+		$template_args = [
1706
+			'existing_datetime_ids'    => '',
1707
+			'event_datetime_help_link' => '',
1708
+			'ticket_options_help_link' => '',
1709
+			'time'                     => null,
1710
+			'ticket_rows'              => '',
1711
+			'existing_ticket_ids'      => '',
1712
+			'total_ticket_rows'        => 1,
1713
+			'ticket_js_structure'      => '',
1714
+			'trash_icon'               => 'dashicons dashicons-lock',
1715
+			'disabled'                 => '',
1716
+		];
1717
+		$event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1718
+		/**
1719
+		 * 1. Start with retrieving Datetimes
1720
+		 * 2. Fore each datetime get related tickets
1721
+		 * 3. For each ticket get related prices
1722
+		 */
1723
+		/** @var EEM_Datetime $datetime_model */
1724
+		$datetime_model = EE_Registry::instance()->load_model('Datetime');
1725
+		/** @var EEM_Ticket $datetime_model */
1726
+		$ticket_model = EE_Registry::instance()->load_model('Ticket');
1727
+		$times        = $datetime_model->get_all_event_dates($event_id);
1728
+		/** @type EE_Datetime $first_datetime */
1729
+		$first_datetime = reset($times);
1730
+		// do we get related tickets?
1731
+		if (
1732
+			$first_datetime instanceof EE_Datetime
1733
+			&& $first_datetime->ID() !== 0
1734
+		) {
1735
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1736
+			$template_args['time']   = $first_datetime;
1737
+			$related_tickets         = $first_datetime->tickets(
1738
+				[
1739
+					['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1740
+					'default_where_conditions' => 'none',
1741
+				]
1742
+			);
1743
+			if (! empty($related_tickets)) {
1744
+				$template_args['total_ticket_rows'] = count($related_tickets);
1745
+				$row                                = 0;
1746
+				foreach ($related_tickets as $ticket) {
1747
+					$existing_ticket_ids[]        = $ticket->get('TKT_ID');
1748
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1749
+					$row++;
1750
+				}
1751
+			} else {
1752
+				$template_args['total_ticket_rows'] = 1;
1753
+				/** @type EE_Ticket $ticket */
1754
+				$ticket                       = $ticket_model->create_default_object();
1755
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1756
+			}
1757
+		} else {
1758
+			$template_args['time'] = $times[0];
1759
+			/** @type EE_Ticket[] $tickets */
1760
+			$tickets                      = $ticket_model->get_all_default_tickets();
1761
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1762
+			// NOTE: we're just sending the first default row
1763
+			// (decaf can't manage default tickets so this should be sufficient);
1764
+		}
1765
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1766
+			'event_editor_event_datetimes_help_tab'
1767
+		);
1768
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1769
+		$template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1770
+		$template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1771
+		$template_args['ticket_js_structure']      = $this->_get_ticket_row(
1772
+			$ticket_model->create_default_object(),
1773
+			true
1774
+		);
1775
+		$template                                  = apply_filters(
1776
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1777
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1778
+		);
1779
+		EEH_Template::display_template($template, $template_args);
1780
+	}
1781
+
1782
+
1783
+	/**
1784
+	 * Setup an individual ticket form for the decaf event editor page
1785
+	 *
1786
+	 * @access private
1787
+	 * @param EE_Ticket $ticket   the ticket object
1788
+	 * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1789
+	 * @param int       $row
1790
+	 * @return string generated html for the ticket row.
1791
+	 * @throws EE_Error
1792
+	 * @throws ReflectionException
1793
+	 */
1794
+	private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1795
+	{
1796
+		$template_args = [
1797
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1798
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1799
+				: '',
1800
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1801
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1802
+			'TKT_name'            => $ticket->get('TKT_name'),
1803
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1804
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1805
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1806
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1807
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1808
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1809
+			'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1810
+									 && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1811
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'dashicons dashicons-lock',
1812
+			'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1813
+				: ' disabled=disabled',
1814
+		];
1815
+		$price         = $ticket->ID() !== 0
1816
+			? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1817
+			: null;
1818
+		$price         = $price instanceof EE_Price
1819
+			? $price
1820
+			: EEM_Price::instance()->create_default_object();
1821
+		$price_args    = [
1822
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1823
+			'PRC_amount'            => $price->get('PRC_amount'),
1824
+			'PRT_ID'                => $price->get('PRT_ID'),
1825
+			'PRC_ID'                => $price->get('PRC_ID'),
1826
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1827
+		];
1828
+		// make sure we have default start and end dates if skeleton
1829
+		// handle rows that should NOT be empty
1830
+		if (empty($template_args['TKT_start_date'])) {
1831
+			// if empty then the start date will be now.
1832
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1833
+		}
1834
+		if (empty($template_args['TKT_end_date'])) {
1835
+			// get the earliest datetime (if present);
1836
+			$earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1837
+				? $this->_cpt_model_obj->get_first_related(
1838
+					'Datetime',
1839
+					['order_by' => ['DTT_EVT_start' => 'ASC']]
1840
+				)
1841
+				: null;
1842
+			$template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1843
+				? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1844
+				: date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1845
+		}
1846
+		$template_args = array_merge($template_args, $price_args);
1847
+		$template      = apply_filters(
1848
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1849
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1850
+			$ticket
1851
+		);
1852
+		return EEH_Template::display_template($template, $template_args, true);
1853
+	}
1854
+
1855
+
1856
+	/**
1857
+	 * @throws EE_Error
1858
+	 * @throws ReflectionException
1859
+	 */
1860
+	public function registration_options_meta_box()
1861
+	{
1862
+		$yes_no_values             = [
1863
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1864
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1865
+		];
1866
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1867
+			[
1868
+				EEM_Registration::status_id_cancelled,
1869
+				EEM_Registration::status_id_declined,
1870
+				EEM_Registration::status_id_incomplete,
1871
+			],
1872
+			true
1873
+		);
1874
+		// $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1875
+		$template_args['_event']                          = $this->_cpt_model_obj;
1876
+		$template_args['event']                           = $this->_cpt_model_obj;
1877
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1878
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1879
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1880
+			'default_reg_status',
1881
+			$default_reg_status_values,
1882
+			$this->_cpt_model_obj->default_registration_status()
1883
+		);
1884
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
1885
+			'display_desc',
1886
+			$yes_no_values,
1887
+			$this->_cpt_model_obj->display_description()
1888
+		);
1889
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1890
+			'display_ticket_selector',
1891
+			$yes_no_values,
1892
+			$this->_cpt_model_obj->display_ticket_selector(),
1893
+			'',
1894
+			'',
1895
+			false
1896
+		);
1897
+		$template_args['additional_registration_options'] = apply_filters(
1898
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1899
+			'',
1900
+			$template_args,
1901
+			$yes_no_values,
1902
+			$default_reg_status_values
1903
+		);
1904
+		EEH_Template::display_template(
1905
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1906
+			$template_args
1907
+		);
1908
+	}
1909
+
1910
+
1911
+	/**
1912
+	 * _get_events()
1913
+	 * This method simply returns all the events (for the given _view and paging)
1914
+	 *
1915
+	 * @access public
1916
+	 * @param int  $per_page     count of items per page (20 default);
1917
+	 * @param int  $current_page what is the current page being viewed.
1918
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1919
+	 *                           If FALSE then we return an array of event objects
1920
+	 *                           that match the given _view and paging parameters.
1921
+	 * @return array|int         an array of event objects or a count of them.
1922
+	 * @throws Exception
1923
+	 */
1924
+	public function get_events($per_page = 10, $current_page = 1, $count = false)
1925
+	{
1926
+		$EEM_Event   = $this->_event_model();
1927
+		$offset      = ($current_page - 1) * $per_page;
1928
+		$limit       = $count ? null : $offset . ',' . $per_page;
1929
+		$orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1930
+		$order       = $this->request->getRequestParam('order', 'DESC');
1931
+		$month_range = $this->request->getRequestParam('month_range');
1932
+		if ($month_range) {
1933
+			$pieces = explode(' ', $month_range, 3);
1934
+			// simulate the FIRST day of the month, that fixes issues for months like February
1935
+			// where PHP doesn't know what to assume for date.
1936
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1937
+			$month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1938
+			$year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1939
+		}
1940
+		$where  = [];
1941
+		$status = $this->request->getRequestParam('status');
1942
+		// determine what post_status our condition will have for the query.
1943
+		switch ($status) {
1944
+			case 'month':
1945
+			case 'today':
1946
+			case null:
1947
+			case 'all':
1948
+				break;
1949
+			case 'draft':
1950
+				$where['status'] = ['IN', ['draft', 'auto-draft']];
1951
+				break;
1952
+			default:
1953
+				$where['status'] = $status;
1954
+		}
1955
+		// categories? The default for all categories is -1
1956
+		$category = $this->request->getRequestParam('EVT_CAT', -1, 'int');
1957
+		if ($category !== -1) {
1958
+			$where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1959
+			$where['Term_Taxonomy.term_id']  = $category;
1960
+		}
1961
+		// date where conditions
1962
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1963
+		if ($month_range) {
1964
+			$DateTime = new DateTime(
1965
+				$year_r . '-' . $month_r . '-01 00:00:00',
1966
+				new DateTimeZone('UTC')
1967
+			);
1968
+			$start    = $DateTime->getTimestamp();
1969
+			// set the datetime to be the end of the month
1970
+			$DateTime->setDate(
1971
+				$year_r,
1972
+				$month_r,
1973
+				$DateTime->format('t')
1974
+			)->setTime(23, 59, 59);
1975
+			$end                             = $DateTime->getTimestamp();
1976
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1977
+		} elseif ($status === 'today') {
1978
+			$DateTime                        =
1979
+				new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1980
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1981
+			$end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1982
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1983
+		} elseif ($status === 'month') {
1984
+			$now                             = date('Y-m-01');
1985
+			$DateTime                        =
1986
+				new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1987
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1988
+			$end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1989
+														->setTime(23, 59, 59)
1990
+														->format(implode(' ', $start_formats));
1991
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1992
+		}
1993
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1994
+			$where['EVT_wp_user'] = get_current_user_id();
1995
+		} else {
1996
+			if (! isset($where['status'])) {
1997
+				if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1998
+					$where['OR'] = [
1999
+						'status*restrict_private' => ['!=', 'private'],
2000
+						'AND'                     => [
2001
+							'status*inclusive' => ['=', 'private'],
2002
+							'EVT_wp_user'      => get_current_user_id(),
2003
+						],
2004
+					];
2005
+				}
2006
+			}
2007
+		}
2008
+		$wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
2009
+		if (
2010
+			$wp_user
2011
+			&& $wp_user !== get_current_user_id()
2012
+			&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
2013
+		) {
2014
+			$where['EVT_wp_user'] = $wp_user;
2015
+		}
2016
+		// search query handling
2017
+		$search_term = $this->request->getRequestParam('s');
2018
+		if ($search_term) {
2019
+			$search_term = '%' . $search_term . '%';
2020
+			$where['OR'] = [
2021
+				'EVT_name'       => ['LIKE', $search_term],
2022
+				'EVT_desc'       => ['LIKE', $search_term],
2023
+				'EVT_short_desc' => ['LIKE', $search_term],
2024
+			];
2025
+		}
2026
+		// filter events by venue.
2027
+		$venue = $this->request->getRequestParam('venue', 0, 'int');
2028
+		if ($venue) {
2029
+			$where['Venue.VNU_ID'] = $venue;
2030
+		}
2031
+		$request_params = $this->request->requestParams();
2032
+		$where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
2033
+		$query_params   = apply_filters(
2034
+			'FHEE__Events_Admin_Page__get_events__query_params',
2035
+			[
2036
+				$where,
2037
+				'limit'    => $limit,
2038
+				'order_by' => $orderby,
2039
+				'order'    => $order,
2040
+				'group_by' => 'EVT_ID',
2041
+			],
2042
+			$request_params
2043
+		);
2044
+
2045
+		// let's first check if we have special requests coming in.
2046
+		$active_status = $this->request->getRequestParam('active_status');
2047
+		if ($active_status) {
2048
+			switch ($active_status) {
2049
+				case 'upcoming':
2050
+					return $EEM_Event->get_upcoming_events($query_params, $count);
2051
+				case 'expired':
2052
+					return $EEM_Event->get_expired_events($query_params, $count);
2053
+				case 'active':
2054
+					return $EEM_Event->get_active_events($query_params, $count);
2055
+				case 'inactive':
2056
+					return $EEM_Event->get_inactive_events($query_params, $count);
2057
+			}
2058
+		}
2059
+
2060
+		return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
2061
+	}
2062
+
2063
+
2064
+	/**
2065
+	 * handling for WordPress CPT actions (trash, restore, delete)
2066
+	 *
2067
+	 * @param string $post_id
2068
+	 * @throws EE_Error
2069
+	 * @throws ReflectionException
2070
+	 */
2071
+	public function trash_cpt_item($post_id)
2072
+	{
2073
+		$this->request->setRequestParam('EVT_ID', $post_id);
2074
+		$this->_trash_or_restore_event('trash', false);
2075
+	}
2076
+
2077
+
2078
+	/**
2079
+	 * @param string $post_id
2080
+	 * @throws EE_Error
2081
+	 * @throws ReflectionException
2082
+	 */
2083
+	public function restore_cpt_item($post_id)
2084
+	{
2085
+		$this->request->setRequestParam('EVT_ID', $post_id);
2086
+		$this->_trash_or_restore_event('draft', false);
2087
+	}
2088
+
2089
+
2090
+	/**
2091
+	 * @param string $post_id
2092
+	 * @throws EE_Error
2093
+	 * @throws EE_Error
2094
+	 */
2095
+	public function delete_cpt_item($post_id)
2096
+	{
2097
+		throw new EE_Error(
2098
+			esc_html__(
2099
+				'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2100
+				'event_espresso'
2101
+			)
2102
+		);
2103
+		// $this->request->setRequestParam('EVT_ID', $post_id);
2104
+		// $this->_delete_event();
2105
+	}
2106
+
2107
+
2108
+	/**
2109
+	 * _trash_or_restore_event
2110
+	 *
2111
+	 * @access protected
2112
+	 * @param string $event_status
2113
+	 * @param bool   $redirect_after
2114
+	 * @throws EE_Error
2115
+	 * @throws EE_Error
2116
+	 * @throws ReflectionException
2117
+	 */
2118
+	protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2119
+	{
2120
+		// determine the event id and set to array.
2121
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2122
+		// loop thru events
2123
+		if ($EVT_ID) {
2124
+			// clean status
2125
+			$event_status = sanitize_key($event_status);
2126
+			// grab status
2127
+			if (! empty($event_status)) {
2128
+				$success = $this->_change_event_status($EVT_ID, $event_status);
2129
+			} else {
2130
+				$success = false;
2131
+				$msg     = esc_html__(
2132
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2133
+					'event_espresso'
2134
+				);
2135
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2136
+			}
2137
+		} else {
2138
+			$success = false;
2139
+			$msg     = esc_html__(
2140
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2141
+				'event_espresso'
2142
+			);
2143
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2144
+		}
2145
+		$action = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2146
+		if ($redirect_after) {
2147
+			$this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2148
+		}
2149
+	}
2150
+
2151
+
2152
+	/**
2153
+	 * _trash_or_restore_events
2154
+	 *
2155
+	 * @access protected
2156
+	 * @param string $event_status
2157
+	 * @return void
2158
+	 * @throws EE_Error
2159
+	 * @throws EE_Error
2160
+	 * @throws ReflectionException
2161
+	 */
2162
+	protected function _trash_or_restore_events($event_status = 'trash')
2163
+	{
2164
+		// clean status
2165
+		$event_status = sanitize_key($event_status);
2166
+		// grab status
2167
+		if (! empty($event_status)) {
2168
+			$success = true;
2169
+			// determine the event id and set to array.
2170
+			$EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2171
+			// loop thru events
2172
+			foreach ($EVT_IDs as $EVT_ID) {
2173
+				if ($EVT_ID = absint($EVT_ID)) {
2174
+					$results = $this->_change_event_status($EVT_ID, $event_status);
2175
+					$success = $results !== false ? $success : false;
2176
+				} else {
2177
+					$msg = sprintf(
2178
+						esc_html__(
2179
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2180
+							'event_espresso'
2181
+						),
2182
+						$EVT_ID
2183
+					);
2184
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2185
+					$success = false;
2186
+				}
2187
+			}
2188
+		} else {
2189
+			$success = false;
2190
+			$msg     = esc_html__(
2191
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2192
+				'event_espresso'
2193
+			);
2194
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2195
+		}
2196
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2197
+		$success = $success ? 2 : false;
2198
+		$action  = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2199
+		$this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2200
+	}
2201
+
2202
+
2203
+	/**
2204
+	 * @param int    $EVT_ID
2205
+	 * @param string $event_status
2206
+	 * @return bool
2207
+	 * @throws EE_Error
2208
+	 * @throws ReflectionException
2209
+	 */
2210
+	private function _change_event_status($EVT_ID = 0, $event_status = '')
2211
+	{
2212
+		// grab event id
2213
+		if (! $EVT_ID) {
2214
+			$msg = esc_html__(
2215
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2216
+				'event_espresso'
2217
+			);
2218
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2219
+			return false;
2220
+		}
2221
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2222
+		// clean status
2223
+		$event_status = sanitize_key($event_status);
2224
+		// grab status
2225
+		if (empty($event_status)) {
2226
+			$msg = esc_html__(
2227
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2228
+				'event_espresso'
2229
+			);
2230
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2231
+			return false;
2232
+		}
2233
+		// was event trashed or restored ?
2234
+		switch ($event_status) {
2235
+			case 'draft':
2236
+				$action = 'restored from the trash';
2237
+				$hook   = 'AHEE_event_restored_from_trash';
2238
+				break;
2239
+			case 'trash':
2240
+				$action = 'moved to the trash';
2241
+				$hook   = 'AHEE_event_moved_to_trash';
2242
+				break;
2243
+			default:
2244
+				$action = 'updated';
2245
+				$hook   = false;
2246
+		}
2247
+		// use class to change status
2248
+		$this->_cpt_model_obj->set_status($event_status);
2249
+		$success = $this->_cpt_model_obj->save();
2250
+		if (! $success) {
2251
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2252
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2253
+			return false;
2254
+		}
2255
+		if ($hook) {
2256
+			do_action($hook);
2257
+		}
2258
+		return true;
2259
+	}
2260
+
2261
+
2262
+	/**
2263
+	 * @param array $event_ids
2264
+	 * @return array
2265
+	 * @since   4.10.23.p
2266
+	 */
2267
+	private function cleanEventIds(array $event_ids)
2268
+	{
2269
+		return array_map('absint', $event_ids);
2270
+	}
2271
+
2272
+
2273
+	/**
2274
+	 * @return array
2275
+	 * @since   4.10.23.p
2276
+	 */
2277
+	private function getEventIdsFromRequest()
2278
+	{
2279
+		if ($this->request->requestParamIsSet('EVT_IDs')) {
2280
+			return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2281
+		} else {
2282
+			return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2283
+		}
2284
+	}
2285
+
2286
+
2287
+	/**
2288
+	 * @param bool $preview_delete
2289
+	 * @throws EE_Error
2290
+	 */
2291
+	protected function _delete_event($preview_delete = true)
2292
+	{
2293
+		$this->_delete_events($preview_delete);
2294
+	}
2295
+
2296
+
2297
+	/**
2298
+	 * Gets the tree traversal batch persister.
2299
+	 *
2300
+	 * @return NodeGroupDao
2301
+	 * @throws InvalidArgumentException
2302
+	 * @throws InvalidDataTypeException
2303
+	 * @throws InvalidInterfaceException
2304
+	 * @since 4.10.12.p
2305
+	 */
2306
+	protected function getModelObjNodeGroupPersister()
2307
+	{
2308
+		if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2309
+			$this->model_obj_node_group_persister =
2310
+				$this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2311
+		}
2312
+		return $this->model_obj_node_group_persister;
2313
+	}
2314
+
2315
+
2316
+	/**
2317
+	 * @param bool $preview_delete
2318
+	 * @return void
2319
+	 * @throws EE_Error
2320
+	 */
2321
+	protected function _delete_events($preview_delete = true)
2322
+	{
2323
+		$event_ids = $this->getEventIdsFromRequest();
2324
+		if ($preview_delete) {
2325
+			$this->generateDeletionPreview($event_ids);
2326
+		} else {
2327
+			EEM_Event::instance()->delete_permanently([['EVT_ID' => ['IN', $event_ids]]]);
2328
+		}
2329
+	}
2330
+
2331
+
2332
+	/**
2333
+	 * @param array $event_ids
2334
+	 */
2335
+	protected function generateDeletionPreview(array $event_ids)
2336
+	{
2337
+		$event_ids = $this->cleanEventIds($event_ids);
2338
+		// Set a code we can use to reference this deletion task in the batch jobs and preview page.
2339
+		$deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2340
+		$return_url        = EE_Admin_Page::add_query_args_and_nonce(
2341
+			[
2342
+				'action'            => 'preview_deletion',
2343
+				'deletion_job_code' => $deletion_job_code,
2344
+			],
2345
+			$this->_admin_base_url
2346
+		);
2347
+		EEH_URL::safeRedirectAndExit(
2348
+			EE_Admin_Page::add_query_args_and_nonce(
2349
+				[
2350
+					'page'              => EED_Batch::PAGE_SLUG,
2351
+					'batch'             => EED_Batch::batch_job,
2352
+					'EVT_IDs'           => $event_ids,
2353
+					'deletion_job_code' => $deletion_job_code,
2354
+					'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2355
+					'return_url'        => urlencode($return_url),
2356
+				],
2357
+				admin_url()
2358
+			)
2359
+		);
2360
+	}
2361
+
2362
+
2363
+	/**
2364
+	 * Checks for a POST submission
2365
+	 *
2366
+	 * @since 4.10.12.p
2367
+	 */
2368
+	protected function confirmDeletion()
2369
+	{
2370
+		$deletion_redirect_logic =
2371
+			$this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2372
+		$deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2373
+	}
2374
+
2375
+
2376
+	/**
2377
+	 * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2378
+	 *
2379
+	 * @throws EE_Error
2380
+	 * @since 4.10.12.p
2381
+	 */
2382
+	protected function previewDeletion()
2383
+	{
2384
+		$preview_deletion_logic =
2385
+			$this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2386
+		$this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2387
+		$this->display_admin_page_with_no_sidebar();
2388
+	}
2389
+
2390
+
2391
+	/**
2392
+	 * get total number of events
2393
+	 *
2394
+	 * @access public
2395
+	 * @return int
2396
+	 * @throws EE_Error
2397
+	 * @throws EE_Error
2398
+	 */
2399
+	public function total_events()
2400
+	{
2401
+		return EEM_Event::instance()->count(
2402
+			['caps' => 'read_admin'],
2403
+			'EVT_ID',
2404
+			true
2405
+		);
2406
+	}
2407
+
2408
+
2409
+	/**
2410
+	 * get total number of draft events
2411
+	 *
2412
+	 * @access public
2413
+	 * @return int
2414
+	 * @throws EE_Error
2415
+	 * @throws EE_Error
2416
+	 */
2417
+	public function total_events_draft()
2418
+	{
2419
+		return EEM_Event::instance()->count(
2420
+			[
2421
+				['status' => ['IN', ['draft', 'auto-draft']]],
2422
+				'caps' => 'read_admin',
2423
+			],
2424
+			'EVT_ID',
2425
+			true
2426
+		);
2427
+	}
2428
+
2429
+
2430
+	/**
2431
+	 * get total number of trashed events
2432
+	 *
2433
+	 * @access public
2434
+	 * @return int
2435
+	 * @throws EE_Error
2436
+	 * @throws EE_Error
2437
+	 */
2438
+	public function total_trashed_events()
2439
+	{
2440
+		return EEM_Event::instance()->count(
2441
+			[
2442
+				['status' => 'trash'],
2443
+				'caps' => 'read_admin',
2444
+			],
2445
+			'EVT_ID',
2446
+			true
2447
+		);
2448
+	}
2449
+
2450
+
2451
+	/**
2452
+	 *    _default_event_settings
2453
+	 *    This generates the Default Settings Tab
2454
+	 *
2455
+	 * @return void
2456
+	 * @throws DomainException
2457
+	 * @throws EE_Error
2458
+	 * @throws InvalidArgumentException
2459
+	 * @throws InvalidDataTypeException
2460
+	 * @throws InvalidInterfaceException
2461
+	 */
2462
+	protected function _default_event_settings()
2463
+	{
2464
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2465
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
2466
+		$this->_template_args['admin_page_content'] = EEH_HTML::div(
2467
+			$this->_default_event_settings_form()->get_html(),
2468
+			'',
2469
+			'padding'
2470
+		);
2471
+		$this->display_admin_page_with_sidebar();
2472
+	}
2473
+
2474
+
2475
+	/**
2476
+	 * Return the form for event settings.
2477
+	 *
2478
+	 * @return EE_Form_Section_Proper
2479
+	 * @throws EE_Error
2480
+	 */
2481
+	protected function _default_event_settings_form()
2482
+	{
2483
+		$registration_config              = EE_Registry::instance()->CFG->registration;
2484
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2485
+		// exclude
2486
+			[
2487
+				EEM_Registration::status_id_cancelled,
2488
+				EEM_Registration::status_id_declined,
2489
+				EEM_Registration::status_id_incomplete,
2490
+				EEM_Registration::status_id_wait_list,
2491
+			],
2492
+			true
2493
+		);
2494
+		// setup Advanced Editor ???
2495
+		if (
2496
+			$this->raw_req_action === 'default_event_settings'
2497
+			|| $this->raw_req_action === 'update_default_event_settings'
2498
+		) {
2499
+			$this->advanced_editor_admin_form = $this->loader->getShared(AdvancedEditorAdminFormSection::class);
2500
+		}
2501
+		return new EE_Form_Section_Proper(
2502
+			[
2503
+				'name'            => 'update_default_event_settings',
2504
+				'html_id'         => 'update_default_event_settings',
2505
+				'html_class'      => 'form-table',
2506
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2507
+				'subsections'     => apply_filters(
2508
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2509
+					[
2510
+						'defaults_section_header' => new EE_Form_Section_HTML(
2511
+							EEH_HTML::h2(
2512
+								esc_html__('Default Settings', 'event_espresso'),
2513
+								'',
2514
+								'ee-admin-settings-hdr'
2515
+							)
2516
+						),
2517
+						'default_reg_status'  => new EE_Select_Input(
2518
+							$registration_stati_for_selection,
2519
+							[
2520
+								'default'         => isset($registration_config->default_STS_ID)
2521
+													 && array_key_exists(
2522
+														 $registration_config->default_STS_ID,
2523
+														 $registration_stati_for_selection
2524
+													 )
2525
+									? sanitize_text_field($registration_config->default_STS_ID)
2526
+									: EEM_Registration::status_id_pending_payment,
2527
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2528
+													 . EEH_Template::get_help_tab_link(
2529
+														 'default_settings_status_help_tab'
2530
+													 ),
2531
+								'html_help_text'  => esc_html__(
2532
+									'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.',
2533
+									'event_espresso'
2534
+								),
2535
+							]
2536
+						),
2537
+						'default_max_tickets' => new EE_Integer_Input(
2538
+							[
2539
+								'default'         => isset($registration_config->default_maximum_number_of_tickets)
2540
+									? $registration_config->default_maximum_number_of_tickets
2541
+									: EEM_Event::get_default_additional_limit(),
2542
+								'html_label_text' => esc_html__(
2543
+									'Default Maximum Tickets Allowed Per Order:',
2544
+									'event_espresso'
2545
+								)
2546
+													 . EEH_Template::get_help_tab_link(
2547
+														 'default_maximum_tickets_help_tab"'
2548
+													 ),
2549
+								'html_help_text'  => esc_html__(
2550
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2551
+									'event_espresso'
2552
+								),
2553
+							]
2554
+						),
2555
+					]
2556
+				),
2557
+			]
2558
+		);
2559
+	}
2560
+
2561
+
2562
+	/**
2563
+	 * @return void
2564
+	 * @throws EE_Error
2565
+	 * @throws InvalidArgumentException
2566
+	 * @throws InvalidDataTypeException
2567
+	 * @throws InvalidInterfaceException
2568
+	 */
2569
+	protected function _update_default_event_settings()
2570
+	{
2571
+		$form = $this->_default_event_settings_form();
2572
+		if ($form->was_submitted()) {
2573
+			$form->receive_form_submission();
2574
+			if ($form->is_valid()) {
2575
+				$registration_config = EE_Registry::instance()->CFG->registration;
2576
+				$valid_data          = $form->valid_data();
2577
+				if (isset($valid_data['default_reg_status'])) {
2578
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2579
+				}
2580
+				if (isset($valid_data['default_max_tickets'])) {
2581
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2582
+				}
2583
+				do_action(
2584
+					'AHEE__Events_Admin_Page___update_default_event_settings',
2585
+					$valid_data,
2586
+					EE_Registry::instance()->CFG,
2587
+					$this
2588
+				);
2589
+				// update because data was valid!
2590
+				EE_Registry::instance()->CFG->update_espresso_config();
2591
+				EE_Error::overwrite_success();
2592
+				EE_Error::add_success(
2593
+					esc_html__('Default Event Settings were updated', 'event_espresso')
2594
+				);
2595
+			}
2596
+		}
2597
+		$this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2598
+	}
2599
+
2600
+
2601
+	/*************        Templates        *************
21 2602
      *
22
-     * @var EE_Event $_event
23
-     */
24
-    protected $_event;
25
-
26
-
27
-    /**
28
-     * This will hold the category object for category_details screen.
29
-     *
30
-     * @var stdClass $_category
31
-     */
32
-    protected $_category;
33
-
34
-
35
-    /**
36
-     * This will hold the event model instance
37
-     *
38
-     * @var EEM_Event $_event_model
39
-     */
40
-    protected $_event_model;
41
-
42
-
43
-    /**
44
-     * @var EE_Event
45
-     */
46
-    protected $_cpt_model_obj = false;
47
-
48
-
49
-    /**
50
-     * @var NodeGroupDao
51
-     */
52
-    protected $model_obj_node_group_persister;
53
-
54
-    /**
55
-     * @var AdvancedEditorAdminFormSection
56
-     */
57
-    protected $advanced_editor_admin_form;
58
-
59
-
60
-    /**
61
-     * Initialize page props for this admin page group.
62
-     */
63
-    protected function _init_page_props()
64
-    {
65
-        $this->page_slug        = EVENTS_PG_SLUG;
66
-        $this->page_label       = EVENTS_LABEL;
67
-        $this->_admin_base_url  = EVENTS_ADMIN_URL;
68
-        $this->_admin_base_path = EVENTS_ADMIN;
69
-        $this->_cpt_model_names = [
70
-            'create_new' => 'EEM_Event',
71
-            'edit'       => 'EEM_Event',
72
-        ];
73
-        $this->_cpt_edit_routes = [
74
-            'espresso_events' => 'edit',
75
-        ];
76
-        add_action(
77
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
78
-            [$this, 'verify_event_edit'],
79
-            10,
80
-            2
81
-        );
82
-    }
83
-
84
-
85
-    /**
86
-     * Sets the ajax hooks used for this admin page group.
87
-     */
88
-    protected function _ajax_hooks()
89
-    {
90
-        add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
91
-    }
92
-
93
-
94
-    /**
95
-     * Sets the page properties for this admin page group.
96
-     */
97
-    protected function _define_page_props()
98
-    {
99
-        $this->_admin_page_title = EVENTS_LABEL;
100
-        $this->_labels           = [
101
-            'buttons'      => [
102
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
103
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
104
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
105
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
106
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
107
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
108
-            ],
109
-            'editor_title' => [
110
-                'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
111
-            ],
112
-            'publishbox'   => [
113
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
114
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
115
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
116
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
117
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
118
-            ],
119
-        ];
120
-    }
121
-
122
-
123
-    /**
124
-     * Sets the page routes property for this admin page group.
125
-     */
126
-    protected function _set_page_routes()
127
-    {
128
-        // load formatter helper
129
-        // load field generator helper
130
-        // is there a evt_id in the request?
131
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
132
-        $EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
133
-
134
-        $this->_page_routes = [
135
-            'default'                       => [
136
-                'func'       => '_events_overview_list_table',
137
-                'capability' => 'ee_read_events',
138
-            ],
139
-            'create_new'                    => [
140
-                'func'       => '_create_new_cpt_item',
141
-                'capability' => 'ee_edit_events',
142
-            ],
143
-            'edit'                          => [
144
-                'func'       => '_edit_cpt_item',
145
-                'capability' => 'ee_edit_event',
146
-                'obj_id'     => $EVT_ID,
147
-            ],
148
-            'copy_event'                    => [
149
-                'func'       => '_copy_events',
150
-                'capability' => 'ee_edit_event',
151
-                'obj_id'     => $EVT_ID,
152
-                'noheader'   => true,
153
-            ],
154
-            'trash_event'                   => [
155
-                'func'       => '_trash_or_restore_event',
156
-                'args'       => ['event_status' => 'trash'],
157
-                'capability' => 'ee_delete_event',
158
-                'obj_id'     => $EVT_ID,
159
-                'noheader'   => true,
160
-            ],
161
-            'trash_events'                  => [
162
-                'func'       => '_trash_or_restore_events',
163
-                'args'       => ['event_status' => 'trash'],
164
-                'capability' => 'ee_delete_events',
165
-                'noheader'   => true,
166
-            ],
167
-            'restore_event'                 => [
168
-                'func'       => '_trash_or_restore_event',
169
-                'args'       => ['event_status' => 'draft'],
170
-                'capability' => 'ee_delete_event',
171
-                'obj_id'     => $EVT_ID,
172
-                'noheader'   => true,
173
-            ],
174
-            'restore_events'                => [
175
-                'func'       => '_trash_or_restore_events',
176
-                'args'       => ['event_status' => 'draft'],
177
-                'capability' => 'ee_delete_events',
178
-                'noheader'   => true,
179
-            ],
180
-            'delete_event'                  => [
181
-                'func'       => '_delete_event',
182
-                'capability' => 'ee_delete_event',
183
-                'obj_id'     => $EVT_ID,
184
-                'noheader'   => true,
185
-            ],
186
-            'delete_events'                 => [
187
-                'func'       => '_delete_events',
188
-                'capability' => 'ee_delete_events',
189
-                'noheader'   => true,
190
-            ],
191
-            'view_report'                   => [
192
-                'func'       => '_view_report',
193
-                'capability' => 'ee_edit_events',
194
-            ],
195
-            'default_event_settings'        => [
196
-                'func'       => '_default_event_settings',
197
-                'capability' => 'manage_options',
198
-            ],
199
-            'update_default_event_settings' => [
200
-                'func'       => '_update_default_event_settings',
201
-                'capability' => 'manage_options',
202
-                'noheader'   => true,
203
-            ],
204
-            'template_settings'             => [
205
-                'func'       => '_template_settings',
206
-                'capability' => 'manage_options',
207
-            ],
208
-            // event category tab related
209
-            'add_category'                  => [
210
-                'func'       => '_category_details',
211
-                'capability' => 'ee_edit_event_category',
212
-                'args'       => ['add'],
213
-            ],
214
-            'edit_category'                 => [
215
-                'func'       => '_category_details',
216
-                'capability' => 'ee_edit_event_category',
217
-                'args'       => ['edit'],
218
-            ],
219
-            'delete_categories'             => [
220
-                'func'       => '_delete_categories',
221
-                'capability' => 'ee_delete_event_category',
222
-                'noheader'   => true,
223
-            ],
224
-            'delete_category'               => [
225
-                'func'       => '_delete_categories',
226
-                'capability' => 'ee_delete_event_category',
227
-                'noheader'   => true,
228
-            ],
229
-            'insert_category'               => [
230
-                'func'       => '_insert_or_update_category',
231
-                'args'       => ['new_category' => true],
232
-                'capability' => 'ee_edit_event_category',
233
-                'noheader'   => true,
234
-            ],
235
-            'update_category'               => [
236
-                'func'       => '_insert_or_update_category',
237
-                'args'       => ['new_category' => false],
238
-                'capability' => 'ee_edit_event_category',
239
-                'noheader'   => true,
240
-            ],
241
-            'category_list'                 => [
242
-                'func'       => '_category_list_table',
243
-                'capability' => 'ee_manage_event_categories',
244
-            ],
245
-            'preview_deletion'              => [
246
-                'func'       => 'previewDeletion',
247
-                'capability' => 'ee_delete_events',
248
-            ],
249
-            'confirm_deletion'              => [
250
-                'func'       => 'confirmDeletion',
251
-                'capability' => 'ee_delete_events',
252
-                'noheader'   => true,
253
-            ],
254
-        ];
255
-    }
256
-
257
-
258
-    /**
259
-     * Set the _page_config property for this admin page group.
260
-     */
261
-    protected function _set_page_config()
262
-    {
263
-        $post_id            = $this->request->getRequestParam('post', 0, 'int');
264
-        $EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
265
-        $this->_page_config = [
266
-            'default'                => [
267
-                'nav'           => [
268
-                    'label' => esc_html__('Overview', 'event_espresso'),
269
-                    'icon' => 'dashicons-list-view',
270
-                    'order' => 10,
271
-                ],
272
-                'list_table'    => 'Events_Admin_List_Table',
273
-                'help_tabs'     => [
274
-                    'events_overview_help_tab'                       => [
275
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
276
-                        'filename' => 'events_overview',
277
-                    ],
278
-                    'events_overview_table_column_headings_help_tab' => [
279
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
280
-                        'filename' => 'events_overview_table_column_headings',
281
-                    ],
282
-                    'events_overview_filters_help_tab'               => [
283
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
284
-                        'filename' => 'events_overview_filters',
285
-                    ],
286
-                    'events_overview_view_help_tab'                  => [
287
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
288
-                        'filename' => 'events_overview_views',
289
-                    ],
290
-                    'events_overview_other_help_tab'                 => [
291
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
292
-                        'filename' => 'events_overview_other',
293
-                    ],
294
-                ],
295
-                'require_nonce' => false,
296
-            ],
297
-            'create_new'             => [
298
-                'nav'           => [
299
-                    'label'      => esc_html__('Add New Event', 'event_espresso'),
300
-                    'icon' => 'dashicons-plus-alt',
301
-                    'order'      => 15,
302
-                    'persistent' => false,
303
-                ],
304
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
305
-                'help_tabs'     => [
306
-                    'event_editor_help_tab'                            => [
307
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
308
-                        'filename' => 'event_editor',
309
-                    ],
310
-                    'event_editor_title_richtexteditor_help_tab'       => [
311
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
312
-                        'filename' => 'event_editor_title_richtexteditor',
313
-                    ],
314
-                    'event_editor_venue_details_help_tab'              => [
315
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
316
-                        'filename' => 'event_editor_venue_details',
317
-                    ],
318
-                    'event_editor_event_datetimes_help_tab'            => [
319
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
320
-                        'filename' => 'event_editor_event_datetimes',
321
-                    ],
322
-                    'event_editor_event_tickets_help_tab'              => [
323
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
324
-                        'filename' => 'event_editor_event_tickets',
325
-                    ],
326
-                    'event_editor_event_registration_options_help_tab' => [
327
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
328
-                        'filename' => 'event_editor_event_registration_options',
329
-                    ],
330
-                    'event_editor_tags_categories_help_tab'            => [
331
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
332
-                        'filename' => 'event_editor_tags_categories',
333
-                    ],
334
-                    'event_editor_questions_registrants_help_tab'      => [
335
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
336
-                        'filename' => 'event_editor_questions_registrants',
337
-                    ],
338
-                    'event_editor_save_new_event_help_tab'             => [
339
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
340
-                        'filename' => 'event_editor_save_new_event',
341
-                    ],
342
-                    'event_editor_other_help_tab'                      => [
343
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
344
-                        'filename' => 'event_editor_other',
345
-                    ],
346
-                ],
347
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
348
-                'require_nonce' => false,
349
-            ],
350
-            'edit'                   => [
351
-                'nav'           => [
352
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
353
-                    'icon' => 'dashicons-edit',
354
-                    'order'      => 15,
355
-                    'persistent' => false,
356
-                    'url'        => $post_id
357
-                        ? EE_Admin_Page::add_query_args_and_nonce(
358
-                            ['post' => $post_id, 'action' => 'edit'],
359
-                            $this->_current_page_view_url
360
-                        )
361
-                        : $this->_admin_base_url,
362
-                ],
363
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
364
-                'help_tabs'     => [
365
-                    'event_editor_help_tab'                            => [
366
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
367
-                        'filename' => 'event_editor',
368
-                    ],
369
-                    'event_editor_title_richtexteditor_help_tab'       => [
370
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
371
-                        'filename' => 'event_editor_title_richtexteditor',
372
-                    ],
373
-                    'event_editor_venue_details_help_tab'              => [
374
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
375
-                        'filename' => 'event_editor_venue_details',
376
-                    ],
377
-                    'event_editor_event_datetimes_help_tab'            => [
378
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
379
-                        'filename' => 'event_editor_event_datetimes',
380
-                    ],
381
-                    'event_editor_event_tickets_help_tab'              => [
382
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
383
-                        'filename' => 'event_editor_event_tickets',
384
-                    ],
385
-                    'event_editor_event_registration_options_help_tab' => [
386
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
387
-                        'filename' => 'event_editor_event_registration_options',
388
-                    ],
389
-                    'event_editor_tags_categories_help_tab'            => [
390
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
391
-                        'filename' => 'event_editor_tags_categories',
392
-                    ],
393
-                    'event_editor_questions_registrants_help_tab'      => [
394
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
395
-                        'filename' => 'event_editor_questions_registrants',
396
-                    ],
397
-                    'event_editor_save_new_event_help_tab'             => [
398
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
399
-                        'filename' => 'event_editor_save_new_event',
400
-                    ],
401
-                    'event_editor_other_help_tab'                      => [
402
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
403
-                        'filename' => 'event_editor_other',
404
-                    ],
405
-                ],
406
-                'require_nonce' => false,
407
-            ],
408
-            'default_event_settings' => [
409
-                'nav'           => [
410
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
411
-                    'icon' => 'dashicons-admin-generic',
412
-                    'order' => 40,
413
-                ],
414
-                'metaboxes'     => array_merge(['_publish_post_box'], $this->_default_espresso_metaboxes),
415
-                'labels'        => [
416
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
417
-                ],
418
-                'help_tabs'     => [
419
-                    'default_settings_help_tab'        => [
420
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
421
-                        'filename' => 'events_default_settings',
422
-                    ],
423
-                    'default_settings_status_help_tab' => [
424
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
425
-                        'filename' => 'events_default_settings_status',
426
-                    ],
427
-                    'default_maximum_tickets_help_tab' => [
428
-                        'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
429
-                        'filename' => 'events_default_settings_max_tickets',
430
-                    ],
431
-                ],
432
-                'require_nonce' => false,
433
-            ],
434
-            // template settings
435
-            'template_settings'      => [
436
-                'nav'           => [
437
-                    'label' => esc_html__('Templates', 'event_espresso'),
438
-                    'icon' => 'dashicons-layout',
439
-                    'order' => 30,
440
-                ],
441
-                'metaboxes'     => $this->_default_espresso_metaboxes,
442
-                'help_tabs'     => [
443
-                    'general_settings_templates_help_tab' => [
444
-                        'title'    => esc_html__('Templates', 'event_espresso'),
445
-                        'filename' => 'general_settings_templates',
446
-                    ],
447
-                ],
448
-                'require_nonce' => false,
449
-            ],
450
-            // event category stuff
451
-            'add_category'           => [
452
-                'nav'           => [
453
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
454
-                    'icon' => 'dashicons-plus-alt',
455
-                    'order'      => 25,
456
-                    'persistent' => false,
457
-                ],
458
-                'help_tabs'     => [
459
-                    'add_category_help_tab' => [
460
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
461
-                        'filename' => 'events_add_category',
462
-                    ],
463
-                ],
464
-                'metaboxes'     => ['_publish_post_box'],
465
-                'require_nonce' => false,
466
-            ],
467
-            'edit_category'          => [
468
-                'nav'           => [
469
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
470
-                    'icon' => 'dashicons-edit',
471
-                    'order'      => 25,
472
-                    'persistent' => false,
473
-                    'url'        => $EVT_CAT_ID
474
-                        ? add_query_arg(
475
-                            ['EVT_CAT_ID' => $EVT_CAT_ID],
476
-                            $this->_current_page_view_url
477
-                        )
478
-                        : $this->_admin_base_url,
479
-                ],
480
-                'help_tabs'     => [
481
-                    'edit_category_help_tab' => [
482
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
483
-                        'filename' => 'events_edit_category',
484
-                    ],
485
-                ],
486
-                'metaboxes'     => ['_publish_post_box'],
487
-                'require_nonce' => false,
488
-            ],
489
-            'category_list'          => [
490
-                'nav'           => [
491
-                    'label' => esc_html__('Categories', 'event_espresso'),
492
-                    'icon' => 'dashicons-networking',
493
-                    'order' => 20,
494
-                ],
495
-                'list_table'    => 'Event_Categories_Admin_List_Table',
496
-                'help_tabs'     => [
497
-                    'events_categories_help_tab'                       => [
498
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
499
-                        'filename' => 'events_categories',
500
-                    ],
501
-                    'events_categories_table_column_headings_help_tab' => [
502
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
503
-                        'filename' => 'events_categories_table_column_headings',
504
-                    ],
505
-                    'events_categories_view_help_tab'                  => [
506
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
507
-                        'filename' => 'events_categories_views',
508
-                    ],
509
-                    'events_categories_other_help_tab'                 => [
510
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
511
-                        'filename' => 'events_categories_other',
512
-                    ],
513
-                ],
514
-                'metaboxes'     => $this->_default_espresso_metaboxes,
515
-                'require_nonce' => false,
516
-            ],
517
-            'preview_deletion'       => [
518
-                'nav'           => [
519
-                    'label'      => esc_html__('Preview Deletion', 'event_espresso'),
520
-                    'icon' => 'dashicons-remove',
521
-                    'order'      => 15,
522
-                    'persistent' => false,
523
-                    'url'        => '',
524
-                ],
525
-                'require_nonce' => false,
526
-            ],
527
-        ];
528
-    }
529
-
530
-
531
-    /**
532
-     * Used to register any global screen options if necessary for every route in this admin page group.
533
-     */
534
-    protected function _add_screen_options()
535
-    {
536
-    }
537
-
538
-
539
-    /**
540
-     * Implementing the screen options for the 'default' route.
541
-     *
542
-     * @throws InvalidArgumentException
543
-     * @throws InvalidDataTypeException
544
-     * @throws InvalidInterfaceException
545
-     */
546
-    protected function _add_screen_options_default()
547
-    {
548
-        $this->_per_page_screen_option();
549
-    }
550
-
551
-
552
-    /**
553
-     * Implementing screen options for the category list route.
554
-     *
555
-     * @throws InvalidArgumentException
556
-     * @throws InvalidDataTypeException
557
-     * @throws InvalidInterfaceException
558
-     */
559
-    protected function _add_screen_options_category_list()
560
-    {
561
-        $page_title              = $this->_admin_page_title;
562
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
563
-        $this->_per_page_screen_option();
564
-        $this->_admin_page_title = $page_title;
565
-    }
566
-
567
-
568
-    /**
569
-     * Used to register any global feature pointers for the admin page group.
570
-     */
571
-    protected function _add_feature_pointers()
572
-    {
573
-    }
574
-
575
-
576
-    /**
577
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
578
-     */
579
-    public function load_scripts_styles()
580
-    {
581
-        wp_register_style(
582
-            'events-admin-css',
583
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
584
-            [],
585
-            EVENT_ESPRESSO_VERSION
586
-        );
587
-        wp_register_style(
588
-            'ee-cat-admin',
589
-            EVENTS_ASSETS_URL . 'ee-cat-admin.css',
590
-            [],
591
-            EVENT_ESPRESSO_VERSION
592
-        );
593
-        wp_enqueue_style('events-admin-css');
594
-        wp_enqueue_style('ee-cat-admin');
595
-        // scripts
596
-        wp_register_script(
597
-            'event_editor_js',
598
-            EVENTS_ASSETS_URL . 'event_editor.js',
599
-            ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
600
-            EVENT_ESPRESSO_VERSION,
601
-            true
602
-        );
603
-    }
604
-
605
-
606
-    /**
607
-     * Enqueuing scripts and styles specific to this view
608
-     */
609
-    public function load_scripts_styles_create_new()
610
-    {
611
-        $this->load_scripts_styles_edit();
612
-    }
613
-
614
-
615
-    /**
616
-     * Enqueuing scripts and styles specific to this view
617
-     */
618
-    public function load_scripts_styles_edit()
619
-    {
620
-        // styles
621
-        wp_enqueue_style('espresso-ui-theme');
622
-        wp_register_style(
623
-            'event-editor-css',
624
-            EVENTS_ASSETS_URL . 'event-editor.css',
625
-            ['ee-admin-css'],
626
-            EVENT_ESPRESSO_VERSION
627
-        );
628
-        wp_enqueue_style('event-editor-css');
629
-        // scripts
630
-        if (! $this->admin_config->useAdvancedEditor()) {
631
-            wp_register_script(
632
-                'event-datetime-metabox',
633
-                EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
634
-                ['event_editor_js', 'ee-datepicker'],
635
-                EVENT_ESPRESSO_VERSION
636
-            );
637
-            wp_enqueue_script('event-datetime-metabox');
638
-        }
639
-    }
640
-
641
-
642
-    /**
643
-     * Populating the _views property for the category list table view.
644
-     */
645
-    protected function _set_list_table_views_category_list()
646
-    {
647
-        $this->_views = [
648
-            'all' => [
649
-                'slug'        => 'all',
650
-                'label'       => esc_html__('All', 'event_espresso'),
651
-                'count'       => 0,
652
-                'bulk_action' => [
653
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
654
-                ],
655
-            ],
656
-        ];
657
-    }
658
-
659
-
660
-    /**
661
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
662
-     */
663
-    public function admin_init()
664
-    {
665
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
666
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
667
-            'event_espresso'
668
-        );
669
-    }
670
-
671
-
672
-    /**
673
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
674
-     * group.
675
-     */
676
-    public function admin_notices()
677
-    {
678
-    }
679
-
680
-
681
-    /**
682
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
683
-     * this admin page group.
684
-     */
685
-    public function admin_footer_scripts()
686
-    {
687
-    }
688
-
689
-
690
-    /**
691
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
692
-     * warning (via EE_Error::add_error());
693
-     *
694
-     * @param EE_Event $event Event object
695
-     * @param string   $req_type
696
-     * @return void
697
-     * @throws EE_Error
698
-     * @throws ReflectionException
699
-     */
700
-    public function verify_event_edit($event = null, $req_type = '')
701
-    {
702
-        // don't need to do this when processing
703
-        if (! empty($req_type)) {
704
-            return;
705
-        }
706
-        // no event?
707
-        if (! $event instanceof EE_Event) {
708
-            $event = $this->_cpt_model_obj;
709
-        }
710
-        // STILL no event?
711
-        if (! $event instanceof EE_Event) {
712
-            return;
713
-        }
714
-        $orig_status = $event->status();
715
-        // first check if event is active.
716
-        if (
717
-            $orig_status === EEM_Event::cancelled
718
-            || $orig_status === EEM_Event::postponed
719
-            || $event->is_expired()
720
-            || $event->is_inactive()
721
-        ) {
722
-            return;
723
-        }
724
-        // made it here so it IS active... next check that any of the tickets are sold.
725
-        if ($event->is_sold_out(true)) {
726
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
727
-                EE_Error::add_attention(
728
-                    sprintf(
729
-                        esc_html__(
730
-                            '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.',
731
-                            'event_espresso'
732
-                        ),
733
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
734
-                    )
735
-                );
736
-            }
737
-            return;
738
-        }
739
-        if ($orig_status === EEM_Event::sold_out) {
740
-            EE_Error::add_attention(
741
-                sprintf(
742
-                    esc_html__(
743
-                        '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.',
744
-                        'event_espresso'
745
-                    ),
746
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
747
-                )
748
-            );
749
-        }
750
-        // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
751
-        if (! $event->tickets_on_sale()) {
752
-            return;
753
-        }
754
-        // made it here so show warning
755
-        $this->_edit_event_warning();
756
-    }
757
-
758
-
759
-    /**
760
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
761
-     * When needed, hook this into a EE_Error::add_error() notice.
762
-     *
763
-     * @access protected
764
-     * @return void
765
-     */
766
-    protected function _edit_event_warning()
767
-    {
768
-        // we don't want to add warnings during these requests
769
-        if ($this->request->getRequestParam('action') === 'editpost') {
770
-            return;
771
-        }
772
-        EE_Error::add_attention(
773
-            sprintf(
774
-                esc_html__(
775
-                    'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
776
-                    'event_espresso'
777
-                ),
778
-                '<a class="espresso-help-tab-lnk ee-help-tab-link">',
779
-                '</a>'
780
-            )
781
-        );
782
-    }
783
-
784
-
785
-    /**
786
-     * When a user is creating a new event, notify them if they haven't set their timezone.
787
-     * Otherwise, do the normal logic
788
-     *
789
-     * @return void
790
-     * @throws EE_Error
791
-     * @throws InvalidArgumentException
792
-     * @throws InvalidDataTypeException
793
-     * @throws InvalidInterfaceException
794
-     */
795
-    protected function _create_new_cpt_item()
796
-    {
797
-        $has_timezone_string = get_option('timezone_string');
798
-        // only nag them about setting their timezone if it's their first event, and they haven't already done it
799
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
800
-            EE_Error::add_attention(
801
-                sprintf(
802
-                    esc_html__(
803
-                        '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',
804
-                        'event_espresso'
805
-                    ),
806
-                    '<br>',
807
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
808
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
809
-                    . '</select>',
810
-                    '<button class="button button--secondary timezone-submit">',
811
-                    '</button><span class="spinner"></span>'
812
-                ),
813
-                __FILE__,
814
-                __FUNCTION__,
815
-                __LINE__
816
-            );
817
-        }
818
-        parent::_create_new_cpt_item();
819
-    }
820
-
821
-
822
-    /**
823
-     * Sets the _views property for the default route in this admin page group.
824
-     */
825
-    protected function _set_list_table_views_default()
826
-    {
827
-        $this->_views = [
828
-            'all'   => [
829
-                'slug'        => 'all',
830
-                'label'       => esc_html__('View All Events', 'event_espresso'),
831
-                'count'       => 0,
832
-                'bulk_action' => [
833
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
834
-                ],
835
-            ],
836
-            'draft' => [
837
-                'slug'        => 'draft',
838
-                'label'       => esc_html__('Draft', 'event_espresso'),
839
-                'count'       => 0,
840
-                'bulk_action' => [
841
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
842
-                ],
843
-            ],
844
-        ];
845
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
846
-            $this->_views['trash'] = [
847
-                'slug'        => 'trash',
848
-                'label'       => esc_html__('Trash', 'event_espresso'),
849
-                'count'       => 0,
850
-                'bulk_action' => [
851
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
852
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
853
-                ],
854
-            ];
855
-        }
856
-    }
857
-
858
-
859
-    /**
860
-     * Provides the legend item array for the default list table view.
861
-     *
862
-     * @return array
863
-     * @throws EE_Error
864
-     * @throws EE_Error
865
-     */
866
-    protected function _event_legend_items()
867
-    {
868
-        $items    = [
869
-            'view_details'   => [
870
-                'class' => 'dashicons dashicons-visibility',
871
-                'desc'  => esc_html__('View Event', 'event_espresso'),
872
-            ],
873
-            'edit_event'     => [
874
-                'class' => 'dashicons dashicons-calendar-alt',
875
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
876
-            ],
877
-            'view_attendees' => [
878
-                'class' => 'dashicons dashicons-groups',
879
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
880
-            ],
881
-        ];
882
-        $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
883
-        $statuses = [
884
-            'sold_out_status'  => [
885
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::sold_out,
886
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
887
-            ],
888
-            'active_status'    => [
889
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::active,
890
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
891
-            ],
892
-            'upcoming_status'  => [
893
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::upcoming,
894
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
895
-            ],
896
-            'postponed_status' => [
897
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::postponed,
898
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
899
-            ],
900
-            'cancelled_status' => [
901
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::cancelled,
902
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
903
-            ],
904
-            'expired_status'   => [
905
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::expired,
906
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
907
-            ],
908
-            'inactive_status'  => [
909
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::inactive,
910
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
911
-            ],
912
-        ];
913
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
914
-        return array_merge($items, $statuses);
915
-    }
916
-
917
-
918
-    /**
919
-     * @return EEM_Event
920
-     * @throws EE_Error
921
-     * @throws InvalidArgumentException
922
-     * @throws InvalidDataTypeException
923
-     * @throws InvalidInterfaceException
924
-     * @throws ReflectionException
925
-     */
926
-    private function _event_model()
927
-    {
928
-        if (! $this->_event_model instanceof EEM_Event) {
929
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
930
-        }
931
-        return $this->_event_model;
932
-    }
933
-
934
-
935
-    /**
936
-     * Adds extra buttons to the WP CPT permalink field row.
937
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
938
-     *
939
-     * @param string $return    the current html
940
-     * @param int    $id        the post id for the page
941
-     * @param string $new_title What the title is
942
-     * @param string $new_slug  what the slug is
943
-     * @return string            The new html string for the permalink area
944
-     */
945
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
946
-    {
947
-        // make sure this is only when editing
948
-        if (! empty($id)) {
949
-            $post = get_post($id);
950
-            $return .= '<a class="button button--small button--secondary" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
951
-                       . esc_html__('Shortcode', 'event_espresso')
952
-                       . '</a> ';
953
-            $return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
954
-                       . $post->ID
955
-                       . ']">';
956
-        }
957
-        return $return;
958
-    }
959
-
960
-
961
-    /**
962
-     * _events_overview_list_table
963
-     * This contains the logic for showing the events_overview list
964
-     *
965
-     * @access protected
966
-     * @return void
967
-     * @throws DomainException
968
-     * @throws EE_Error
969
-     * @throws InvalidArgumentException
970
-     * @throws InvalidDataTypeException
971
-     * @throws InvalidInterfaceException
972
-     */
973
-    protected function _events_overview_list_table()
974
-    {
975
-        $after_list_table                           = [];
976
-        $links_html = EEH_HTML::div('', '', 'ee-admin-section ee-layout-stack');
977
-        $links_html .= EEH_HTML::h3(esc_html__('Links', 'event_espresso'));
978
-        $links_html .= EEH_HTML::div(
979
-            EEH_Template::get_button_or_link(
980
-                get_post_type_archive_link('espresso_events'),
981
-                esc_html__('View Event Archive Page', 'event_espresso'),
982
-                'button button--small button--secondary'
983
-            ),
984
-            '',
985
-            'ee-admin-button-row ee-admin-button-row--align-start'
986
-        );
987
-        $links_html .= EEH_HTML::divx();
988
-
989
-        $after_list_table['view_event_list_button'] = $links_html;
990
-
991
-        $after_list_table['legend'] = $this->_display_legend($this->_event_legend_items());
992
-        $this->_admin_page_title                    .= ' ' . $this->get_action_link_or_button(
993
-            'create_new',
994
-            'add',
995
-            [],
996
-            'add-new-h2'
997
-        );
998
-
999
-        $this->_template_args['after_list_table']   = array_merge(
1000
-            (array) $this->_template_args['after_list_table'],
1001
-            $after_list_table
1002
-        );
1003
-        $this->display_admin_list_table_page_with_no_sidebar();
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * this allows for extra misc actions in the default WP publish box
1009
-     *
1010
-     * @return void
1011
-     * @throws DomainException
1012
-     * @throws EE_Error
1013
-     * @throws InvalidArgumentException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws InvalidInterfaceException
1016
-     * @throws ReflectionException
1017
-     */
1018
-    public function extra_misc_actions_publish_box()
1019
-    {
1020
-        $this->_generate_publish_box_extra_content();
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1026
-     * saved.
1027
-     * Typically you would use this to save any additional data.
1028
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
1029
-     * ALSO very important.  When a post transitions from scheduled to published,
1030
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1031
-     * other meta saves. So MAKE sure that you handle this accordingly.
1032
-     *
1033
-     * @access protected
1034
-     * @abstract
1035
-     * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
1036
-     * @param WP_Post $post    The post object of the cpt that was saved.
1037
-     * @return void
1038
-     * @throws EE_Error
1039
-     * @throws InvalidArgumentException
1040
-     * @throws InvalidDataTypeException
1041
-     * @throws InvalidInterfaceException
1042
-     * @throws ReflectionException
1043
-     */
1044
-    protected function _insert_update_cpt_item($post_id, $post)
1045
-    {
1046
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1047
-            // get out we're not processing an event save.
1048
-            return;
1049
-        }
1050
-        $event_values = [
1051
-            'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1052
-            'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1053
-            'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1054
-        ];
1055
-        // check if the new EDTR reg options meta box is being used, and if so, don't run updates for legacy version
1056
-        if (! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1057
-            $event_values['EVT_display_ticket_selector']     = $this->request->getRequestParam(
1058
-                'display_ticket_selector',
1059
-                false,
1060
-                'bool'
1061
-            );
1062
-            $event_values['EVT_additional_limit']            = min(
1063
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1064
-                $this->request->getRequestParam(
1065
-                    'additional_limit',
1066
-                    EEM_Event::get_default_additional_limit(),
1067
-                    'int'
1068
-                )
1069
-            );
1070
-            $event_values['EVT_default_registration_status'] = $this->request->getRequestParam(
1071
-                'EVT_default_registration_status',
1072
-                EE_Registry::instance()->CFG->registration->default_STS_ID
1073
-            );
1074
-
1075
-            $event_values['EVT_external_URL'] = $this->request->getRequestParam('externalURL');
1076
-            $event_values['EVT_phone']        = $this->request->getRequestParam('event_phone');
1077
-            $event_values['EVT_display_desc'] = $this->request->getRequestParam('display_desc', false, 'bool');
1078
-        }
1079
-        // update event
1080
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1081
-        // get event_object for other metaboxes...
1082
-        // though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1083
-        // i have to setup where conditions to override the filters in the model
1084
-        // that filter out auto-draft and inherit statuses so we GET the inherit id!
1085
-        /** @var EE_Event $event */
1086
-        $event = $this->_event_model()->get_one(
1087
-            [
1088
-                [
1089
-                    $this->_event_model()->primary_key_name() => $post_id,
1090
-                    'OR'                                      => [
1091
-                        'status'   => $post->post_status,
1092
-                        // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1093
-                        // but the returned object here has a status of "publish", so use the original post status as well
1094
-                        'status*1' => $this->request->getRequestParam('original_post_status'),
1095
-                    ],
1096
-                ],
1097
-            ]
1098
-        );
1099
-
1100
-        // the following are default callbacks for event attachment updates
1101
-        // that can be overridden by caffeinated functionality and/or addons.
1102
-        $event_update_callbacks = [];
1103
-        if (! $this->admin_config->useAdvancedEditor()) {
1104
-            $event_update_callbacks['_default_venue_update']   = [$this, '_default_venue_update'];
1105
-            $event_update_callbacks['_default_tickets_update'] = [$this, '_default_tickets_update'];
1106
-        }
1107
-        $event_update_callbacks = apply_filters(
1108
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1109
-            $event_update_callbacks
1110
-        );
1111
-
1112
-        $att_success = true;
1113
-        foreach ($event_update_callbacks as $e_callback) {
1114
-            $_success = is_callable($e_callback)
1115
-                ? $e_callback($event, $this->request->requestParams())
1116
-                : false;
1117
-            // if ANY of these updates fail then we want the appropriate global error message
1118
-            $att_success = $_success !== false ? $att_success : false;
1119
-        }
1120
-        // any errors?
1121
-        if ($success && $att_success === false) {
1122
-            EE_Error::add_error(
1123
-                esc_html__(
1124
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1125
-                    'event_espresso'
1126
-                ),
1127
-                __FILE__,
1128
-                __FUNCTION__,
1129
-                __LINE__
1130
-            );
1131
-        } elseif ($success === false) {
1132
-            EE_Error::add_error(
1133
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1134
-                __FILE__,
1135
-                __FUNCTION__,
1136
-                __LINE__
1137
-            );
1138
-        }
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * @param int $post_id
1144
-     * @param int $revision_id
1145
-     * @throws EE_Error
1146
-     * @throws EE_Error
1147
-     * @throws ReflectionException
1148
-     * @see parent::restore_item()
1149
-     */
1150
-    protected function _restore_cpt_item($post_id, $revision_id)
1151
-    {
1152
-        // copy existing event meta to new post
1153
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1154
-        if ($post_evt instanceof EE_Event) {
1155
-            // meta revision restore
1156
-            $post_evt->restore_revision($revision_id);
1157
-            // related objs restore
1158
-            $post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1159
-        }
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * Attach the venue to the Event
1165
-     *
1166
-     * @param EE_Event $event Event Object to add the venue to
1167
-     * @param array    $data  The request data from the form
1168
-     * @return bool           Success or fail.
1169
-     * @throws EE_Error
1170
-     * @throws ReflectionException
1171
-     */
1172
-    protected function _default_venue_update(EE_Event $event, $data)
1173
-    {
1174
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1175
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1176
-        $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1177
-        // very important.  If we don't have a venue name...
1178
-        // then we'll get out because not necessary to create empty venue
1179
-        if (empty($data['venue_title'])) {
1180
-            return false;
1181
-        }
1182
-        $venue_array = [
1183
-            'VNU_wp_user'         => $event->get('EVT_wp_user'),
1184
-            'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1185
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1186
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1187
-            'VNU_short_desc'      => ! empty($data['venue_short_description'])
1188
-                ? $data['venue_short_description']
1189
-                : null,
1190
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1191
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1192
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1193
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1194
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1195
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1196
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1197
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1198
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1199
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1200
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1201
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1202
-            'status'              => 'publish',
1203
-        ];
1204
-        // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1205
-        if (! empty($venue_id)) {
1206
-            $update_where  = [$venue_model->primary_key_name() => $venue_id];
1207
-            $rows_affected = $venue_model->update($venue_array, [$update_where]);
1208
-            // we've gotta make sure that the venue is always attached to a revision..
1209
-            // add_relation_to should take care of making sure that the relation is already present.
1210
-            $event->_add_relation_to($venue_id, 'Venue');
1211
-            return $rows_affected > 0;
1212
-        }
1213
-        // we insert the venue
1214
-        $venue_id = $venue_model->insert($venue_array);
1215
-        $event->_add_relation_to($venue_id, 'Venue');
1216
-        return ! empty($venue_id);
1217
-        // when we have the ancestor come in it's already been handled by the revision save.
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1223
-     *
1224
-     * @param EE_Event $event The Event object we're attaching data to
1225
-     * @param array    $data  The request data from the form
1226
-     * @return array
1227
-     * @throws EE_Error
1228
-     * @throws ReflectionException
1229
-     * @throws Exception
1230
-     */
1231
-    protected function _default_tickets_update(EE_Event $event, $data)
1232
-    {
1233
-        if ($this->admin_config->useAdvancedEditor()) {
1234
-            return [];
1235
-        }
1236
-        $datetime       = null;
1237
-        $saved_tickets  = [];
1238
-        $event_timezone = $event->get_timezone();
1239
-        $date_formats   = ['Y-m-d', 'h:i a'];
1240
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1241
-            // trim all values to ensure any excess whitespace is removed.
1242
-            $datetime_data                = array_map('trim', $datetime_data);
1243
-            $datetime_data['DTT_EVT_end'] =
1244
-                isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1245
-                    ? $datetime_data['DTT_EVT_end']
1246
-                    : $datetime_data['DTT_EVT_start'];
1247
-            $datetime_values              = [
1248
-                'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1249
-                'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1250
-                'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1251
-                'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1252
-                'DTT_order'     => $row,
1253
-            ];
1254
-            // if we have an id then let's get existing object first and then set the new values.
1255
-            //  Otherwise we instantiate a new object for save.
1256
-            if (! empty($datetime_data['DTT_ID'])) {
1257
-                $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1258
-                if (! $datetime instanceof EE_Datetime) {
1259
-                    throw new RuntimeException(
1260
-                        sprintf(
1261
-                            esc_html__(
1262
-                                'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1263
-                                'event_espresso'
1264
-                            ),
1265
-                            $datetime_data['DTT_ID']
1266
-                        )
1267
-                    );
1268
-                }
1269
-                $datetime->set_date_format($date_formats[0]);
1270
-                $datetime->set_time_format($date_formats[1]);
1271
-                foreach ($datetime_values as $field => $value) {
1272
-                    $datetime->set($field, $value);
1273
-                }
1274
-            } else {
1275
-                $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1276
-            }
1277
-            if (! $datetime instanceof EE_Datetime) {
1278
-                throw new RuntimeException(
1279
-                    sprintf(
1280
-                        esc_html__(
1281
-                            'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1282
-                            'event_espresso'
1283
-                        ),
1284
-                        print_r($datetime_values, true)
1285
-                    )
1286
-                );
1287
-            }
1288
-            // before going any further make sure our dates are setup correctly
1289
-            // so that the end date is always equal or greater than the start date.
1290
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1291
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1292
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1293
-            }
1294
-            $datetime->save();
1295
-            $event->_add_relation_to($datetime, 'Datetime');
1296
-        }
1297
-        // no datetimes get deleted so we don't do any of that logic here.
1298
-        // update tickets next
1299
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1300
-
1301
-        // set up some default start and end dates in case those are not present in the incoming data
1302
-        $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1303
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1304
-        // use the start date of the first datetime for the end date
1305
-        $first_datetime   = $event->first_datetime();
1306
-        $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1307
-
1308
-        // now process the incoming data
1309
-        foreach ($data['edit_tickets'] as $row => $ticket_data) {
1310
-            $update_prices = false;
1311
-            $ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1312
-                ? $data['edit_prices'][ $row ][1]['PRC_amount']
1313
-                : 0;
1314
-            // trim inputs to ensure any excess whitespace is removed.
1315
-            $ticket_data   = array_map('trim', $ticket_data);
1316
-            $ticket_values = [
1317
-                'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1318
-                'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1319
-                'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1320
-                'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1321
-                'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1322
-                    ? $ticket_data['TKT_start_date']
1323
-                    : $default_start_date,
1324
-                'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1325
-                    ? $ticket_data['TKT_end_date']
1326
-                    : $default_end_date,
1327
-                'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1328
-                                     || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1329
-                    ? $ticket_data['TKT_qty']
1330
-                    : EE_INF,
1331
-                'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1332
-                                     || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1333
-                    ? $ticket_data['TKT_uses']
1334
-                    : EE_INF,
1335
-                'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1336
-                'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1337
-                'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1338
-                'TKT_price'       => $ticket_price,
1339
-                'TKT_row'         => $row,
1340
-            ];
1341
-            // if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1342
-            // which means in turn that the prices will become new prices as well.
1343
-            if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1344
-                $ticket_values['TKT_ID']         = 0;
1345
-                $ticket_values['TKT_is_default'] = 0;
1346
-                $update_prices                   = true;
1347
-            }
1348
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
1349
-            // we actually do our saves ahead of adding any relations because its entirely possible that this
1350
-            // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1351
-            // keep in mind that if the ticket has been sold (and we have changed pricing information),
1352
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1353
-            if (! empty($ticket_data['TKT_ID'])) {
1354
-                $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1355
-                if (! $existing_ticket instanceof EE_Ticket) {
1356
-                    throw new RuntimeException(
1357
-                        sprintf(
1358
-                            esc_html__(
1359
-                                'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1360
-                                'event_espresso'
1361
-                            ),
1362
-                            $ticket_data['TKT_ID']
1363
-                        )
1364
-                    );
1365
-                }
1366
-                $ticket_sold = $existing_ticket->count_related(
1367
-                    'Registration',
1368
-                    [
1369
-                            [
1370
-                                'STS_ID' => [
1371
-                                    'NOT IN',
1372
-                                    [EEM_Registration::status_id_incomplete],
1373
-                                ],
1374
-                            ],
1375
-                        ]
1376
-                ) > 0;
1377
-                // let's just check the total price for the existing ticket and determine if it matches the new total price.
1378
-                // if they are different then we create a new ticket (if $ticket_sold)
1379
-                // if they aren't different then we go ahead and modify existing ticket.
1380
-                $create_new_ticket = $ticket_sold
1381
-                                     && $ticket_price !== $existing_ticket->price()
1382
-                                     && ! $existing_ticket->deleted();
1383
-                $existing_ticket->set_date_format($date_formats[0]);
1384
-                $existing_ticket->set_time_format($date_formats[1]);
1385
-                // set new values
1386
-                foreach ($ticket_values as $field => $value) {
1387
-                    if ($field == 'TKT_qty') {
1388
-                        $existing_ticket->set_qty($value);
1389
-                    } elseif ($field == 'TKT_price') {
1390
-                        $existing_ticket->set('TKT_price', $ticket_price);
1391
-                    } else {
1392
-                        $existing_ticket->set($field, $value);
1393
-                    }
1394
-                }
1395
-                $ticket = $existing_ticket;
1396
-                // if $create_new_ticket is false then we can safely update the existing ticket.
1397
-                //  Otherwise we have to create a new ticket.
1398
-                if ($create_new_ticket) {
1399
-                    // archive the old ticket first
1400
-                    $existing_ticket->set('TKT_deleted', 1);
1401
-                    $existing_ticket->save();
1402
-                    // make sure this ticket is still recorded in our $saved_tickets
1403
-                    // so we don't run it through the regular trash routine.
1404
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1405
-                    // create new ticket that's a copy of the existing except,
1406
-                    // (a new id of course and not archived) AND has the new TKT_price associated with it.
1407
-                    $new_ticket = clone $existing_ticket;
1408
-                    $new_ticket->set('TKT_ID', 0);
1409
-                    $new_ticket->set('TKT_deleted', 0);
1410
-                    $new_ticket->set('TKT_sold', 0);
1411
-                    // now we need to make sure that $new prices are created as well and attached to new ticket.
1412
-                    $update_prices = true;
1413
-                    $ticket        = $new_ticket;
1414
-                }
1415
-            } else {
1416
-                // no TKT_id so a new ticket
1417
-                $ticket_values['TKT_price'] = $ticket_price;
1418
-                $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1419
-                $update_prices              = true;
1420
-            }
1421
-            if (! $ticket instanceof EE_Ticket) {
1422
-                throw new RuntimeException(
1423
-                    sprintf(
1424
-                        esc_html__(
1425
-                            'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1426
-                            'event_espresso'
1427
-                        ),
1428
-                        print_r($ticket_values, true)
1429
-                    )
1430
-                );
1431
-            }
1432
-            // cap ticket qty by datetime reg limits
1433
-            $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1434
-            // update ticket.
1435
-            $ticket->save();
1436
-            // before going any further make sure our dates are setup correctly
1437
-            // so that the end date is always equal or greater than the start date.
1438
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1439
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1440
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1441
-                $ticket->save();
1442
-            }
1443
-            // initially let's add the ticket to the datetime
1444
-            $datetime->_add_relation_to($ticket, 'Ticket');
1445
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1446
-            // add prices to ticket
1447
-            $prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1448
-                ? $data['edit_prices'][ $row ]
1449
-                : [];
1450
-            $this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1451
-        }
1452
-        // however now we need to handle permanently deleting tickets via the ui.
1453
-        // Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1454
-        // However, it does allow for deleting tickets that have no tickets sold,
1455
-        // in which case we want to get rid of permanently because there is no need to save in db.
1456
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? [] : $old_tickets;
1457
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1458
-        foreach ($tickets_removed as $id) {
1459
-            $id = absint($id);
1460
-            // get the ticket for this id
1461
-            $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1462
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1463
-                continue;
1464
-            }
1465
-            // need to get all the related datetimes on this ticket and remove from every single one of them
1466
-            // (remember this process can ONLY kick off if there are NO tickets sold)
1467
-            $related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1468
-            foreach ($related_datetimes as $related_datetime) {
1469
-                $ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1470
-            }
1471
-            // need to do the same for prices (except these prices can also be deleted because again,
1472
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1473
-            $ticket_to_remove->delete_related_permanently('Price');
1474
-            // finally let's delete this ticket
1475
-            // (which should not be blocked at this point b/c we've removed all our relationships)
1476
-            $ticket_to_remove->delete_permanently();
1477
-        }
1478
-        return [$datetime, $saved_tickets];
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * This attaches a list of given prices to a ticket.
1484
-     * Note we dont' have to worry about ever removing relationships (or archiving prices)
1485
-     * because if there is a change in price information on a ticket, a new ticket is created anyways
1486
-     * so the archived ticket will retain the old price info and prices are automatically "archived" via the ticket.
1487
-     *
1488
-     * @access  private
1489
-     * @param array     $prices_data Array of prices from the form.
1490
-     * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1491
-     * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1492
-     * @return  void
1493
-     * @throws EE_Error
1494
-     * @throws ReflectionException
1495
-     */
1496
-    private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1497
-    {
1498
-        $timezone = $ticket->get_timezone();
1499
-        foreach ($prices_data as $row => $price_data) {
1500
-            $price_values = [
1501
-                'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1502
-                'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1503
-                'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1504
-                'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1505
-                'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1506
-                'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1507
-                'PRC_order'      => $row,
1508
-            ];
1509
-            if ($new_prices || empty($price_values['PRC_ID'])) {
1510
-                $price_values['PRC_ID'] = 0;
1511
-                $price                  = EE_Price::new_instance($price_values, $timezone);
1512
-            } else {
1513
-                $price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1514
-                // update this price with new values
1515
-                foreach ($price_values as $field => $new_price) {
1516
-                    $price->set($field, $new_price);
1517
-                }
1518
-            }
1519
-            if (! $price instanceof EE_Price) {
1520
-                throw new RuntimeException(
1521
-                    sprintf(
1522
-                        esc_html__(
1523
-                            'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1524
-                            'event_espresso'
1525
-                        ),
1526
-                        print_r($price_values, true)
1527
-                    )
1528
-                );
1529
-            }
1530
-            $price->save();
1531
-            $ticket->_add_relation_to($price, 'Price');
1532
-        }
1533
-    }
1534
-
1535
-
1536
-    /**
1537
-     * Add in our autosave ajax handlers
1538
-     *
1539
-     */
1540
-    protected function _ee_autosave_create_new()
1541
-    {
1542
-    }
1543
-
1544
-
1545
-    /**
1546
-     * More autosave handlers.
1547
-     */
1548
-    protected function _ee_autosave_edit()
1549
-    {
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * @throws EE_Error
1555
-     * @throws ReflectionException
1556
-     */
1557
-    private function _generate_publish_box_extra_content()
1558
-    {
1559
-        // load formatter helper
1560
-        // args for getting related registrations
1561
-        $approved_query_args        = [
1562
-            [
1563
-                'REG_deleted' => 0,
1564
-                'STS_ID'      => EEM_Registration::status_id_approved,
1565
-            ],
1566
-        ];
1567
-        $not_approved_query_args    = [
1568
-            [
1569
-                'REG_deleted' => 0,
1570
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1571
-            ],
1572
-        ];
1573
-        $pending_payment_query_args = [
1574
-            [
1575
-                'REG_deleted' => 0,
1576
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1577
-            ],
1578
-        ];
1579
-        // publish box
1580
-        $publish_box_extra_args = [
1581
-            'view_approved_reg_url'        => add_query_arg(
1582
-                [
1583
-                    'action'      => 'default',
1584
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1585
-                    '_reg_status' => EEM_Registration::status_id_approved,
1586
-                ],
1587
-                REG_ADMIN_URL
1588
-            ),
1589
-            'view_not_approved_reg_url'    => add_query_arg(
1590
-                [
1591
-                    'action'      => 'default',
1592
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1593
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1594
-                ],
1595
-                REG_ADMIN_URL
1596
-            ),
1597
-            'view_pending_payment_reg_url' => add_query_arg(
1598
-                [
1599
-                    'action'      => 'default',
1600
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1601
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1602
-                ],
1603
-                REG_ADMIN_URL
1604
-            ),
1605
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1606
-                'Registration',
1607
-                $approved_query_args
1608
-            ),
1609
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1610
-                'Registration',
1611
-                $not_approved_query_args
1612
-            ),
1613
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1614
-                'Registration',
1615
-                $pending_payment_query_args
1616
-            ),
1617
-            'misc_pub_section_class'       => apply_filters(
1618
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1619
-                'misc-pub-section'
1620
-            ),
1621
-        ];
1622
-        ob_start();
1623
-        do_action(
1624
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1625
-            $this->_cpt_model_obj
1626
-        );
1627
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1628
-        // load template
1629
-        EEH_Template::display_template(
1630
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1631
-            $publish_box_extra_args
1632
-        );
1633
-    }
1634
-
1635
-
1636
-    /**
1637
-     * @return EE_Event
1638
-     */
1639
-    public function get_event_object()
1640
-    {
1641
-        return $this->_cpt_model_obj;
1642
-    }
1643
-
1644
-
1645
-
1646
-
1647
-    /** METABOXES * */
1648
-    /**
1649
-     * _register_event_editor_meta_boxes
1650
-     * add all metaboxes related to the event_editor
1651
-     *
1652
-     * @return void
1653
-     * @throws EE_Error
1654
-     * @throws ReflectionException
1655
-     */
1656
-    protected function _register_event_editor_meta_boxes()
1657
-    {
1658
-        $this->verify_cpt_object();
1659
-        $use_advanced_editor = $this->admin_config->useAdvancedEditor();
1660
-        // check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
1661
-        if (! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1662
-            $this->addMetaBox(
1663
-                'espresso_event_editor_event_options',
1664
-                esc_html__('Event Registration Options', 'event_espresso'),
1665
-                [$this, 'registration_options_meta_box'],
1666
-                $this->page_slug,
1667
-                'side'
1668
-            );
1669
-        }
1670
-        if (! $use_advanced_editor) {
1671
-            $this->addMetaBox(
1672
-                'espresso_event_editor_tickets',
1673
-                esc_html__('Event Datetime & Ticket', 'event_espresso'),
1674
-                [$this, 'ticket_metabox'],
1675
-                $this->page_slug,
1676
-                'normal',
1677
-                'high'
1678
-            );
1679
-        } elseif ($this->feature->allowed('use_reg_options_meta_box')) {
1680
-            add_action(
1681
-                'add_meta_boxes_espresso_events',
1682
-                function () {
1683
-                    global $current_screen;
1684
-                    remove_meta_box('authordiv', $current_screen, 'normal');
1685
-                },
1686
-                99
1687
-            );
1688
-        }
1689
-        // NOTE: if you're looking for other metaboxes in here,
1690
-        // where a metabox has a related management page in the admin
1691
-        // you will find it setup in the related management page's "_Hooks" file.
1692
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1693
-    }
1694
-
1695
-
1696
-    /**
1697
-     * @throws DomainException
1698
-     * @throws EE_Error
1699
-     * @throws ReflectionException
1700
-     */
1701
-    public function ticket_metabox()
1702
-    {
1703
-        $existing_datetime_ids = $existing_ticket_ids = [];
1704
-        // defaults for template args
1705
-        $template_args = [
1706
-            'existing_datetime_ids'    => '',
1707
-            'event_datetime_help_link' => '',
1708
-            'ticket_options_help_link' => '',
1709
-            'time'                     => null,
1710
-            'ticket_rows'              => '',
1711
-            'existing_ticket_ids'      => '',
1712
-            'total_ticket_rows'        => 1,
1713
-            'ticket_js_structure'      => '',
1714
-            'trash_icon'               => 'dashicons dashicons-lock',
1715
-            'disabled'                 => '',
1716
-        ];
1717
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1718
-        /**
1719
-         * 1. Start with retrieving Datetimes
1720
-         * 2. Fore each datetime get related tickets
1721
-         * 3. For each ticket get related prices
1722
-         */
1723
-        /** @var EEM_Datetime $datetime_model */
1724
-        $datetime_model = EE_Registry::instance()->load_model('Datetime');
1725
-        /** @var EEM_Ticket $datetime_model */
1726
-        $ticket_model = EE_Registry::instance()->load_model('Ticket');
1727
-        $times        = $datetime_model->get_all_event_dates($event_id);
1728
-        /** @type EE_Datetime $first_datetime */
1729
-        $first_datetime = reset($times);
1730
-        // do we get related tickets?
1731
-        if (
1732
-            $first_datetime instanceof EE_Datetime
1733
-            && $first_datetime->ID() !== 0
1734
-        ) {
1735
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1736
-            $template_args['time']   = $first_datetime;
1737
-            $related_tickets         = $first_datetime->tickets(
1738
-                [
1739
-                    ['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1740
-                    'default_where_conditions' => 'none',
1741
-                ]
1742
-            );
1743
-            if (! empty($related_tickets)) {
1744
-                $template_args['total_ticket_rows'] = count($related_tickets);
1745
-                $row                                = 0;
1746
-                foreach ($related_tickets as $ticket) {
1747
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1748
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1749
-                    $row++;
1750
-                }
1751
-            } else {
1752
-                $template_args['total_ticket_rows'] = 1;
1753
-                /** @type EE_Ticket $ticket */
1754
-                $ticket                       = $ticket_model->create_default_object();
1755
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1756
-            }
1757
-        } else {
1758
-            $template_args['time'] = $times[0];
1759
-            /** @type EE_Ticket[] $tickets */
1760
-            $tickets                      = $ticket_model->get_all_default_tickets();
1761
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1762
-            // NOTE: we're just sending the first default row
1763
-            // (decaf can't manage default tickets so this should be sufficient);
1764
-        }
1765
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1766
-            'event_editor_event_datetimes_help_tab'
1767
-        );
1768
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1769
-        $template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1770
-        $template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1771
-        $template_args['ticket_js_structure']      = $this->_get_ticket_row(
1772
-            $ticket_model->create_default_object(),
1773
-            true
1774
-        );
1775
-        $template                                  = apply_filters(
1776
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1777
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1778
-        );
1779
-        EEH_Template::display_template($template, $template_args);
1780
-    }
1781
-
1782
-
1783
-    /**
1784
-     * Setup an individual ticket form for the decaf event editor page
1785
-     *
1786
-     * @access private
1787
-     * @param EE_Ticket $ticket   the ticket object
1788
-     * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1789
-     * @param int       $row
1790
-     * @return string generated html for the ticket row.
1791
-     * @throws EE_Error
1792
-     * @throws ReflectionException
1793
-     */
1794
-    private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1795
-    {
1796
-        $template_args = [
1797
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1798
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1799
-                : '',
1800
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1801
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1802
-            'TKT_name'            => $ticket->get('TKT_name'),
1803
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1804
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1805
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1806
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1807
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1808
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1809
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1810
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1811
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'dashicons dashicons-lock',
1812
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1813
-                : ' disabled=disabled',
1814
-        ];
1815
-        $price         = $ticket->ID() !== 0
1816
-            ? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1817
-            : null;
1818
-        $price         = $price instanceof EE_Price
1819
-            ? $price
1820
-            : EEM_Price::instance()->create_default_object();
1821
-        $price_args    = [
1822
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1823
-            'PRC_amount'            => $price->get('PRC_amount'),
1824
-            'PRT_ID'                => $price->get('PRT_ID'),
1825
-            'PRC_ID'                => $price->get('PRC_ID'),
1826
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1827
-        ];
1828
-        // make sure we have default start and end dates if skeleton
1829
-        // handle rows that should NOT be empty
1830
-        if (empty($template_args['TKT_start_date'])) {
1831
-            // if empty then the start date will be now.
1832
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1833
-        }
1834
-        if (empty($template_args['TKT_end_date'])) {
1835
-            // get the earliest datetime (if present);
1836
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1837
-                ? $this->_cpt_model_obj->get_first_related(
1838
-                    'Datetime',
1839
-                    ['order_by' => ['DTT_EVT_start' => 'ASC']]
1840
-                )
1841
-                : null;
1842
-            $template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1843
-                ? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1844
-                : date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1845
-        }
1846
-        $template_args = array_merge($template_args, $price_args);
1847
-        $template      = apply_filters(
1848
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1849
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1850
-            $ticket
1851
-        );
1852
-        return EEH_Template::display_template($template, $template_args, true);
1853
-    }
1854
-
1855
-
1856
-    /**
1857
-     * @throws EE_Error
1858
-     * @throws ReflectionException
1859
-     */
1860
-    public function registration_options_meta_box()
1861
-    {
1862
-        $yes_no_values             = [
1863
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1864
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1865
-        ];
1866
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1867
-            [
1868
-                EEM_Registration::status_id_cancelled,
1869
-                EEM_Registration::status_id_declined,
1870
-                EEM_Registration::status_id_incomplete,
1871
-            ],
1872
-            true
1873
-        );
1874
-        // $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1875
-        $template_args['_event']                          = $this->_cpt_model_obj;
1876
-        $template_args['event']                           = $this->_cpt_model_obj;
1877
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1878
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1879
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1880
-            'default_reg_status',
1881
-            $default_reg_status_values,
1882
-            $this->_cpt_model_obj->default_registration_status()
1883
-        );
1884
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1885
-            'display_desc',
1886
-            $yes_no_values,
1887
-            $this->_cpt_model_obj->display_description()
1888
-        );
1889
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1890
-            'display_ticket_selector',
1891
-            $yes_no_values,
1892
-            $this->_cpt_model_obj->display_ticket_selector(),
1893
-            '',
1894
-            '',
1895
-            false
1896
-        );
1897
-        $template_args['additional_registration_options'] = apply_filters(
1898
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1899
-            '',
1900
-            $template_args,
1901
-            $yes_no_values,
1902
-            $default_reg_status_values
1903
-        );
1904
-        EEH_Template::display_template(
1905
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1906
-            $template_args
1907
-        );
1908
-    }
1909
-
1910
-
1911
-    /**
1912
-     * _get_events()
1913
-     * This method simply returns all the events (for the given _view and paging)
1914
-     *
1915
-     * @access public
1916
-     * @param int  $per_page     count of items per page (20 default);
1917
-     * @param int  $current_page what is the current page being viewed.
1918
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1919
-     *                           If FALSE then we return an array of event objects
1920
-     *                           that match the given _view and paging parameters.
1921
-     * @return array|int         an array of event objects or a count of them.
1922
-     * @throws Exception
1923
-     */
1924
-    public function get_events($per_page = 10, $current_page = 1, $count = false)
1925
-    {
1926
-        $EEM_Event   = $this->_event_model();
1927
-        $offset      = ($current_page - 1) * $per_page;
1928
-        $limit       = $count ? null : $offset . ',' . $per_page;
1929
-        $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1930
-        $order       = $this->request->getRequestParam('order', 'DESC');
1931
-        $month_range = $this->request->getRequestParam('month_range');
1932
-        if ($month_range) {
1933
-            $pieces = explode(' ', $month_range, 3);
1934
-            // simulate the FIRST day of the month, that fixes issues for months like February
1935
-            // where PHP doesn't know what to assume for date.
1936
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1937
-            $month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1938
-            $year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1939
-        }
1940
-        $where  = [];
1941
-        $status = $this->request->getRequestParam('status');
1942
-        // determine what post_status our condition will have for the query.
1943
-        switch ($status) {
1944
-            case 'month':
1945
-            case 'today':
1946
-            case null:
1947
-            case 'all':
1948
-                break;
1949
-            case 'draft':
1950
-                $where['status'] = ['IN', ['draft', 'auto-draft']];
1951
-                break;
1952
-            default:
1953
-                $where['status'] = $status;
1954
-        }
1955
-        // categories? The default for all categories is -1
1956
-        $category = $this->request->getRequestParam('EVT_CAT', -1, 'int');
1957
-        if ($category !== -1) {
1958
-            $where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1959
-            $where['Term_Taxonomy.term_id']  = $category;
1960
-        }
1961
-        // date where conditions
1962
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1963
-        if ($month_range) {
1964
-            $DateTime = new DateTime(
1965
-                $year_r . '-' . $month_r . '-01 00:00:00',
1966
-                new DateTimeZone('UTC')
1967
-            );
1968
-            $start    = $DateTime->getTimestamp();
1969
-            // set the datetime to be the end of the month
1970
-            $DateTime->setDate(
1971
-                $year_r,
1972
-                $month_r,
1973
-                $DateTime->format('t')
1974
-            )->setTime(23, 59, 59);
1975
-            $end                             = $DateTime->getTimestamp();
1976
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1977
-        } elseif ($status === 'today') {
1978
-            $DateTime                        =
1979
-                new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1980
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1981
-            $end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1982
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1983
-        } elseif ($status === 'month') {
1984
-            $now                             = date('Y-m-01');
1985
-            $DateTime                        =
1986
-                new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1987
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1988
-            $end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1989
-                                                        ->setTime(23, 59, 59)
1990
-                                                        ->format(implode(' ', $start_formats));
1991
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1992
-        }
1993
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1994
-            $where['EVT_wp_user'] = get_current_user_id();
1995
-        } else {
1996
-            if (! isset($where['status'])) {
1997
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1998
-                    $where['OR'] = [
1999
-                        'status*restrict_private' => ['!=', 'private'],
2000
-                        'AND'                     => [
2001
-                            'status*inclusive' => ['=', 'private'],
2002
-                            'EVT_wp_user'      => get_current_user_id(),
2003
-                        ],
2004
-                    ];
2005
-                }
2006
-            }
2007
-        }
2008
-        $wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
2009
-        if (
2010
-            $wp_user
2011
-            && $wp_user !== get_current_user_id()
2012
-            && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
2013
-        ) {
2014
-            $where['EVT_wp_user'] = $wp_user;
2015
-        }
2016
-        // search query handling
2017
-        $search_term = $this->request->getRequestParam('s');
2018
-        if ($search_term) {
2019
-            $search_term = '%' . $search_term . '%';
2020
-            $where['OR'] = [
2021
-                'EVT_name'       => ['LIKE', $search_term],
2022
-                'EVT_desc'       => ['LIKE', $search_term],
2023
-                'EVT_short_desc' => ['LIKE', $search_term],
2024
-            ];
2025
-        }
2026
-        // filter events by venue.
2027
-        $venue = $this->request->getRequestParam('venue', 0, 'int');
2028
-        if ($venue) {
2029
-            $where['Venue.VNU_ID'] = $venue;
2030
-        }
2031
-        $request_params = $this->request->requestParams();
2032
-        $where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
2033
-        $query_params   = apply_filters(
2034
-            'FHEE__Events_Admin_Page__get_events__query_params',
2035
-            [
2036
-                $where,
2037
-                'limit'    => $limit,
2038
-                'order_by' => $orderby,
2039
-                'order'    => $order,
2040
-                'group_by' => 'EVT_ID',
2041
-            ],
2042
-            $request_params
2043
-        );
2044
-
2045
-        // let's first check if we have special requests coming in.
2046
-        $active_status = $this->request->getRequestParam('active_status');
2047
-        if ($active_status) {
2048
-            switch ($active_status) {
2049
-                case 'upcoming':
2050
-                    return $EEM_Event->get_upcoming_events($query_params, $count);
2051
-                case 'expired':
2052
-                    return $EEM_Event->get_expired_events($query_params, $count);
2053
-                case 'active':
2054
-                    return $EEM_Event->get_active_events($query_params, $count);
2055
-                case 'inactive':
2056
-                    return $EEM_Event->get_inactive_events($query_params, $count);
2057
-            }
2058
-        }
2059
-
2060
-        return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
2061
-    }
2062
-
2063
-
2064
-    /**
2065
-     * handling for WordPress CPT actions (trash, restore, delete)
2066
-     *
2067
-     * @param string $post_id
2068
-     * @throws EE_Error
2069
-     * @throws ReflectionException
2070
-     */
2071
-    public function trash_cpt_item($post_id)
2072
-    {
2073
-        $this->request->setRequestParam('EVT_ID', $post_id);
2074
-        $this->_trash_or_restore_event('trash', false);
2075
-    }
2076
-
2077
-
2078
-    /**
2079
-     * @param string $post_id
2080
-     * @throws EE_Error
2081
-     * @throws ReflectionException
2082
-     */
2083
-    public function restore_cpt_item($post_id)
2084
-    {
2085
-        $this->request->setRequestParam('EVT_ID', $post_id);
2086
-        $this->_trash_or_restore_event('draft', false);
2087
-    }
2088
-
2089
-
2090
-    /**
2091
-     * @param string $post_id
2092
-     * @throws EE_Error
2093
-     * @throws EE_Error
2094
-     */
2095
-    public function delete_cpt_item($post_id)
2096
-    {
2097
-        throw new EE_Error(
2098
-            esc_html__(
2099
-                'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2100
-                'event_espresso'
2101
-            )
2102
-        );
2103
-        // $this->request->setRequestParam('EVT_ID', $post_id);
2104
-        // $this->_delete_event();
2105
-    }
2106
-
2107
-
2108
-    /**
2109
-     * _trash_or_restore_event
2110
-     *
2111
-     * @access protected
2112
-     * @param string $event_status
2113
-     * @param bool   $redirect_after
2114
-     * @throws EE_Error
2115
-     * @throws EE_Error
2116
-     * @throws ReflectionException
2117
-     */
2118
-    protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2119
-    {
2120
-        // determine the event id and set to array.
2121
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2122
-        // loop thru events
2123
-        if ($EVT_ID) {
2124
-            // clean status
2125
-            $event_status = sanitize_key($event_status);
2126
-            // grab status
2127
-            if (! empty($event_status)) {
2128
-                $success = $this->_change_event_status($EVT_ID, $event_status);
2129
-            } else {
2130
-                $success = false;
2131
-                $msg     = esc_html__(
2132
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2133
-                    'event_espresso'
2134
-                );
2135
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2136
-            }
2137
-        } else {
2138
-            $success = false;
2139
-            $msg     = esc_html__(
2140
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2141
-                'event_espresso'
2142
-            );
2143
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2144
-        }
2145
-        $action = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2146
-        if ($redirect_after) {
2147
-            $this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2148
-        }
2149
-    }
2150
-
2151
-
2152
-    /**
2153
-     * _trash_or_restore_events
2154
-     *
2155
-     * @access protected
2156
-     * @param string $event_status
2157
-     * @return void
2158
-     * @throws EE_Error
2159
-     * @throws EE_Error
2160
-     * @throws ReflectionException
2161
-     */
2162
-    protected function _trash_or_restore_events($event_status = 'trash')
2163
-    {
2164
-        // clean status
2165
-        $event_status = sanitize_key($event_status);
2166
-        // grab status
2167
-        if (! empty($event_status)) {
2168
-            $success = true;
2169
-            // determine the event id and set to array.
2170
-            $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2171
-            // loop thru events
2172
-            foreach ($EVT_IDs as $EVT_ID) {
2173
-                if ($EVT_ID = absint($EVT_ID)) {
2174
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
2175
-                    $success = $results !== false ? $success : false;
2176
-                } else {
2177
-                    $msg = sprintf(
2178
-                        esc_html__(
2179
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2180
-                            'event_espresso'
2181
-                        ),
2182
-                        $EVT_ID
2183
-                    );
2184
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2185
-                    $success = false;
2186
-                }
2187
-            }
2188
-        } else {
2189
-            $success = false;
2190
-            $msg     = esc_html__(
2191
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2192
-                'event_espresso'
2193
-            );
2194
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2195
-        }
2196
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2197
-        $success = $success ? 2 : false;
2198
-        $action  = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2199
-        $this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2200
-    }
2201
-
2202
-
2203
-    /**
2204
-     * @param int    $EVT_ID
2205
-     * @param string $event_status
2206
-     * @return bool
2207
-     * @throws EE_Error
2208
-     * @throws ReflectionException
2209
-     */
2210
-    private function _change_event_status($EVT_ID = 0, $event_status = '')
2211
-    {
2212
-        // grab event id
2213
-        if (! $EVT_ID) {
2214
-            $msg = esc_html__(
2215
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2216
-                'event_espresso'
2217
-            );
2218
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2219
-            return false;
2220
-        }
2221
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2222
-        // clean status
2223
-        $event_status = sanitize_key($event_status);
2224
-        // grab status
2225
-        if (empty($event_status)) {
2226
-            $msg = esc_html__(
2227
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2228
-                'event_espresso'
2229
-            );
2230
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2231
-            return false;
2232
-        }
2233
-        // was event trashed or restored ?
2234
-        switch ($event_status) {
2235
-            case 'draft':
2236
-                $action = 'restored from the trash';
2237
-                $hook   = 'AHEE_event_restored_from_trash';
2238
-                break;
2239
-            case 'trash':
2240
-                $action = 'moved to the trash';
2241
-                $hook   = 'AHEE_event_moved_to_trash';
2242
-                break;
2243
-            default:
2244
-                $action = 'updated';
2245
-                $hook   = false;
2246
-        }
2247
-        // use class to change status
2248
-        $this->_cpt_model_obj->set_status($event_status);
2249
-        $success = $this->_cpt_model_obj->save();
2250
-        if (! $success) {
2251
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2252
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2253
-            return false;
2254
-        }
2255
-        if ($hook) {
2256
-            do_action($hook);
2257
-        }
2258
-        return true;
2259
-    }
2260
-
2261
-
2262
-    /**
2263
-     * @param array $event_ids
2264
-     * @return array
2265
-     * @since   4.10.23.p
2266
-     */
2267
-    private function cleanEventIds(array $event_ids)
2268
-    {
2269
-        return array_map('absint', $event_ids);
2270
-    }
2271
-
2272
-
2273
-    /**
2274
-     * @return array
2275
-     * @since   4.10.23.p
2276
-     */
2277
-    private function getEventIdsFromRequest()
2278
-    {
2279
-        if ($this->request->requestParamIsSet('EVT_IDs')) {
2280
-            return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2281
-        } else {
2282
-            return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2283
-        }
2284
-    }
2285
-
2286
-
2287
-    /**
2288
-     * @param bool $preview_delete
2289
-     * @throws EE_Error
2290
-     */
2291
-    protected function _delete_event($preview_delete = true)
2292
-    {
2293
-        $this->_delete_events($preview_delete);
2294
-    }
2295
-
2296
-
2297
-    /**
2298
-     * Gets the tree traversal batch persister.
2299
-     *
2300
-     * @return NodeGroupDao
2301
-     * @throws InvalidArgumentException
2302
-     * @throws InvalidDataTypeException
2303
-     * @throws InvalidInterfaceException
2304
-     * @since 4.10.12.p
2305
-     */
2306
-    protected function getModelObjNodeGroupPersister()
2307
-    {
2308
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2309
-            $this->model_obj_node_group_persister =
2310
-                $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2311
-        }
2312
-        return $this->model_obj_node_group_persister;
2313
-    }
2314
-
2315
-
2316
-    /**
2317
-     * @param bool $preview_delete
2318
-     * @return void
2319
-     * @throws EE_Error
2320
-     */
2321
-    protected function _delete_events($preview_delete = true)
2322
-    {
2323
-        $event_ids = $this->getEventIdsFromRequest();
2324
-        if ($preview_delete) {
2325
-            $this->generateDeletionPreview($event_ids);
2326
-        } else {
2327
-            EEM_Event::instance()->delete_permanently([['EVT_ID' => ['IN', $event_ids]]]);
2328
-        }
2329
-    }
2330
-
2331
-
2332
-    /**
2333
-     * @param array $event_ids
2334
-     */
2335
-    protected function generateDeletionPreview(array $event_ids)
2336
-    {
2337
-        $event_ids = $this->cleanEventIds($event_ids);
2338
-        // Set a code we can use to reference this deletion task in the batch jobs and preview page.
2339
-        $deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2340
-        $return_url        = EE_Admin_Page::add_query_args_and_nonce(
2341
-            [
2342
-                'action'            => 'preview_deletion',
2343
-                'deletion_job_code' => $deletion_job_code,
2344
-            ],
2345
-            $this->_admin_base_url
2346
-        );
2347
-        EEH_URL::safeRedirectAndExit(
2348
-            EE_Admin_Page::add_query_args_and_nonce(
2349
-                [
2350
-                    'page'              => EED_Batch::PAGE_SLUG,
2351
-                    'batch'             => EED_Batch::batch_job,
2352
-                    'EVT_IDs'           => $event_ids,
2353
-                    'deletion_job_code' => $deletion_job_code,
2354
-                    'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2355
-                    'return_url'        => urlencode($return_url),
2356
-                ],
2357
-                admin_url()
2358
-            )
2359
-        );
2360
-    }
2361
-
2362
-
2363
-    /**
2364
-     * Checks for a POST submission
2365
-     *
2366
-     * @since 4.10.12.p
2367
-     */
2368
-    protected function confirmDeletion()
2369
-    {
2370
-        $deletion_redirect_logic =
2371
-            $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2372
-        $deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2373
-    }
2374
-
2375
-
2376
-    /**
2377
-     * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2378
-     *
2379
-     * @throws EE_Error
2380
-     * @since 4.10.12.p
2381
-     */
2382
-    protected function previewDeletion()
2383
-    {
2384
-        $preview_deletion_logic =
2385
-            $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2386
-        $this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2387
-        $this->display_admin_page_with_no_sidebar();
2388
-    }
2389
-
2390
-
2391
-    /**
2392
-     * get total number of events
2393
-     *
2394
-     * @access public
2395
-     * @return int
2396
-     * @throws EE_Error
2397
-     * @throws EE_Error
2398
-     */
2399
-    public function total_events()
2400
-    {
2401
-        return EEM_Event::instance()->count(
2402
-            ['caps' => 'read_admin'],
2403
-            'EVT_ID',
2404
-            true
2405
-        );
2406
-    }
2407
-
2408
-
2409
-    /**
2410
-     * get total number of draft events
2411
-     *
2412
-     * @access public
2413
-     * @return int
2414
-     * @throws EE_Error
2415
-     * @throws EE_Error
2416
-     */
2417
-    public function total_events_draft()
2418
-    {
2419
-        return EEM_Event::instance()->count(
2420
-            [
2421
-                ['status' => ['IN', ['draft', 'auto-draft']]],
2422
-                'caps' => 'read_admin',
2423
-            ],
2424
-            'EVT_ID',
2425
-            true
2426
-        );
2427
-    }
2428
-
2429
-
2430
-    /**
2431
-     * get total number of trashed events
2432
-     *
2433
-     * @access public
2434
-     * @return int
2435
-     * @throws EE_Error
2436
-     * @throws EE_Error
2437
-     */
2438
-    public function total_trashed_events()
2439
-    {
2440
-        return EEM_Event::instance()->count(
2441
-            [
2442
-                ['status' => 'trash'],
2443
-                'caps' => 'read_admin',
2444
-            ],
2445
-            'EVT_ID',
2446
-            true
2447
-        );
2448
-    }
2449
-
2450
-
2451
-    /**
2452
-     *    _default_event_settings
2453
-     *    This generates the Default Settings Tab
2454
-     *
2455
-     * @return void
2456
-     * @throws DomainException
2457
-     * @throws EE_Error
2458
-     * @throws InvalidArgumentException
2459
-     * @throws InvalidDataTypeException
2460
-     * @throws InvalidInterfaceException
2461
-     */
2462
-    protected function _default_event_settings()
2463
-    {
2464
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2465
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
2466
-        $this->_template_args['admin_page_content'] = EEH_HTML::div(
2467
-            $this->_default_event_settings_form()->get_html(),
2468
-            '',
2469
-            'padding'
2470
-        );
2471
-        $this->display_admin_page_with_sidebar();
2472
-    }
2473
-
2474
-
2475
-    /**
2476
-     * Return the form for event settings.
2477
-     *
2478
-     * @return EE_Form_Section_Proper
2479
-     * @throws EE_Error
2480
-     */
2481
-    protected function _default_event_settings_form()
2482
-    {
2483
-        $registration_config              = EE_Registry::instance()->CFG->registration;
2484
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2485
-        // exclude
2486
-            [
2487
-                EEM_Registration::status_id_cancelled,
2488
-                EEM_Registration::status_id_declined,
2489
-                EEM_Registration::status_id_incomplete,
2490
-                EEM_Registration::status_id_wait_list,
2491
-            ],
2492
-            true
2493
-        );
2494
-        // setup Advanced Editor ???
2495
-        if (
2496
-            $this->raw_req_action === 'default_event_settings'
2497
-            || $this->raw_req_action === 'update_default_event_settings'
2498
-        ) {
2499
-            $this->advanced_editor_admin_form = $this->loader->getShared(AdvancedEditorAdminFormSection::class);
2500
-        }
2501
-        return new EE_Form_Section_Proper(
2502
-            [
2503
-                'name'            => 'update_default_event_settings',
2504
-                'html_id'         => 'update_default_event_settings',
2505
-                'html_class'      => 'form-table',
2506
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2507
-                'subsections'     => apply_filters(
2508
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2509
-                    [
2510
-                        'defaults_section_header' => new EE_Form_Section_HTML(
2511
-                            EEH_HTML::h2(
2512
-                                esc_html__('Default Settings', 'event_espresso'),
2513
-                                '',
2514
-                                'ee-admin-settings-hdr'
2515
-                            )
2516
-                        ),
2517
-                        'default_reg_status'  => new EE_Select_Input(
2518
-                            $registration_stati_for_selection,
2519
-                            [
2520
-                                'default'         => isset($registration_config->default_STS_ID)
2521
-                                                     && array_key_exists(
2522
-                                                         $registration_config->default_STS_ID,
2523
-                                                         $registration_stati_for_selection
2524
-                                                     )
2525
-                                    ? sanitize_text_field($registration_config->default_STS_ID)
2526
-                                    : EEM_Registration::status_id_pending_payment,
2527
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2528
-                                                     . EEH_Template::get_help_tab_link(
2529
-                                                         'default_settings_status_help_tab'
2530
-                                                     ),
2531
-                                'html_help_text'  => esc_html__(
2532
-                                    '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.',
2533
-                                    'event_espresso'
2534
-                                ),
2535
-                            ]
2536
-                        ),
2537
-                        'default_max_tickets' => new EE_Integer_Input(
2538
-                            [
2539
-                                'default'         => isset($registration_config->default_maximum_number_of_tickets)
2540
-                                    ? $registration_config->default_maximum_number_of_tickets
2541
-                                    : EEM_Event::get_default_additional_limit(),
2542
-                                'html_label_text' => esc_html__(
2543
-                                    'Default Maximum Tickets Allowed Per Order:',
2544
-                                    'event_espresso'
2545
-                                )
2546
-                                                     . EEH_Template::get_help_tab_link(
2547
-                                                         'default_maximum_tickets_help_tab"'
2548
-                                                     ),
2549
-                                'html_help_text'  => esc_html__(
2550
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2551
-                                    'event_espresso'
2552
-                                ),
2553
-                            ]
2554
-                        ),
2555
-                    ]
2556
-                ),
2557
-            ]
2558
-        );
2559
-    }
2560
-
2561
-
2562
-    /**
2563
-     * @return void
2564
-     * @throws EE_Error
2565
-     * @throws InvalidArgumentException
2566
-     * @throws InvalidDataTypeException
2567
-     * @throws InvalidInterfaceException
2568
-     */
2569
-    protected function _update_default_event_settings()
2570
-    {
2571
-        $form = $this->_default_event_settings_form();
2572
-        if ($form->was_submitted()) {
2573
-            $form->receive_form_submission();
2574
-            if ($form->is_valid()) {
2575
-                $registration_config = EE_Registry::instance()->CFG->registration;
2576
-                $valid_data          = $form->valid_data();
2577
-                if (isset($valid_data['default_reg_status'])) {
2578
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2579
-                }
2580
-                if (isset($valid_data['default_max_tickets'])) {
2581
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2582
-                }
2583
-                do_action(
2584
-                    'AHEE__Events_Admin_Page___update_default_event_settings',
2585
-                    $valid_data,
2586
-                    EE_Registry::instance()->CFG,
2587
-                    $this
2588
-                );
2589
-                // update because data was valid!
2590
-                EE_Registry::instance()->CFG->update_espresso_config();
2591
-                EE_Error::overwrite_success();
2592
-                EE_Error::add_success(
2593
-                    esc_html__('Default Event Settings were updated', 'event_espresso')
2594
-                );
2595
-            }
2596
-        }
2597
-        $this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2598
-    }
2599
-
2600
-
2601
-    /*************        Templates        *************
2602
-     *
2603
-     * @throws EE_Error
2604
-     */
2605
-    protected function _template_settings()
2606
-    {
2607
-        $this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2608
-        $this->_template_args['preview_img']  = '<img src="'
2609
-                                                . EVENTS_ASSETS_URL
2610
-                                                . '/images/'
2611
-                                                . 'caffeinated_template_features.jpg" alt="'
2612
-                                                . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2613
-                                                . '" />';
2614
-        $this->_template_args['preview_text'] = '<strong>'
2615
-                                                . esc_html__(
2616
-                                                    '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.',
2617
-                                                    'event_espresso'
2618
-                                                ) . '</strong>';
2619
-        $this->display_admin_caf_preview_page('template_settings_tab');
2620
-    }
2621
-
2622
-
2623
-    /** Event Category Stuff **/
2624
-    /**
2625
-     * set the _category property with the category object for the loaded page.
2626
-     *
2627
-     * @access private
2628
-     * @return void
2629
-     */
2630
-    private function _set_category_object()
2631
-    {
2632
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2633
-            return;
2634
-        } //already have the category object so get out.
2635
-        // set default category object
2636
-        $this->_set_empty_category_object();
2637
-        // only set if we've got an id
2638
-        $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2639
-        if (! $category_ID) {
2640
-            return;
2641
-        }
2642
-        $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2643
-        if (! empty($term)) {
2644
-            $this->_category->category_name       = $term->name;
2645
-            $this->_category->category_identifier = $term->slug;
2646
-            $this->_category->category_desc       = $term->description;
2647
-            $this->_category->id                  = $term->term_id;
2648
-            $this->_category->parent              = $term->parent;
2649
-        }
2650
-    }
2651
-
2652
-
2653
-    /**
2654
-     * Clears out category properties.
2655
-     */
2656
-    private function _set_empty_category_object()
2657
-    {
2658
-        $this->_category                = new stdClass();
2659
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2660
-        $this->_category->id            = $this->_category->parent = 0;
2661
-    }
2662
-
2663
-
2664
-    /**
2665
-     * @throws DomainException
2666
-     * @throws EE_Error
2667
-     * @throws InvalidArgumentException
2668
-     * @throws InvalidDataTypeException
2669
-     * @throws InvalidInterfaceException
2670
-     */
2671
-    protected function _category_list_table()
2672
-    {
2673
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2674
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2675
-        $this->_admin_page_title .= ' ';
2676
-        $this->_admin_page_title .= $this->get_action_link_or_button(
2677
-            'add_category',
2678
-            'add_category',
2679
-            [],
2680
-            'add-new-h2'
2681
-        );
2682
-        $this->display_admin_list_table_page_with_sidebar();
2683
-    }
2684
-
2685
-
2686
-    /**
2687
-     * Output category details view.
2688
-     *
2689
-     * @throws EE_Error
2690
-     * @throws EE_Error
2691
-     */
2692
-    protected function _category_details($view)
2693
-    {
2694
-        // load formatter helper
2695
-        // load field generator helper
2696
-        $route = $view === 'edit' ? 'update_category' : 'insert_category';
2697
-        $this->_set_add_edit_form_tags($route);
2698
-        $this->_set_category_object();
2699
-        $id            = ! empty($this->_category->id) ? $this->_category->id : '';
2700
-        $delete_action = 'delete_category';
2701
-        // custom redirect
2702
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2703
-            ['action' => 'category_list'],
2704
-            $this->_admin_base_url
2705
-        );
2706
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2707
-        // take care of contents
2708
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2709
-        $this->display_admin_page_with_sidebar();
2710
-    }
2711
-
2712
-
2713
-    /**
2714
-     * Output category details content.
2715
-     *
2716
-     * @throws DomainException
2717
-     */
2718
-    protected function _category_details_content()
2719
-    {
2720
-        $editor_args['category_desc'] = [
2721
-            'type'          => 'wp_editor',
2722
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2723
-            'class'         => 'my_editor_custom',
2724
-            'wpeditor_args' => ['media_buttons' => false],
2725
-        ];
2726
-        $_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2727
-        $all_terms                    = get_terms(
2728
-            [EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2729
-            ['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2730
-        );
2731
-        // setup category select for term parents.
2732
-        $category_select_values[] = [
2733
-            'text' => esc_html__('No Parent', 'event_espresso'),
2734
-            'id'   => 0,
2735
-        ];
2736
-        foreach ($all_terms as $term) {
2737
-            $category_select_values[] = [
2738
-                'text' => $term->name,
2739
-                'id'   => $term->term_id,
2740
-            ];
2741
-        }
2742
-        $category_select = EEH_Form_Fields::select_input(
2743
-            'category_parent',
2744
-            $category_select_values,
2745
-            $this->_category->parent
2746
-        );
2747
-        $template_args   = [
2748
-            'category'                 => $this->_category,
2749
-            'category_select'          => $category_select,
2750
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2751
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2752
-            'disable'                  => '',
2753
-            'disabled_message'         => false,
2754
-        ];
2755
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2756
-        return EEH_Template::display_template($template, $template_args, true);
2757
-    }
2758
-
2759
-
2760
-    /**
2761
-     * Handles deleting categories.
2762
-     *
2763
-     * @throws EE_Error
2764
-     */
2765
-    protected function _delete_categories()
2766
-    {
2767
-        $category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2768
-        foreach ($category_IDs as $category_ID) {
2769
-            $this->_delete_category($category_ID);
2770
-        }
2771
-        // doesn't matter what page we're coming from... we're going to the same place after delete.
2772
-        $query_args = [
2773
-            'action' => 'category_list',
2774
-        ];
2775
-        $this->_redirect_after_action(0, '', '', $query_args);
2776
-    }
2777
-
2778
-
2779
-    /**
2780
-     * Handles deleting specific category.
2781
-     *
2782
-     * @param int $cat_id
2783
-     */
2784
-    protected function _delete_category($cat_id)
2785
-    {
2786
-        $cat_id = absint($cat_id);
2787
-        wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2788
-    }
2789
-
2790
-
2791
-    /**
2792
-     * Handles triggering the update or insertion of a new category.
2793
-     *
2794
-     * @param bool $new_category true means we're triggering the insert of a new category.
2795
-     * @throws EE_Error
2796
-     * @throws EE_Error
2797
-     */
2798
-    protected function _insert_or_update_category($new_category)
2799
-    {
2800
-        $cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2801
-        $success = 0; // we already have a success message so lets not send another.
2802
-        if ($cat_id) {
2803
-            $query_args = [
2804
-                'action'     => 'edit_category',
2805
-                'EVT_CAT_ID' => $cat_id,
2806
-            ];
2807
-        } else {
2808
-            $query_args = ['action' => 'add_category'];
2809
-        }
2810
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2811
-    }
2812
-
2813
-
2814
-    /**
2815
-     * Inserts or updates category
2816
-     *
2817
-     * @param bool $update (true indicates we're updating a category).
2818
-     * @return bool|mixed|string
2819
-     */
2820
-    private function _insert_category($update = false)
2821
-    {
2822
-        $category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2823
-        $category_name       = $this->request->getRequestParam('category_name', '');
2824
-        $category_desc       = $this->request->getRequestParam('category_desc', '');
2825
-        $category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2826
-        $category_identifier = $this->request->getRequestParam('category_identifier', '');
2827
-
2828
-        if (empty($category_name)) {
2829
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2830
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2831
-            return false;
2832
-        }
2833
-        $term_args = [
2834
-            'name'        => $category_name,
2835
-            'description' => $category_desc,
2836
-            'parent'      => $category_parent,
2837
-        ];
2838
-        // was the category_identifier input disabled?
2839
-        if ($category_identifier) {
2840
-            $term_args['slug'] = $category_identifier;
2841
-        }
2842
-        $insert_ids = $update
2843
-            ? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2844
-            : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2845
-        if (! is_array($insert_ids)) {
2846
-            $msg = esc_html__(
2847
-                'An error occurred and the category has not been saved to the database.',
2848
-                'event_espresso'
2849
-            );
2850
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2851
-        } else {
2852
-            $category_ID = $insert_ids['term_id'];
2853
-            $msg         = sprintf(
2854
-                esc_html__('The category %s was successfully saved', 'event_espresso'),
2855
-                $category_name
2856
-            );
2857
-            EE_Error::add_success($msg);
2858
-        }
2859
-        return $category_ID;
2860
-    }
2861
-
2862
-
2863
-    /**
2864
-     * Gets categories or count of categories matching the arguments in the request.
2865
-     *
2866
-     * @param int  $per_page
2867
-     * @param int  $current_page
2868
-     * @param bool $count
2869
-     * @return EE_Term_Taxonomy[]|int
2870
-     * @throws EE_Error
2871
-     */
2872
-    public function get_categories($per_page = 10, $current_page = 1, $count = false)
2873
-    {
2874
-        // testing term stuff
2875
-        $orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2876
-        $order       = $this->request->getRequestParam('order', 'DESC');
2877
-        $limit       = ($current_page - 1) * $per_page;
2878
-        $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2879
-        $search_term = $this->request->getRequestParam('s');
2880
-        if ($search_term) {
2881
-            $search_term = '%' . $search_term . '%';
2882
-            $where['OR'] = [
2883
-                'Term.name'   => ['LIKE', $search_term],
2884
-                'description' => ['LIKE', $search_term],
2885
-            ];
2886
-        }
2887
-        $query_params = [
2888
-            $where,
2889
-            'order_by'   => [$orderby => $order],
2890
-            'limit'      => $limit . ',' . $per_page,
2891
-            'force_join' => ['Term'],
2892
-        ];
2893
-        return $count
2894
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2895
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2896
-    }
2897
-
2898
-    /* end category stuff */
2899
-
2900
-
2901
-    /**************/
2902
-
2903
-
2904
-    /**
2905
-     * Callback for the `ee_save_timezone_setting` ajax action.
2906
-     *
2907
-     * @throws EE_Error
2908
-     * @throws InvalidArgumentException
2909
-     * @throws InvalidDataTypeException
2910
-     * @throws InvalidInterfaceException
2911
-     */
2912
-    public function saveTimezoneString()
2913
-    {
2914
-        $timezone_string = $this->request->getRequestParam('timezone_selected');
2915
-        if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2916
-            EE_Error::add_error(
2917
-                esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2918
-                __FILE__,
2919
-                __FUNCTION__,
2920
-                __LINE__
2921
-            );
2922
-            $this->_template_args['error'] = true;
2923
-            $this->_return_json();
2924
-        }
2925
-
2926
-        update_option('timezone_string', $timezone_string);
2927
-        EE_Error::add_success(
2928
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2929
-        );
2930
-        $this->_template_args['success'] = true;
2931
-        $this->_return_json(true, ['action' => 'create_new']);
2932
-    }
2933
-
2934
-
2935
-    /**
2936 2603
      * @throws EE_Error
2937
-     * @deprecated 4.10.25.p
2938 2604
      */
2939
-    public function save_timezonestring_setting()
2940
-    {
2941
-        $this->saveTimezoneString();
2942
-    }
2605
+	protected function _template_settings()
2606
+	{
2607
+		$this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2608
+		$this->_template_args['preview_img']  = '<img src="'
2609
+												. EVENTS_ASSETS_URL
2610
+												. '/images/'
2611
+												. 'caffeinated_template_features.jpg" alt="'
2612
+												. esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2613
+												. '" />';
2614
+		$this->_template_args['preview_text'] = '<strong>'
2615
+												. esc_html__(
2616
+													'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.',
2617
+													'event_espresso'
2618
+												) . '</strong>';
2619
+		$this->display_admin_caf_preview_page('template_settings_tab');
2620
+	}
2621
+
2622
+
2623
+	/** Event Category Stuff **/
2624
+	/**
2625
+	 * set the _category property with the category object for the loaded page.
2626
+	 *
2627
+	 * @access private
2628
+	 * @return void
2629
+	 */
2630
+	private function _set_category_object()
2631
+	{
2632
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2633
+			return;
2634
+		} //already have the category object so get out.
2635
+		// set default category object
2636
+		$this->_set_empty_category_object();
2637
+		// only set if we've got an id
2638
+		$category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2639
+		if (! $category_ID) {
2640
+			return;
2641
+		}
2642
+		$term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2643
+		if (! empty($term)) {
2644
+			$this->_category->category_name       = $term->name;
2645
+			$this->_category->category_identifier = $term->slug;
2646
+			$this->_category->category_desc       = $term->description;
2647
+			$this->_category->id                  = $term->term_id;
2648
+			$this->_category->parent              = $term->parent;
2649
+		}
2650
+	}
2651
+
2652
+
2653
+	/**
2654
+	 * Clears out category properties.
2655
+	 */
2656
+	private function _set_empty_category_object()
2657
+	{
2658
+		$this->_category                = new stdClass();
2659
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2660
+		$this->_category->id            = $this->_category->parent = 0;
2661
+	}
2662
+
2663
+
2664
+	/**
2665
+	 * @throws DomainException
2666
+	 * @throws EE_Error
2667
+	 * @throws InvalidArgumentException
2668
+	 * @throws InvalidDataTypeException
2669
+	 * @throws InvalidInterfaceException
2670
+	 */
2671
+	protected function _category_list_table()
2672
+	{
2673
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2674
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2675
+		$this->_admin_page_title .= ' ';
2676
+		$this->_admin_page_title .= $this->get_action_link_or_button(
2677
+			'add_category',
2678
+			'add_category',
2679
+			[],
2680
+			'add-new-h2'
2681
+		);
2682
+		$this->display_admin_list_table_page_with_sidebar();
2683
+	}
2684
+
2685
+
2686
+	/**
2687
+	 * Output category details view.
2688
+	 *
2689
+	 * @throws EE_Error
2690
+	 * @throws EE_Error
2691
+	 */
2692
+	protected function _category_details($view)
2693
+	{
2694
+		// load formatter helper
2695
+		// load field generator helper
2696
+		$route = $view === 'edit' ? 'update_category' : 'insert_category';
2697
+		$this->_set_add_edit_form_tags($route);
2698
+		$this->_set_category_object();
2699
+		$id            = ! empty($this->_category->id) ? $this->_category->id : '';
2700
+		$delete_action = 'delete_category';
2701
+		// custom redirect
2702
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2703
+			['action' => 'category_list'],
2704
+			$this->_admin_base_url
2705
+		);
2706
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2707
+		// take care of contents
2708
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2709
+		$this->display_admin_page_with_sidebar();
2710
+	}
2711
+
2712
+
2713
+	/**
2714
+	 * Output category details content.
2715
+	 *
2716
+	 * @throws DomainException
2717
+	 */
2718
+	protected function _category_details_content()
2719
+	{
2720
+		$editor_args['category_desc'] = [
2721
+			'type'          => 'wp_editor',
2722
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2723
+			'class'         => 'my_editor_custom',
2724
+			'wpeditor_args' => ['media_buttons' => false],
2725
+		];
2726
+		$_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2727
+		$all_terms                    = get_terms(
2728
+			[EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2729
+			['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2730
+		);
2731
+		// setup category select for term parents.
2732
+		$category_select_values[] = [
2733
+			'text' => esc_html__('No Parent', 'event_espresso'),
2734
+			'id'   => 0,
2735
+		];
2736
+		foreach ($all_terms as $term) {
2737
+			$category_select_values[] = [
2738
+				'text' => $term->name,
2739
+				'id'   => $term->term_id,
2740
+			];
2741
+		}
2742
+		$category_select = EEH_Form_Fields::select_input(
2743
+			'category_parent',
2744
+			$category_select_values,
2745
+			$this->_category->parent
2746
+		);
2747
+		$template_args   = [
2748
+			'category'                 => $this->_category,
2749
+			'category_select'          => $category_select,
2750
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2751
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2752
+			'disable'                  => '',
2753
+			'disabled_message'         => false,
2754
+		];
2755
+		$template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2756
+		return EEH_Template::display_template($template, $template_args, true);
2757
+	}
2758
+
2759
+
2760
+	/**
2761
+	 * Handles deleting categories.
2762
+	 *
2763
+	 * @throws EE_Error
2764
+	 */
2765
+	protected function _delete_categories()
2766
+	{
2767
+		$category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2768
+		foreach ($category_IDs as $category_ID) {
2769
+			$this->_delete_category($category_ID);
2770
+		}
2771
+		// doesn't matter what page we're coming from... we're going to the same place after delete.
2772
+		$query_args = [
2773
+			'action' => 'category_list',
2774
+		];
2775
+		$this->_redirect_after_action(0, '', '', $query_args);
2776
+	}
2777
+
2778
+
2779
+	/**
2780
+	 * Handles deleting specific category.
2781
+	 *
2782
+	 * @param int $cat_id
2783
+	 */
2784
+	protected function _delete_category($cat_id)
2785
+	{
2786
+		$cat_id = absint($cat_id);
2787
+		wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2788
+	}
2789
+
2790
+
2791
+	/**
2792
+	 * Handles triggering the update or insertion of a new category.
2793
+	 *
2794
+	 * @param bool $new_category true means we're triggering the insert of a new category.
2795
+	 * @throws EE_Error
2796
+	 * @throws EE_Error
2797
+	 */
2798
+	protected function _insert_or_update_category($new_category)
2799
+	{
2800
+		$cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2801
+		$success = 0; // we already have a success message so lets not send another.
2802
+		if ($cat_id) {
2803
+			$query_args = [
2804
+				'action'     => 'edit_category',
2805
+				'EVT_CAT_ID' => $cat_id,
2806
+			];
2807
+		} else {
2808
+			$query_args = ['action' => 'add_category'];
2809
+		}
2810
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2811
+	}
2812
+
2813
+
2814
+	/**
2815
+	 * Inserts or updates category
2816
+	 *
2817
+	 * @param bool $update (true indicates we're updating a category).
2818
+	 * @return bool|mixed|string
2819
+	 */
2820
+	private function _insert_category($update = false)
2821
+	{
2822
+		$category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2823
+		$category_name       = $this->request->getRequestParam('category_name', '');
2824
+		$category_desc       = $this->request->getRequestParam('category_desc', '');
2825
+		$category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2826
+		$category_identifier = $this->request->getRequestParam('category_identifier', '');
2827
+
2828
+		if (empty($category_name)) {
2829
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2830
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2831
+			return false;
2832
+		}
2833
+		$term_args = [
2834
+			'name'        => $category_name,
2835
+			'description' => $category_desc,
2836
+			'parent'      => $category_parent,
2837
+		];
2838
+		// was the category_identifier input disabled?
2839
+		if ($category_identifier) {
2840
+			$term_args['slug'] = $category_identifier;
2841
+		}
2842
+		$insert_ids = $update
2843
+			? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2844
+			: wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2845
+		if (! is_array($insert_ids)) {
2846
+			$msg = esc_html__(
2847
+				'An error occurred and the category has not been saved to the database.',
2848
+				'event_espresso'
2849
+			);
2850
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2851
+		} else {
2852
+			$category_ID = $insert_ids['term_id'];
2853
+			$msg         = sprintf(
2854
+				esc_html__('The category %s was successfully saved', 'event_espresso'),
2855
+				$category_name
2856
+			);
2857
+			EE_Error::add_success($msg);
2858
+		}
2859
+		return $category_ID;
2860
+	}
2861
+
2862
+
2863
+	/**
2864
+	 * Gets categories or count of categories matching the arguments in the request.
2865
+	 *
2866
+	 * @param int  $per_page
2867
+	 * @param int  $current_page
2868
+	 * @param bool $count
2869
+	 * @return EE_Term_Taxonomy[]|int
2870
+	 * @throws EE_Error
2871
+	 */
2872
+	public function get_categories($per_page = 10, $current_page = 1, $count = false)
2873
+	{
2874
+		// testing term stuff
2875
+		$orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2876
+		$order       = $this->request->getRequestParam('order', 'DESC');
2877
+		$limit       = ($current_page - 1) * $per_page;
2878
+		$where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2879
+		$search_term = $this->request->getRequestParam('s');
2880
+		if ($search_term) {
2881
+			$search_term = '%' . $search_term . '%';
2882
+			$where['OR'] = [
2883
+				'Term.name'   => ['LIKE', $search_term],
2884
+				'description' => ['LIKE', $search_term],
2885
+			];
2886
+		}
2887
+		$query_params = [
2888
+			$where,
2889
+			'order_by'   => [$orderby => $order],
2890
+			'limit'      => $limit . ',' . $per_page,
2891
+			'force_join' => ['Term'],
2892
+		];
2893
+		return $count
2894
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2895
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2896
+	}
2897
+
2898
+	/* end category stuff */
2899
+
2900
+
2901
+	/**************/
2902
+
2903
+
2904
+	/**
2905
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2906
+	 *
2907
+	 * @throws EE_Error
2908
+	 * @throws InvalidArgumentException
2909
+	 * @throws InvalidDataTypeException
2910
+	 * @throws InvalidInterfaceException
2911
+	 */
2912
+	public function saveTimezoneString()
2913
+	{
2914
+		$timezone_string = $this->request->getRequestParam('timezone_selected');
2915
+		if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2916
+			EE_Error::add_error(
2917
+				esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2918
+				__FILE__,
2919
+				__FUNCTION__,
2920
+				__LINE__
2921
+			);
2922
+			$this->_template_args['error'] = true;
2923
+			$this->_return_json();
2924
+		}
2925
+
2926
+		update_option('timezone_string', $timezone_string);
2927
+		EE_Error::add_success(
2928
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2929
+		);
2930
+		$this->_template_args['success'] = true;
2931
+		$this->_return_json(true, ['action' => 'create_new']);
2932
+	}
2933
+
2934
+
2935
+	/**
2936
+	 * @throws EE_Error
2937
+	 * @deprecated 4.10.25.p
2938
+	 */
2939
+	public function save_timezonestring_setting()
2940
+	{
2941
+		$this->saveTimezoneString();
2942
+	}
2943 2943
 }
Please login to merge, or discard this patch.
Spacing   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -580,13 +580,13 @@  discard block
 block discarded – undo
580 580
     {
581 581
         wp_register_style(
582 582
             'events-admin-css',
583
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
583
+            EVENTS_ASSETS_URL.'events-admin-page.css',
584 584
             [],
585 585
             EVENT_ESPRESSO_VERSION
586 586
         );
587 587
         wp_register_style(
588 588
             'ee-cat-admin',
589
-            EVENTS_ASSETS_URL . 'ee-cat-admin.css',
589
+            EVENTS_ASSETS_URL.'ee-cat-admin.css',
590 590
             [],
591 591
             EVENT_ESPRESSO_VERSION
592 592
         );
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
         // scripts
596 596
         wp_register_script(
597 597
             'event_editor_js',
598
-            EVENTS_ASSETS_URL . 'event_editor.js',
598
+            EVENTS_ASSETS_URL.'event_editor.js',
599 599
             ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
600 600
             EVENT_ESPRESSO_VERSION,
601 601
             true
@@ -621,16 +621,16 @@  discard block
 block discarded – undo
621 621
         wp_enqueue_style('espresso-ui-theme');
622 622
         wp_register_style(
623 623
             'event-editor-css',
624
-            EVENTS_ASSETS_URL . 'event-editor.css',
624
+            EVENTS_ASSETS_URL.'event-editor.css',
625 625
             ['ee-admin-css'],
626 626
             EVENT_ESPRESSO_VERSION
627 627
         );
628 628
         wp_enqueue_style('event-editor-css');
629 629
         // scripts
630
-        if (! $this->admin_config->useAdvancedEditor()) {
630
+        if ( ! $this->admin_config->useAdvancedEditor()) {
631 631
             wp_register_script(
632 632
                 'event-datetime-metabox',
633
-                EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
633
+                EVENTS_ASSETS_URL.'event-datetime-metabox.js',
634 634
                 ['event_editor_js', 'ee-datepicker'],
635 635
                 EVENT_ESPRESSO_VERSION
636 636
             );
@@ -700,15 +700,15 @@  discard block
 block discarded – undo
700 700
     public function verify_event_edit($event = null, $req_type = '')
701 701
     {
702 702
         // don't need to do this when processing
703
-        if (! empty($req_type)) {
703
+        if ( ! empty($req_type)) {
704 704
             return;
705 705
         }
706 706
         // no event?
707
-        if (! $event instanceof EE_Event) {
707
+        if ( ! $event instanceof EE_Event) {
708 708
             $event = $this->_cpt_model_obj;
709 709
         }
710 710
         // STILL no event?
711
-        if (! $event instanceof EE_Event) {
711
+        if ( ! $event instanceof EE_Event) {
712 712
             return;
713 713
         }
714 714
         $orig_status = $event->status();
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
             );
749 749
         }
750 750
         // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
751
-        if (! $event->tickets_on_sale()) {
751
+        if ( ! $event->tickets_on_sale()) {
752 752
             return;
753 753
         }
754 754
         // made it here so show warning
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
     {
797 797
         $has_timezone_string = get_option('timezone_string');
798 798
         // only nag them about setting their timezone if it's their first event, and they haven't already done it
799
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
799
+        if ( ! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
800 800
             EE_Error::add_attention(
801 801
                 sprintf(
802 802
                     esc_html__(
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
      */
866 866
     protected function _event_legend_items()
867 867
     {
868
-        $items    = [
868
+        $items = [
869 869
             'view_details'   => [
870 870
                 'class' => 'dashicons dashicons-visibility',
871 871
                 'desc'  => esc_html__('View Event', 'event_espresso'),
@@ -882,31 +882,31 @@  discard block
 block discarded – undo
882 882
         $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
883 883
         $statuses = [
884 884
             'sold_out_status'  => [
885
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::sold_out,
885
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::sold_out,
886 886
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
887 887
             ],
888 888
             'active_status'    => [
889
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::active,
889
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::active,
890 890
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
891 891
             ],
892 892
             'upcoming_status'  => [
893
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::upcoming,
893
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::upcoming,
894 894
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
895 895
             ],
896 896
             'postponed_status' => [
897
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::postponed,
897
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::postponed,
898 898
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
899 899
             ],
900 900
             'cancelled_status' => [
901
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::cancelled,
901
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::cancelled,
902 902
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
903 903
             ],
904 904
             'expired_status'   => [
905
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::expired,
905
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::expired,
906 906
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
907 907
             ],
908 908
             'inactive_status'  => [
909
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::inactive,
909
+                'class' => 'ee-status-legend ee-status-bg--'.EE_Datetime::inactive,
910 910
                 'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
911 911
             ],
912 912
         ];
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
      */
926 926
     private function _event_model()
927 927
     {
928
-        if (! $this->_event_model instanceof EEM_Event) {
928
+        if ( ! $this->_event_model instanceof EEM_Event) {
929 929
             $this->_event_model = EE_Registry::instance()->load_model('Event');
930 930
         }
931 931
         return $this->_event_model;
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
     public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
946 946
     {
947 947
         // make sure this is only when editing
948
-        if (! empty($id)) {
948
+        if ( ! empty($id)) {
949 949
             $post = get_post($id);
950 950
             $return .= '<a class="button button--small button--secondary" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
951 951
                        . esc_html__('Shortcode', 'event_espresso')
@@ -972,7 +972,7 @@  discard block
 block discarded – undo
972 972
      */
973 973
     protected function _events_overview_list_table()
974 974
     {
975
-        $after_list_table                           = [];
975
+        $after_list_table = [];
976 976
         $links_html = EEH_HTML::div('', '', 'ee-admin-section ee-layout-stack');
977 977
         $links_html .= EEH_HTML::h3(esc_html__('Links', 'event_espresso'));
978 978
         $links_html .= EEH_HTML::div(
@@ -989,14 +989,14 @@  discard block
 block discarded – undo
989 989
         $after_list_table['view_event_list_button'] = $links_html;
990 990
 
991 991
         $after_list_table['legend'] = $this->_display_legend($this->_event_legend_items());
992
-        $this->_admin_page_title                    .= ' ' . $this->get_action_link_or_button(
992
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
993 993
             'create_new',
994 994
             'add',
995 995
             [],
996 996
             'add-new-h2'
997 997
         );
998 998
 
999
-        $this->_template_args['after_list_table']   = array_merge(
999
+        $this->_template_args['after_list_table'] = array_merge(
1000 1000
             (array) $this->_template_args['after_list_table'],
1001 1001
             $after_list_table
1002 1002
         );
@@ -1053,13 +1053,13 @@  discard block
 block discarded – undo
1053 1053
             'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1054 1054
         ];
1055 1055
         // check if the new EDTR reg options meta box is being used, and if so, don't run updates for legacy version
1056
-        if (! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1057
-            $event_values['EVT_display_ticket_selector']     = $this->request->getRequestParam(
1056
+        if ( ! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1057
+            $event_values['EVT_display_ticket_selector'] = $this->request->getRequestParam(
1058 1058
                 'display_ticket_selector',
1059 1059
                 false,
1060 1060
                 'bool'
1061 1061
             );
1062
-            $event_values['EVT_additional_limit']            = min(
1062
+            $event_values['EVT_additional_limit'] = min(
1063 1063
                 apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1064 1064
                 $this->request->getRequestParam(
1065 1065
                     'additional_limit',
@@ -1100,7 +1100,7 @@  discard block
 block discarded – undo
1100 1100
         // the following are default callbacks for event attachment updates
1101 1101
         // that can be overridden by caffeinated functionality and/or addons.
1102 1102
         $event_update_callbacks = [];
1103
-        if (! $this->admin_config->useAdvancedEditor()) {
1103
+        if ( ! $this->admin_config->useAdvancedEditor()) {
1104 1104
             $event_update_callbacks['_default_venue_update']   = [$this, '_default_venue_update'];
1105 1105
             $event_update_callbacks['_default_tickets_update'] = [$this, '_default_tickets_update'];
1106 1106
         }
@@ -1171,7 +1171,7 @@  discard block
 block discarded – undo
1171 1171
      */
1172 1172
     protected function _default_venue_update(EE_Event $event, $data)
1173 1173
     {
1174
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1174
+        require_once(EE_MODELS.'EEM_Venue.model.php');
1175 1175
         $venue_model = EE_Registry::instance()->load_model('Venue');
1176 1176
         $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1177 1177
         // very important.  If we don't have a venue name...
@@ -1202,7 +1202,7 @@  discard block
 block discarded – undo
1202 1202
             'status'              => 'publish',
1203 1203
         ];
1204 1204
         // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1205
-        if (! empty($venue_id)) {
1205
+        if ( ! empty($venue_id)) {
1206 1206
             $update_where  = [$venue_model->primary_key_name() => $venue_id];
1207 1207
             $rows_affected = $venue_model->update($venue_array, [$update_where]);
1208 1208
             // we've gotta make sure that the venue is always attached to a revision..
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
                 isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1245 1245
                     ? $datetime_data['DTT_EVT_end']
1246 1246
                     : $datetime_data['DTT_EVT_start'];
1247
-            $datetime_values              = [
1247
+            $datetime_values = [
1248 1248
                 'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1249 1249
                 'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1250 1250
                 'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
@@ -1253,9 +1253,9 @@  discard block
 block discarded – undo
1253 1253
             ];
1254 1254
             // if we have an id then let's get existing object first and then set the new values.
1255 1255
             //  Otherwise we instantiate a new object for save.
1256
-            if (! empty($datetime_data['DTT_ID'])) {
1256
+            if ( ! empty($datetime_data['DTT_ID'])) {
1257 1257
                 $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1258
-                if (! $datetime instanceof EE_Datetime) {
1258
+                if ( ! $datetime instanceof EE_Datetime) {
1259 1259
                     throw new RuntimeException(
1260 1260
                         sprintf(
1261 1261
                             esc_html__(
@@ -1274,7 +1274,7 @@  discard block
 block discarded – undo
1274 1274
             } else {
1275 1275
                 $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1276 1276
             }
1277
-            if (! $datetime instanceof EE_Datetime) {
1277
+            if ( ! $datetime instanceof EE_Datetime) {
1278 1278
                 throw new RuntimeException(
1279 1279
                     sprintf(
1280 1280
                         esc_html__(
@@ -1300,7 +1300,7 @@  discard block
 block discarded – undo
1300 1300
 
1301 1301
         // set up some default start and end dates in case those are not present in the incoming data
1302 1302
         $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1303
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1303
+        $default_start_date = $default_start_date->format($date_formats[0].' '.$date_formats[1]);
1304 1304
         // use the start date of the first datetime for the end date
1305 1305
         $first_datetime   = $event->first_datetime();
1306 1306
         $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
@@ -1308,8 +1308,8 @@  discard block
 block discarded – undo
1308 1308
         // now process the incoming data
1309 1309
         foreach ($data['edit_tickets'] as $row => $ticket_data) {
1310 1310
             $update_prices = false;
1311
-            $ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1312
-                ? $data['edit_prices'][ $row ][1]['PRC_amount']
1311
+            $ticket_price  = isset($data['edit_prices'][$row][1]['PRC_amount'])
1312
+                ? $data['edit_prices'][$row][1]['PRC_amount']
1313 1313
                 : 0;
1314 1314
             // trim inputs to ensure any excess whitespace is removed.
1315 1315
             $ticket_data   = array_map('trim', $ticket_data);
@@ -1350,9 +1350,9 @@  discard block
 block discarded – undo
1350 1350
             // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1351 1351
             // keep in mind that if the ticket has been sold (and we have changed pricing information),
1352 1352
             // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1353
-            if (! empty($ticket_data['TKT_ID'])) {
1353
+            if ( ! empty($ticket_data['TKT_ID'])) {
1354 1354
                 $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1355
-                if (! $existing_ticket instanceof EE_Ticket) {
1355
+                if ( ! $existing_ticket instanceof EE_Ticket) {
1356 1356
                     throw new RuntimeException(
1357 1357
                         sprintf(
1358 1358
                             esc_html__(
@@ -1401,7 +1401,7 @@  discard block
 block discarded – undo
1401 1401
                     $existing_ticket->save();
1402 1402
                     // make sure this ticket is still recorded in our $saved_tickets
1403 1403
                     // so we don't run it through the regular trash routine.
1404
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1404
+                    $saved_tickets[$existing_ticket->ID()] = $existing_ticket;
1405 1405
                     // create new ticket that's a copy of the existing except,
1406 1406
                     // (a new id of course and not archived) AND has the new TKT_price associated with it.
1407 1407
                     $new_ticket = clone $existing_ticket;
@@ -1418,7 +1418,7 @@  discard block
 block discarded – undo
1418 1418
                 $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1419 1419
                 $update_prices              = true;
1420 1420
             }
1421
-            if (! $ticket instanceof EE_Ticket) {
1421
+            if ( ! $ticket instanceof EE_Ticket) {
1422 1422
                 throw new RuntimeException(
1423 1423
                     sprintf(
1424 1424
                         esc_html__(
@@ -1442,10 +1442,10 @@  discard block
 block discarded – undo
1442 1442
             }
1443 1443
             // initially let's add the ticket to the datetime
1444 1444
             $datetime->_add_relation_to($ticket, 'Ticket');
1445
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1445
+            $saved_tickets[$ticket->ID()] = $ticket;
1446 1446
             // add prices to ticket
1447
-            $prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1448
-                ? $data['edit_prices'][ $row ]
1447
+            $prices_data = isset($data['edit_prices'][$row]) && is_array($data['edit_prices'][$row])
1448
+                ? $data['edit_prices'][$row]
1449 1449
                 : [];
1450 1450
             $this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1451 1451
         }
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
             $id = absint($id);
1460 1460
             // get the ticket for this id
1461 1461
             $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1462
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1462
+            if ( ! $ticket_to_remove instanceof EE_Ticket) {
1463 1463
                 continue;
1464 1464
             }
1465 1465
             // need to get all the related datetimes on this ticket and remove from every single one of them
@@ -1516,7 +1516,7 @@  discard block
 block discarded – undo
1516 1516
                     $price->set($field, $new_price);
1517 1517
                 }
1518 1518
             }
1519
-            if (! $price instanceof EE_Price) {
1519
+            if ( ! $price instanceof EE_Price) {
1520 1520
                 throw new RuntimeException(
1521 1521
                     sprintf(
1522 1522
                         esc_html__(
@@ -1558,13 +1558,13 @@  discard block
 block discarded – undo
1558 1558
     {
1559 1559
         // load formatter helper
1560 1560
         // args for getting related registrations
1561
-        $approved_query_args        = [
1561
+        $approved_query_args = [
1562 1562
             [
1563 1563
                 'REG_deleted' => 0,
1564 1564
                 'STS_ID'      => EEM_Registration::status_id_approved,
1565 1565
             ],
1566 1566
         ];
1567
-        $not_approved_query_args    = [
1567
+        $not_approved_query_args = [
1568 1568
             [
1569 1569
                 'REG_deleted' => 0,
1570 1570
                 'STS_ID'      => EEM_Registration::status_id_not_approved,
@@ -1627,7 +1627,7 @@  discard block
 block discarded – undo
1627 1627
         $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1628 1628
         // load template
1629 1629
         EEH_Template::display_template(
1630
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1630
+            EVENTS_TEMPLATE_PATH.'event_publish_box_extras.template.php',
1631 1631
             $publish_box_extra_args
1632 1632
         );
1633 1633
     }
@@ -1658,7 +1658,7 @@  discard block
 block discarded – undo
1658 1658
         $this->verify_cpt_object();
1659 1659
         $use_advanced_editor = $this->admin_config->useAdvancedEditor();
1660 1660
         // check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
1661
-        if (! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1661
+        if ( ! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1662 1662
             $this->addMetaBox(
1663 1663
                 'espresso_event_editor_event_options',
1664 1664
                 esc_html__('Event Registration Options', 'event_espresso'),
@@ -1667,7 +1667,7 @@  discard block
 block discarded – undo
1667 1667
                 'side'
1668 1668
             );
1669 1669
         }
1670
-        if (! $use_advanced_editor) {
1670
+        if ( ! $use_advanced_editor) {
1671 1671
             $this->addMetaBox(
1672 1672
                 'espresso_event_editor_tickets',
1673 1673
                 esc_html__('Event Datetime & Ticket', 'event_espresso'),
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
         } elseif ($this->feature->allowed('use_reg_options_meta_box')) {
1680 1680
             add_action(
1681 1681
                 'add_meta_boxes_espresso_events',
1682
-                function () {
1682
+                function() {
1683 1683
                     global $current_screen;
1684 1684
                     remove_meta_box('authordiv', $current_screen, 'normal');
1685 1685
                 },
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
             'trash_icon'               => 'dashicons dashicons-lock',
1715 1715
             'disabled'                 => '',
1716 1716
         ];
1717
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1717
+        $event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1718 1718
         /**
1719 1719
          * 1. Start with retrieving Datetimes
1720 1720
          * 2. Fore each datetime get related tickets
@@ -1740,24 +1740,24 @@  discard block
 block discarded – undo
1740 1740
                     'default_where_conditions' => 'none',
1741 1741
                 ]
1742 1742
             );
1743
-            if (! empty($related_tickets)) {
1743
+            if ( ! empty($related_tickets)) {
1744 1744
                 $template_args['total_ticket_rows'] = count($related_tickets);
1745 1745
                 $row                                = 0;
1746 1746
                 foreach ($related_tickets as $ticket) {
1747
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1747
+                    $existing_ticket_ids[] = $ticket->get('TKT_ID');
1748 1748
                     $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1749 1749
                     $row++;
1750 1750
                 }
1751 1751
             } else {
1752 1752
                 $template_args['total_ticket_rows'] = 1;
1753 1753
                 /** @type EE_Ticket $ticket */
1754
-                $ticket                       = $ticket_model->create_default_object();
1754
+                $ticket = $ticket_model->create_default_object();
1755 1755
                 $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1756 1756
             }
1757 1757
         } else {
1758 1758
             $template_args['time'] = $times[0];
1759 1759
             /** @type EE_Ticket[] $tickets */
1760
-            $tickets                      = $ticket_model->get_all_default_tickets();
1760
+            $tickets = $ticket_model->get_all_default_tickets();
1761 1761
             $template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1762 1762
             // NOTE: we're just sending the first default row
1763 1763
             // (decaf can't manage default tickets so this should be sufficient);
@@ -1772,9 +1772,9 @@  discard block
 block discarded – undo
1772 1772
             $ticket_model->create_default_object(),
1773 1773
             true
1774 1774
         );
1775
-        $template                                  = apply_filters(
1775
+        $template = apply_filters(
1776 1776
             'FHEE__Events_Admin_Page__ticket_metabox__template',
1777
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1777
+            EVENTS_TEMPLATE_PATH.'event_tickets_metabox_main.template.php'
1778 1778
         );
1779 1779
         EEH_Template::display_template($template, $template_args);
1780 1780
     }
@@ -1794,7 +1794,7 @@  discard block
 block discarded – undo
1794 1794
     private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1795 1795
     {
1796 1796
         $template_args = [
1797
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1797
+            'tkt_status_class'    => ' tkt-status-'.$ticket->ticket_status(),
1798 1798
             'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1799 1799
                 : '',
1800 1800
             'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
@@ -1806,10 +1806,10 @@  discard block
 block discarded – undo
1806 1806
             'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1807 1807
             'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1808 1808
             'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1809
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1810
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1809
+            'trash_icon'          => ($skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')))
1810
+                                     && ( ! empty($ticket) && $ticket->get('TKT_sold') === 0)
1811 1811
                 ? 'trash-icon dashicons dashicons-post-trash clickable' : 'dashicons dashicons-lock',
1812
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1812
+            'disabled'            => $skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1813 1813
                 : ' disabled=disabled',
1814 1814
         ];
1815 1815
         $price         = $ticket->ID() !== 0
@@ -1833,7 +1833,7 @@  discard block
 block discarded – undo
1833 1833
         }
1834 1834
         if (empty($template_args['TKT_end_date'])) {
1835 1835
             // get the earliest datetime (if present);
1836
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1836
+            $earliest_datetime = $this->_cpt_model_obj->ID() > 0
1837 1837
                 ? $this->_cpt_model_obj->get_first_related(
1838 1838
                     'Datetime',
1839 1839
                     ['order_by' => ['DTT_EVT_start' => 'ASC']]
@@ -1846,7 +1846,7 @@  discard block
 block discarded – undo
1846 1846
         $template_args = array_merge($template_args, $price_args);
1847 1847
         $template      = apply_filters(
1848 1848
             'FHEE__Events_Admin_Page__get_ticket_row__template',
1849
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1849
+            EVENTS_TEMPLATE_PATH.'event_tickets_metabox_ticket_row.template.php',
1850 1850
             $ticket
1851 1851
         );
1852 1852
         return EEH_Template::display_template($template, $template_args, true);
@@ -1859,7 +1859,7 @@  discard block
 block discarded – undo
1859 1859
      */
1860 1860
     public function registration_options_meta_box()
1861 1861
     {
1862
-        $yes_no_values             = [
1862
+        $yes_no_values = [
1863 1863
             ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1864 1864
             ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1865 1865
         ];
@@ -1881,12 +1881,12 @@  discard block
 block discarded – undo
1881 1881
             $default_reg_status_values,
1882 1882
             $this->_cpt_model_obj->default_registration_status()
1883 1883
         );
1884
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1884
+        $template_args['display_description'] = EEH_Form_Fields::select_input(
1885 1885
             'display_desc',
1886 1886
             $yes_no_values,
1887 1887
             $this->_cpt_model_obj->display_description()
1888 1888
         );
1889
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1889
+        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1890 1890
             'display_ticket_selector',
1891 1891
             $yes_no_values,
1892 1892
             $this->_cpt_model_obj->display_ticket_selector(),
@@ -1902,7 +1902,7 @@  discard block
 block discarded – undo
1902 1902
             $default_reg_status_values
1903 1903
         );
1904 1904
         EEH_Template::display_template(
1905
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1905
+            EVENTS_TEMPLATE_PATH.'event_registration_options.template.php',
1906 1906
             $template_args
1907 1907
         );
1908 1908
     }
@@ -1925,7 +1925,7 @@  discard block
 block discarded – undo
1925 1925
     {
1926 1926
         $EEM_Event   = $this->_event_model();
1927 1927
         $offset      = ($current_page - 1) * $per_page;
1928
-        $limit       = $count ? null : $offset . ',' . $per_page;
1928
+        $limit       = $count ? null : $offset.','.$per_page;
1929 1929
         $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1930 1930
         $order       = $this->request->getRequestParam('order', 'DESC');
1931 1931
         $month_range = $this->request->getRequestParam('month_range');
@@ -1962,10 +1962,10 @@  discard block
 block discarded – undo
1962 1962
         $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1963 1963
         if ($month_range) {
1964 1964
             $DateTime = new DateTime(
1965
-                $year_r . '-' . $month_r . '-01 00:00:00',
1965
+                $year_r.'-'.$month_r.'-01 00:00:00',
1966 1966
                 new DateTimeZone('UTC')
1967 1967
             );
1968
-            $start    = $DateTime->getTimestamp();
1968
+            $start = $DateTime->getTimestamp();
1969 1969
             // set the datetime to be the end of the month
1970 1970
             $DateTime->setDate(
1971 1971
                 $year_r,
@@ -1990,11 +1990,11 @@  discard block
 block discarded – undo
1990 1990
                                                         ->format(implode(' ', $start_formats));
1991 1991
             $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1992 1992
         }
1993
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1993
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1994 1994
             $where['EVT_wp_user'] = get_current_user_id();
1995 1995
         } else {
1996
-            if (! isset($where['status'])) {
1997
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1996
+            if ( ! isset($where['status'])) {
1997
+                if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1998 1998
                     $where['OR'] = [
1999 1999
                         'status*restrict_private' => ['!=', 'private'],
2000 2000
                         'AND'                     => [
@@ -2016,7 +2016,7 @@  discard block
 block discarded – undo
2016 2016
         // search query handling
2017 2017
         $search_term = $this->request->getRequestParam('s');
2018 2018
         if ($search_term) {
2019
-            $search_term = '%' . $search_term . '%';
2019
+            $search_term = '%'.$search_term.'%';
2020 2020
             $where['OR'] = [
2021 2021
                 'EVT_name'       => ['LIKE', $search_term],
2022 2022
                 'EVT_desc'       => ['LIKE', $search_term],
@@ -2124,7 +2124,7 @@  discard block
 block discarded – undo
2124 2124
             // clean status
2125 2125
             $event_status = sanitize_key($event_status);
2126 2126
             // grab status
2127
-            if (! empty($event_status)) {
2127
+            if ( ! empty($event_status)) {
2128 2128
                 $success = $this->_change_event_status($EVT_ID, $event_status);
2129 2129
             } else {
2130 2130
                 $success = false;
@@ -2164,7 +2164,7 @@  discard block
 block discarded – undo
2164 2164
         // clean status
2165 2165
         $event_status = sanitize_key($event_status);
2166 2166
         // grab status
2167
-        if (! empty($event_status)) {
2167
+        if ( ! empty($event_status)) {
2168 2168
             $success = true;
2169 2169
             // determine the event id and set to array.
2170 2170
             $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
@@ -2210,7 +2210,7 @@  discard block
 block discarded – undo
2210 2210
     private function _change_event_status($EVT_ID = 0, $event_status = '')
2211 2211
     {
2212 2212
         // grab event id
2213
-        if (! $EVT_ID) {
2213
+        if ( ! $EVT_ID) {
2214 2214
             $msg = esc_html__(
2215 2215
                 'An error occurred. No Event ID or an invalid Event ID was received.',
2216 2216
                 'event_espresso'
@@ -2247,7 +2247,7 @@  discard block
 block discarded – undo
2247 2247
         // use class to change status
2248 2248
         $this->_cpt_model_obj->set_status($event_status);
2249 2249
         $success = $this->_cpt_model_obj->save();
2250
-        if (! $success) {
2250
+        if ( ! $success) {
2251 2251
             $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2252 2252
             EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2253 2253
             return false;
@@ -2305,7 +2305,7 @@  discard block
 block discarded – undo
2305 2305
      */
2306 2306
     protected function getModelObjNodeGroupPersister()
2307 2307
     {
2308
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2308
+        if ( ! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2309 2309
             $this->model_obj_node_group_persister =
2310 2310
                 $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2311 2311
         }
@@ -2615,7 +2615,7 @@  discard block
 block discarded – undo
2615 2615
                                                 . esc_html__(
2616 2616
                                                     '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.',
2617 2617
                                                     'event_espresso'
2618
-                                                ) . '</strong>';
2618
+                                                ).'</strong>';
2619 2619
         $this->display_admin_caf_preview_page('template_settings_tab');
2620 2620
     }
2621 2621
 
@@ -2636,11 +2636,11 @@  discard block
 block discarded – undo
2636 2636
         $this->_set_empty_category_object();
2637 2637
         // only set if we've got an id
2638 2638
         $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2639
-        if (! $category_ID) {
2639
+        if ( ! $category_ID) {
2640 2640
             return;
2641 2641
         }
2642 2642
         $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2643
-        if (! empty($term)) {
2643
+        if ( ! empty($term)) {
2644 2644
             $this->_category->category_name       = $term->name;
2645 2645
             $this->_category->category_identifier = $term->slug;
2646 2646
             $this->_category->category_desc       = $term->description;
@@ -2744,7 +2744,7 @@  discard block
 block discarded – undo
2744 2744
             $category_select_values,
2745 2745
             $this->_category->parent
2746 2746
         );
2747
-        $template_args   = [
2747
+        $template_args = [
2748 2748
             'category'                 => $this->_category,
2749 2749
             'category_select'          => $category_select,
2750 2750
             'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
@@ -2752,7 +2752,7 @@  discard block
 block discarded – undo
2752 2752
             'disable'                  => '',
2753 2753
             'disabled_message'         => false,
2754 2754
         ];
2755
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2755
+        $template = EVENTS_TEMPLATE_PATH.'event_category_details.template.php';
2756 2756
         return EEH_Template::display_template($template, $template_args, true);
2757 2757
     }
2758 2758
 
@@ -2842,7 +2842,7 @@  discard block
 block discarded – undo
2842 2842
         $insert_ids = $update
2843 2843
             ? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2844 2844
             : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2845
-        if (! is_array($insert_ids)) {
2845
+        if ( ! is_array($insert_ids)) {
2846 2846
             $msg = esc_html__(
2847 2847
                 'An error occurred and the category has not been saved to the database.',
2848 2848
                 'event_espresso'
@@ -2878,7 +2878,7 @@  discard block
 block discarded – undo
2878 2878
         $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2879 2879
         $search_term = $this->request->getRequestParam('s');
2880 2880
         if ($search_term) {
2881
-            $search_term = '%' . $search_term . '%';
2881
+            $search_term = '%'.$search_term.'%';
2882 2882
             $where['OR'] = [
2883 2883
                 'Term.name'   => ['LIKE', $search_term],
2884 2884
                 'description' => ['LIKE', $search_term],
@@ -2887,7 +2887,7 @@  discard block
 block discarded – undo
2887 2887
         $query_params = [
2888 2888
             $where,
2889 2889
             'order_by'   => [$orderby => $order],
2890
-            'limit'      => $limit . ',' . $per_page,
2890
+            'limit'      => $limit.','.$per_page,
2891 2891
             'force_join' => ['Term'],
2892 2892
         ];
2893 2893
         return $count
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Indentation   +1453 added lines, -1453 removed lines patch added patch discarded remove patch
@@ -27,476 +27,476 @@  discard block
 block discarded – undo
27 27
  */
28 28
 abstract class EE_Admin_Page_CPT extends EE_Admin_Page
29 29
 {
30
-    /**
31
-     * This gets set in _setup_cpt
32
-     * It will contain the object for the custom post type.
33
-     *
34
-     * @var EE_CPT_Base
35
-     */
36
-    protected $_cpt_object;
37
-
38
-
39
-    /**
40
-     * a boolean flag to set whether the current route is a cpt route or not.
41
-     *
42
-     * @var bool
43
-     */
44
-    protected $_cpt_route = false;
45
-
46
-
47
-    /**
48
-     * This property allows cpt classes to define multiple routes as cpt routes.
49
-     * //in this array we define what the custom post type for this route is.
50
-     * array(
51
-     * 'route_name' => 'custom_post_type_slug'
52
-     * )
53
-     *
54
-     * @var array
55
-     */
56
-    protected $_cpt_routes = [];
57
-
58
-
59
-    /**
60
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
-     * in this format:
62
-     * array(
63
-     * 'post_type_slug' => 'edit_route'
64
-     * )
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_cpt_edit_routes = [];
69
-
70
-
71
-    /**
72
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
73
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
74
-     * _cpt_model_names property should be in the following format: array(
75
-     * 'route_defined_by_action_param' => 'Model_Name')
76
-     *
77
-     * @var array $_cpt_model_names
78
-     */
79
-    protected $_cpt_model_names = [];
80
-
81
-
82
-    /**
83
-     * @var EE_CPT_Base
84
-     */
85
-    protected $_cpt_model_obj = false;
86
-
87
-
88
-    /**
89
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
90
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
91
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
92
-     * Registration of containers should be done before load_page_dependencies() is run.
93
-     *
94
-     * @var array()
95
-     */
96
-    protected $_autosave_containers = [];
97
-
98
-    protected $_autosave_fields     = [];
99
-
100
-    /**
101
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
102
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
103
-     *
104
-     * @var array
105
-     */
106
-    protected $_pagenow_map;
107
-
108
-
109
-
110
-    /**
111
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
112
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
113
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
114
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
115
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
116
-     *
117
-     * @abstract
118
-     * @param string      $post_id The ID of the cpt that was saved (so you can link relationally)
119
-     * @param WP_Post     $post    The post object of the cpt that was saved.
120
-     * @return void
121
-     */
122
-    abstract protected function _insert_update_cpt_item($post_id, $post);
123
-
124
-
125
-    /**
126
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
127
-     *
128
-     * @abstract
129
-     * @param string $post_id The ID of the cpt that was trashed
130
-     * @return void
131
-     */
132
-    abstract public function trash_cpt_item($post_id);
133
-
134
-
135
-    /**
136
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
137
-     *
138
-     * @param string $post_id theID of the cpt that was untrashed
139
-     * @return void
140
-     */
141
-    abstract public function restore_cpt_item($post_id);
142
-
143
-
144
-    /**
145
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
146
-     * from the db
147
-     *
148
-     * @param string $post_id the ID of the cpt that was deleted
149
-     * @return void
150
-     */
151
-    abstract public function delete_cpt_item($post_id);
152
-
153
-
154
-    /**
155
-     * @return LoaderInterface
156
-     * @throws InvalidArgumentException
157
-     * @throws InvalidDataTypeException
158
-     * @throws InvalidInterfaceException
159
-     */
160
-    protected function getLoader()
161
-    {
162
-        if (! $this->loader instanceof LoaderInterface) {
163
-            $this->loader = LoaderFactory::getLoader();
164
-        }
165
-        return $this->loader;
166
-    }
167
-
168
-
169
-    /**
170
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
171
-     *
172
-     * @return void
173
-     */
174
-    protected function _before_page_setup()
175
-    {
176
-        $this->raw_req_action = $this->request->getRequestParam('action');
177
-        $this->raw_req_page = $this->request->getRequestParam('page');
178
-        $this->_cpt_routes = array_merge(
179
-            [
180
-                'create_new' => $this->page_slug,
181
-                'edit'       => $this->page_slug,
182
-                'trash'      => $this->page_slug,
183
-            ],
184
-            $this->_cpt_routes
185
-        );
186
-        $cpt_route_action  = isset($this->_cpt_routes[ $this->raw_req_action ])
187
-            ? $this->_cpt_routes[ $this->raw_req_action ]
188
-            : null;
189
-        // let's see if the current route has a value for cpt_object_slug. if it does, we use that instead of the page
190
-        $page              = $this->raw_req_page ?: $this->page_slug;
191
-        $page              = $cpt_route_action ?: $page;
192
-        $this->_cpt_object = get_post_type_object($page);
193
-        // tweak pagenow for page loading.
194
-        if (! $this->_pagenow_map) {
195
-            $this->_pagenow_map = [
196
-                'create_new' => 'post-new.php',
197
-                'edit'       => 'post.php',
198
-                'trash'      => 'post.php',
199
-            ];
200
-        }
201
-        add_action('current_screen', [$this, 'modify_pagenow']);
202
-        // TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
203
-        // get current page from autosave
204
-        $current_page        = $this->request->getRequestParam('ee_autosave_data[ee-cpt-hidden-inputs][current_page]');
205
-        $this->_current_page = $this->request->getRequestParam('current_page', $current_page);
206
-    }
207
-
208
-
209
-    /**
210
-     * Simply ensure that we simulate the correct post route for cpt screens
211
-     *
212
-     * @param WP_Screen $current_screen
213
-     * @return void
214
-     */
215
-    public function modify_pagenow($current_screen)
216
-    {
217
-        // possibly reset pagenow.
218
-        if (
219
-            $this->page_slug === $this->raw_req_page
220
-            && isset($this->_pagenow_map[ $this->raw_req_action ])
221
-        ) {
222
-            global $pagenow, $hook_suffix;
223
-            $pagenow     = $this->_pagenow_map[ $this->raw_req_action ];
224
-            $hook_suffix = $pagenow;
225
-        }
226
-    }
227
-
228
-
229
-    /**
230
-     * This method is used to register additional autosave containers to the _autosave_containers property.
231
-     *
232
-     * @param array $ids  an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
-     *                    you would send along the id of a metabox container.
234
-     * @return void
235
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
236
-     *                    automatically register the id for the post metabox as a container.
237
-     */
238
-    protected function _register_autosave_containers($ids)
239
-    {
240
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
241
-    }
242
-
243
-
244
-    /**
245
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
246
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
247
-     */
248
-    protected function _set_autosave_containers()
249
-    {
250
-        global $wp_meta_boxes;
251
-        $containers = [];
252
-        if (empty($wp_meta_boxes)) {
253
-            return;
254
-        }
255
-        $current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : [];
256
-        foreach ($current_metaboxes as $box_context) {
257
-            foreach ($box_context as $box_details) {
258
-                foreach ($box_details as $box) {
259
-                    if (
260
-                        is_array($box) && is_array($box['callback'])
261
-                        && (
262
-                            $box['callback'][0] instanceof EE_Admin_Page
263
-                            || $box['callback'][0] instanceof EE_Admin_Hooks
264
-                        )
265
-                    ) {
266
-                        $containers[] = $box['id'];
267
-                    }
268
-                }
269
-            }
270
-        }
271
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
272
-        // add hidden inputs container
273
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
274
-    }
275
-
276
-
277
-    protected function _load_autosave_scripts_styles()
278
-    {
279
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
30
+	/**
31
+	 * This gets set in _setup_cpt
32
+	 * It will contain the object for the custom post type.
33
+	 *
34
+	 * @var EE_CPT_Base
35
+	 */
36
+	protected $_cpt_object;
37
+
38
+
39
+	/**
40
+	 * a boolean flag to set whether the current route is a cpt route or not.
41
+	 *
42
+	 * @var bool
43
+	 */
44
+	protected $_cpt_route = false;
45
+
46
+
47
+	/**
48
+	 * This property allows cpt classes to define multiple routes as cpt routes.
49
+	 * //in this array we define what the custom post type for this route is.
50
+	 * array(
51
+	 * 'route_name' => 'custom_post_type_slug'
52
+	 * )
53
+	 *
54
+	 * @var array
55
+	 */
56
+	protected $_cpt_routes = [];
57
+
58
+
59
+	/**
60
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
+	 * in this format:
62
+	 * array(
63
+	 * 'post_type_slug' => 'edit_route'
64
+	 * )
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_cpt_edit_routes = [];
69
+
70
+
71
+	/**
72
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
73
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
74
+	 * _cpt_model_names property should be in the following format: array(
75
+	 * 'route_defined_by_action_param' => 'Model_Name')
76
+	 *
77
+	 * @var array $_cpt_model_names
78
+	 */
79
+	protected $_cpt_model_names = [];
80
+
81
+
82
+	/**
83
+	 * @var EE_CPT_Base
84
+	 */
85
+	protected $_cpt_model_obj = false;
86
+
87
+
88
+	/**
89
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
90
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
91
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
92
+	 * Registration of containers should be done before load_page_dependencies() is run.
93
+	 *
94
+	 * @var array()
95
+	 */
96
+	protected $_autosave_containers = [];
97
+
98
+	protected $_autosave_fields     = [];
99
+
100
+	/**
101
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
102
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
103
+	 *
104
+	 * @var array
105
+	 */
106
+	protected $_pagenow_map;
107
+
108
+
109
+
110
+	/**
111
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
112
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
113
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
114
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
115
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
116
+	 *
117
+	 * @abstract
118
+	 * @param string      $post_id The ID of the cpt that was saved (so you can link relationally)
119
+	 * @param WP_Post     $post    The post object of the cpt that was saved.
120
+	 * @return void
121
+	 */
122
+	abstract protected function _insert_update_cpt_item($post_id, $post);
123
+
124
+
125
+	/**
126
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
127
+	 *
128
+	 * @abstract
129
+	 * @param string $post_id The ID of the cpt that was trashed
130
+	 * @return void
131
+	 */
132
+	abstract public function trash_cpt_item($post_id);
133
+
134
+
135
+	/**
136
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
137
+	 *
138
+	 * @param string $post_id theID of the cpt that was untrashed
139
+	 * @return void
140
+	 */
141
+	abstract public function restore_cpt_item($post_id);
142
+
143
+
144
+	/**
145
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
146
+	 * from the db
147
+	 *
148
+	 * @param string $post_id the ID of the cpt that was deleted
149
+	 * @return void
150
+	 */
151
+	abstract public function delete_cpt_item($post_id);
152
+
153
+
154
+	/**
155
+	 * @return LoaderInterface
156
+	 * @throws InvalidArgumentException
157
+	 * @throws InvalidDataTypeException
158
+	 * @throws InvalidInterfaceException
159
+	 */
160
+	protected function getLoader()
161
+	{
162
+		if (! $this->loader instanceof LoaderInterface) {
163
+			$this->loader = LoaderFactory::getLoader();
164
+		}
165
+		return $this->loader;
166
+	}
167
+
168
+
169
+	/**
170
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
171
+	 *
172
+	 * @return void
173
+	 */
174
+	protected function _before_page_setup()
175
+	{
176
+		$this->raw_req_action = $this->request->getRequestParam('action');
177
+		$this->raw_req_page = $this->request->getRequestParam('page');
178
+		$this->_cpt_routes = array_merge(
179
+			[
180
+				'create_new' => $this->page_slug,
181
+				'edit'       => $this->page_slug,
182
+				'trash'      => $this->page_slug,
183
+			],
184
+			$this->_cpt_routes
185
+		);
186
+		$cpt_route_action  = isset($this->_cpt_routes[ $this->raw_req_action ])
187
+			? $this->_cpt_routes[ $this->raw_req_action ]
188
+			: null;
189
+		// let's see if the current route has a value for cpt_object_slug. if it does, we use that instead of the page
190
+		$page              = $this->raw_req_page ?: $this->page_slug;
191
+		$page              = $cpt_route_action ?: $page;
192
+		$this->_cpt_object = get_post_type_object($page);
193
+		// tweak pagenow for page loading.
194
+		if (! $this->_pagenow_map) {
195
+			$this->_pagenow_map = [
196
+				'create_new' => 'post-new.php',
197
+				'edit'       => 'post.php',
198
+				'trash'      => 'post.php',
199
+			];
200
+		}
201
+		add_action('current_screen', [$this, 'modify_pagenow']);
202
+		// TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
203
+		// get current page from autosave
204
+		$current_page        = $this->request->getRequestParam('ee_autosave_data[ee-cpt-hidden-inputs][current_page]');
205
+		$this->_current_page = $this->request->getRequestParam('current_page', $current_page);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Simply ensure that we simulate the correct post route for cpt screens
211
+	 *
212
+	 * @param WP_Screen $current_screen
213
+	 * @return void
214
+	 */
215
+	public function modify_pagenow($current_screen)
216
+	{
217
+		// possibly reset pagenow.
218
+		if (
219
+			$this->page_slug === $this->raw_req_page
220
+			&& isset($this->_pagenow_map[ $this->raw_req_action ])
221
+		) {
222
+			global $pagenow, $hook_suffix;
223
+			$pagenow     = $this->_pagenow_map[ $this->raw_req_action ];
224
+			$hook_suffix = $pagenow;
225
+		}
226
+	}
227
+
228
+
229
+	/**
230
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
231
+	 *
232
+	 * @param array $ids  an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
+	 *                    you would send along the id of a metabox container.
234
+	 * @return void
235
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
236
+	 *                    automatically register the id for the post metabox as a container.
237
+	 */
238
+	protected function _register_autosave_containers($ids)
239
+	{
240
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
241
+	}
242
+
243
+
244
+	/**
245
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
246
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
247
+	 */
248
+	protected function _set_autosave_containers()
249
+	{
250
+		global $wp_meta_boxes;
251
+		$containers = [];
252
+		if (empty($wp_meta_boxes)) {
253
+			return;
254
+		}
255
+		$current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : [];
256
+		foreach ($current_metaboxes as $box_context) {
257
+			foreach ($box_context as $box_details) {
258
+				foreach ($box_details as $box) {
259
+					if (
260
+						is_array($box) && is_array($box['callback'])
261
+						&& (
262
+							$box['callback'][0] instanceof EE_Admin_Page
263
+							|| $box['callback'][0] instanceof EE_Admin_Hooks
264
+						)
265
+					) {
266
+						$containers[] = $box['id'];
267
+					}
268
+				}
269
+			}
270
+		}
271
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
272
+		// add hidden inputs container
273
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
274
+	}
275
+
276
+
277
+	protected function _load_autosave_scripts_styles()
278
+	{
279
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
280 280
         wp_enqueue_script('cpt-autosave');/**/ // todo re-enable when we start doing autosave again in 4.2
281 281
 
282
-        // filter _autosave_containers
283
-        $containers = apply_filters(
284
-            'FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
285
-            $this->_autosave_containers,
286
-            $this
287
-        );
288
-        $containers = apply_filters(
289
-            'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
290
-            $containers,
291
-            $this
292
-        );
293
-
294
-        wp_localize_script(
295
-            'event_editor_js',
296
-            'EE_AUTOSAVE_IDS',
297
-            $containers
298
-        ); // todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
299
-
300
-        $unsaved_data_msg = [
301
-            'eventmsg'     => sprintf(
302
-                wp_strip_all_tags(
303
-                    __(
304
-                        "The changes you made to this %s will be lost if you navigate away from this page.",
305
-                        'event_espresso'
306
-                    )
307
-                ),
308
-                $this->_cpt_object->labels->singular_name
309
-            ),
310
-            'inputChanged' => 0,
311
-        ];
312
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
313
-    }
314
-
315
-
316
-    /**
317
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
318
-     *
319
-     * @return void
320
-     * @throws EE_Error
321
-     * @throws ReflectionException
322
-     */
323
-    protected function _load_page_dependencies()
324
-    {
325
-        // we only add stuff if this is a cpt_route!
326
-        if (! $this->_cpt_route) {
327
-            parent::_load_page_dependencies();
328
-            return;
329
-        }
330
-        // now let's do some automatic filters into the wp_system
331
-        // and we'll check to make sure the CHILD class
332
-        // automatically has the required methods in place.
333
-        // the following filters are for setting all the redirects
334
-        // on DEFAULT WP custom post type actions
335
-        // let's add a hidden input to the post-edit form
336
-        // so we know when we have to trigger our custom redirects!
337
-        // Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
338
-        add_action('edit_form_after_title', [$this, 'cpt_post_form_hidden_input']);
339
-        // inject our Admin page nav tabs...
340
-        // let's make sure the nav tabs are set if they aren't already
341
-        // if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
342
-        add_action('edit_form_top', [$this, 'inject_nav_tabs']);
343
-        // modify the post_updated messages array
344
-        add_action('post_updated_messages', [$this, 'post_update_messages'], 10);
345
-        // add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
346
-        // cpts use the same format for shortlinks as posts!
347
-        add_filter('pre_get_shortlink', [$this, 'add_shortlink_button_to_editor'], 10, 4);
348
-        // This basically allows us to change the title of the "publish" metabox area
349
-        // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
350
-        if (! empty($this->_labels['publishbox'])) {
351
-            $box_label = is_array($this->_labels['publishbox'])
352
-                         && isset($this->_labels['publishbox'][ $this->_req_action ])
353
-                ? $this->_labels['publishbox'][ $this->_req_action ]
354
-                : $this->_labels['publishbox'];
355
-            $this->addMetaBox(
356
-                'submitdiv',
357
-                $box_label,
358
-                'post_submit_meta_box',
359
-                $this->_cpt_routes[ $this->_req_action ],
360
-                'side',
361
-                'core'
362
-            );
363
-        }
364
-        // let's add page_templates metabox if this cpt added support for it.
365
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
366
-            $this->addMetaBox(
367
-                'page_templates',
368
-                esc_html__('Page Template', 'event_espresso'),
369
-                [$this, 'page_template_meta_box'],
370
-                $this->_cpt_routes[ $this->_req_action ],
371
-                'side',
372
-                'default'
373
-            );
374
-        }
375
-        // this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
376
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
377
-            add_filter('get_sample_permalink_html', [$this, 'extra_permalink_field_buttons'], 10, 4);
378
-        }
379
-        // add preview button
380
-        add_filter('get_sample_permalink_html', [$this, 'preview_button_html'], 5, 4);
381
-        // insert our own post_stati dropdown
382
-        add_action('post_submitbox_misc_actions', [$this, 'custom_post_stati_dropdown'], 10);
383
-        // This allows adding additional information to the publish post submitbox on the wp post edit form
384
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
385
-            add_action('post_submitbox_misc_actions', [$this, 'extra_misc_actions_publish_box'], 10);
386
-        }
387
-        // This allows for adding additional stuff after the title field on the wp post edit form.
388
-        // This is also before the wp_editor for post description field.
389
-        if (method_exists($this, 'edit_form_after_title')) {
390
-            add_action('edit_form_after_title', [$this, 'edit_form_after_title'], 10);
391
-        }
392
-        /**
393
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
394
-         */
395
-        add_filter('clean_url', [$this, 'switch_core_wp_urls_with_ours'], 10, 3);
396
-        parent::_load_page_dependencies();
397
-        // notice we are ALSO going to load the pagenow hook set for this route
398
-        // (see _before_page_setup for the reset of the pagenow global ).
399
-        // This is for any plugins that are doing things properly
400
-        // and hooking into the load page hook for core wp cpt routes.
401
-        global $pagenow;
402
-        add_action('load-' . $pagenow, [$this, 'modify_current_screen'], 20);
403
-        do_action('load-' . $pagenow);
404
-        add_action('admin_enqueue_scripts', [$this, 'setup_autosave_hooks'], 30);
405
-        // we route REALLY early.
406
-        try {
407
-            $this->_route_admin_request();
408
-        } catch (EE_Error $e) {
409
-            $e->get_error();
410
-        }
411
-    }
412
-
413
-
414
-    /**
415
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
416
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
417
-     * route instead.
418
-     *
419
-     * @param string $good_protocol_url The escaped url.
420
-     * @param string $original_url      The original url.
421
-     * @param string $_context          The context sent to the esc_url method.
422
-     * @return string possibly a new url for our route.
423
-     */
424
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
425
-    {
426
-        $routes_to_match = [
427
-            0 => [
428
-                'edit.php?post_type=espresso_attendees',
429
-                'admin.php?page=espresso_registrations&action=contact_list',
430
-            ],
431
-            1 => [
432
-                'edit.php?post_type=' . $this->_cpt_object->name,
433
-                'admin.php?page=' . $this->_cpt_object->name,
434
-            ],
435
-        ];
436
-        foreach ($routes_to_match as $route_matches) {
437
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
438
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
439
-            }
440
-        }
441
-        return $good_protocol_url;
442
-    }
443
-
444
-
445
-    /**
446
-     * Determine whether the current cpt supports page templates or not.
447
-     *
448
-     * @param string $cpt_name The cpt slug we're checking on.
449
-     * @return bool True supported, false not.
450
-     * @throws InvalidArgumentException
451
-     * @throws InvalidDataTypeException
452
-     * @throws InvalidInterfaceException
453
-     * @since %VER%
454
-     */
455
-    private function _supports_page_templates($cpt_name)
456
-    {
457
-        /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
458
-        $custom_post_types = $this->loader->getShared(
459
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
460
-        );
461
-        $cpt_args          = $custom_post_types->getDefinitions();
462
-        $cpt_args          = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : [];
463
-        $cpt_has_support   = ! empty($cpt_args['page_templates']);
464
-
465
-        // if the installed version of WP is > 4.7 we do some additional checks.
466
-        if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
467
-            $post_templates = wp_get_theme()->get_post_templates();
468
-            // if there are $post_templates for this cpt, then we return false for this method because
469
-            // that means we aren't going to load our page template manager and leave that up to the native
470
-            // cpt template manager.
471
-            $cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
472
-        }
473
-
474
-        return $cpt_has_support;
475
-    }
476
-
477
-
478
-    /**
479
-     * Callback for the page_templates metabox selector.
480
-     *
481
-     * @return void
482
-     * @since %VER%
483
-     */
484
-    public function page_template_meta_box()
485
-    {
486
-        global $post;
487
-        $template = '';
488
-
489
-        if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
490
-            $page_template_count = count(get_page_templates());
491
-        } else {
492
-            $page_template_count = count(get_page_templates($post));
493
-        }
494
-
495
-        if ($page_template_count) {
496
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
497
-            $template      = ! empty($page_template) ? $page_template : '';
498
-        }
499
-        ?>
282
+		// filter _autosave_containers
283
+		$containers = apply_filters(
284
+			'FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
285
+			$this->_autosave_containers,
286
+			$this
287
+		);
288
+		$containers = apply_filters(
289
+			'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
290
+			$containers,
291
+			$this
292
+		);
293
+
294
+		wp_localize_script(
295
+			'event_editor_js',
296
+			'EE_AUTOSAVE_IDS',
297
+			$containers
298
+		); // todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
299
+
300
+		$unsaved_data_msg = [
301
+			'eventmsg'     => sprintf(
302
+				wp_strip_all_tags(
303
+					__(
304
+						"The changes you made to this %s will be lost if you navigate away from this page.",
305
+						'event_espresso'
306
+					)
307
+				),
308
+				$this->_cpt_object->labels->singular_name
309
+			),
310
+			'inputChanged' => 0,
311
+		];
312
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
313
+	}
314
+
315
+
316
+	/**
317
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
318
+	 *
319
+	 * @return void
320
+	 * @throws EE_Error
321
+	 * @throws ReflectionException
322
+	 */
323
+	protected function _load_page_dependencies()
324
+	{
325
+		// we only add stuff if this is a cpt_route!
326
+		if (! $this->_cpt_route) {
327
+			parent::_load_page_dependencies();
328
+			return;
329
+		}
330
+		// now let's do some automatic filters into the wp_system
331
+		// and we'll check to make sure the CHILD class
332
+		// automatically has the required methods in place.
333
+		// the following filters are for setting all the redirects
334
+		// on DEFAULT WP custom post type actions
335
+		// let's add a hidden input to the post-edit form
336
+		// so we know when we have to trigger our custom redirects!
337
+		// Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
338
+		add_action('edit_form_after_title', [$this, 'cpt_post_form_hidden_input']);
339
+		// inject our Admin page nav tabs...
340
+		// let's make sure the nav tabs are set if they aren't already
341
+		// if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
342
+		add_action('edit_form_top', [$this, 'inject_nav_tabs']);
343
+		// modify the post_updated messages array
344
+		add_action('post_updated_messages', [$this, 'post_update_messages'], 10);
345
+		// add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
346
+		// cpts use the same format for shortlinks as posts!
347
+		add_filter('pre_get_shortlink', [$this, 'add_shortlink_button_to_editor'], 10, 4);
348
+		// This basically allows us to change the title of the "publish" metabox area
349
+		// on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
350
+		if (! empty($this->_labels['publishbox'])) {
351
+			$box_label = is_array($this->_labels['publishbox'])
352
+						 && isset($this->_labels['publishbox'][ $this->_req_action ])
353
+				? $this->_labels['publishbox'][ $this->_req_action ]
354
+				: $this->_labels['publishbox'];
355
+			$this->addMetaBox(
356
+				'submitdiv',
357
+				$box_label,
358
+				'post_submit_meta_box',
359
+				$this->_cpt_routes[ $this->_req_action ],
360
+				'side',
361
+				'core'
362
+			);
363
+		}
364
+		// let's add page_templates metabox if this cpt added support for it.
365
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
366
+			$this->addMetaBox(
367
+				'page_templates',
368
+				esc_html__('Page Template', 'event_espresso'),
369
+				[$this, 'page_template_meta_box'],
370
+				$this->_cpt_routes[ $this->_req_action ],
371
+				'side',
372
+				'default'
373
+			);
374
+		}
375
+		// this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
376
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
377
+			add_filter('get_sample_permalink_html', [$this, 'extra_permalink_field_buttons'], 10, 4);
378
+		}
379
+		// add preview button
380
+		add_filter('get_sample_permalink_html', [$this, 'preview_button_html'], 5, 4);
381
+		// insert our own post_stati dropdown
382
+		add_action('post_submitbox_misc_actions', [$this, 'custom_post_stati_dropdown'], 10);
383
+		// This allows adding additional information to the publish post submitbox on the wp post edit form
384
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
385
+			add_action('post_submitbox_misc_actions', [$this, 'extra_misc_actions_publish_box'], 10);
386
+		}
387
+		// This allows for adding additional stuff after the title field on the wp post edit form.
388
+		// This is also before the wp_editor for post description field.
389
+		if (method_exists($this, 'edit_form_after_title')) {
390
+			add_action('edit_form_after_title', [$this, 'edit_form_after_title'], 10);
391
+		}
392
+		/**
393
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
394
+		 */
395
+		add_filter('clean_url', [$this, 'switch_core_wp_urls_with_ours'], 10, 3);
396
+		parent::_load_page_dependencies();
397
+		// notice we are ALSO going to load the pagenow hook set for this route
398
+		// (see _before_page_setup for the reset of the pagenow global ).
399
+		// This is for any plugins that are doing things properly
400
+		// and hooking into the load page hook for core wp cpt routes.
401
+		global $pagenow;
402
+		add_action('load-' . $pagenow, [$this, 'modify_current_screen'], 20);
403
+		do_action('load-' . $pagenow);
404
+		add_action('admin_enqueue_scripts', [$this, 'setup_autosave_hooks'], 30);
405
+		// we route REALLY early.
406
+		try {
407
+			$this->_route_admin_request();
408
+		} catch (EE_Error $e) {
409
+			$e->get_error();
410
+		}
411
+	}
412
+
413
+
414
+	/**
415
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
416
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
417
+	 * route instead.
418
+	 *
419
+	 * @param string $good_protocol_url The escaped url.
420
+	 * @param string $original_url      The original url.
421
+	 * @param string $_context          The context sent to the esc_url method.
422
+	 * @return string possibly a new url for our route.
423
+	 */
424
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
425
+	{
426
+		$routes_to_match = [
427
+			0 => [
428
+				'edit.php?post_type=espresso_attendees',
429
+				'admin.php?page=espresso_registrations&action=contact_list',
430
+			],
431
+			1 => [
432
+				'edit.php?post_type=' . $this->_cpt_object->name,
433
+				'admin.php?page=' . $this->_cpt_object->name,
434
+			],
435
+		];
436
+		foreach ($routes_to_match as $route_matches) {
437
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
438
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
439
+			}
440
+		}
441
+		return $good_protocol_url;
442
+	}
443
+
444
+
445
+	/**
446
+	 * Determine whether the current cpt supports page templates or not.
447
+	 *
448
+	 * @param string $cpt_name The cpt slug we're checking on.
449
+	 * @return bool True supported, false not.
450
+	 * @throws InvalidArgumentException
451
+	 * @throws InvalidDataTypeException
452
+	 * @throws InvalidInterfaceException
453
+	 * @since %VER%
454
+	 */
455
+	private function _supports_page_templates($cpt_name)
456
+	{
457
+		/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
458
+		$custom_post_types = $this->loader->getShared(
459
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
460
+		);
461
+		$cpt_args          = $custom_post_types->getDefinitions();
462
+		$cpt_args          = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : [];
463
+		$cpt_has_support   = ! empty($cpt_args['page_templates']);
464
+
465
+		// if the installed version of WP is > 4.7 we do some additional checks.
466
+		if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
467
+			$post_templates = wp_get_theme()->get_post_templates();
468
+			// if there are $post_templates for this cpt, then we return false for this method because
469
+			// that means we aren't going to load our page template manager and leave that up to the native
470
+			// cpt template manager.
471
+			$cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
472
+		}
473
+
474
+		return $cpt_has_support;
475
+	}
476
+
477
+
478
+	/**
479
+	 * Callback for the page_templates metabox selector.
480
+	 *
481
+	 * @return void
482
+	 * @since %VER%
483
+	 */
484
+	public function page_template_meta_box()
485
+	{
486
+		global $post;
487
+		$template = '';
488
+
489
+		if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
490
+			$page_template_count = count(get_page_templates());
491
+		} else {
492
+			$page_template_count = count(get_page_templates($post));
493
+		}
494
+
495
+		if ($page_template_count) {
496
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
497
+			$template      = ! empty($page_template) ? $page_template : '';
498
+		}
499
+		?>
500 500
         <p><strong><?php esc_html_e('Template', 'event_espresso') ?></strong></p>
501 501
         <label class="screen-reader-text" for="page_template">
502 502
             <?php esc_html_e('Page Template', 'event_espresso') ?>
@@ -506,475 +506,475 @@  discard block
 block discarded – undo
506 506
             <?php page_template_dropdown($template); ?>
507 507
         </select>
508 508
         <?php
509
-    }
510
-
511
-
512
-    /**
513
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
514
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
515
-     *
516
-     * @param string $return    the current html
517
-     * @param int    $id        the post id for the page
518
-     * @param string $new_title What the title is
519
-     * @param string $new_slug  what the slug is
520
-     * @return string            The new html string for the permalink area
521
-     */
522
-    public function preview_button_html($return, $id, $new_title, $new_slug)
523
-    {
524
-        $post = get_post($id);
525
-        if ('publish' !== get_post_status($post)) {
526
-            $return .= '
509
+	}
510
+
511
+
512
+	/**
513
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
514
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
515
+	 *
516
+	 * @param string $return    the current html
517
+	 * @param int    $id        the post id for the page
518
+	 * @param string $new_title What the title is
519
+	 * @param string $new_slug  what the slug is
520
+	 * @return string            The new html string for the permalink area
521
+	 */
522
+	public function preview_button_html($return, $id, $new_title, $new_slug)
523
+	{
524
+		$post = get_post($id);
525
+		if ('publish' !== get_post_status($post)) {
526
+			$return .= '
527 527
             <span id="view-post-btn">
528 528
                 <a target="_blank" href="' . get_preview_post_link($id) . '" class="button button--secondary">
529 529
                     ' . esc_html__('Preview', 'event_espresso') . '
530 530
                 </a>
531 531
             </span>
532 532
             ';
533
-        }
534
-        return $return;
535
-    }
536
-
537
-
538
-    /**
539
-     * add our custom post status dropdown on the wp post page for this cpt
540
-     *
541
-     * @return void
542
-     */
543
-    public function custom_post_stati_dropdown()
544
-    {
545
-
546
-        $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
547
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
548
-            ? $statuses[ $this->_cpt_model_obj->status() ]
549
-            : '';
550
-        $template_args    = [
551
-            'cur_status'            => $this->_cpt_model_obj->status(),
552
-            'statuses'              => $statuses,
553
-            'cur_status_label'      => $cur_status_label,
554
-            'localized_status_save' => sprintf(esc_html__('Save %s', 'event_espresso'), $cur_status_label),
555
-        ];
556
-        // we'll add a trash post status (WP doesn't add one for some reason)
557
-        if ($this->_cpt_model_obj->status() === 'trash') {
558
-            $template_args['cur_status_label'] = esc_html__('Trashed', 'event_espresso');
559
-            $statuses['trash']                 = esc_html__('Trashed', 'event_espresso');
560
-            $template_args['statuses']         = $statuses;
561
-        }
562
-
563
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
564
-        EEH_Template::display_template($template, $template_args);
565
-    }
566
-
567
-
568
-    public function setup_autosave_hooks()
569
-    {
570
-        $this->_set_autosave_containers();
571
-        $this->_load_autosave_scripts_styles();
572
-    }
573
-
574
-
575
-    /**
576
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a post object (available
577
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
578
-     * for the nonce in here, but then this method looks for two things:
579
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
580
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
581
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
582
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
583
-     * template args.
584
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
585
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
586
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
587
-     *    $this->_template_args['data']['items'] = array(
588
-     *        'event-datetime-ids' => '1,2,3';
589
-     *    );
590
-     *    Keep in mind the following things:
591
-     *    - "where" index is for the input with the id as that string.
592
-     *    - "what" index is what will be used for the value of that input.
593
-     *
594
-     * @return void
595
-     * @throws EE_Error
596
-     */
597
-    public function do_extra_autosave_stuff()
598
-    {
599
-        // next let's check for the autosave nonce (we'll use _verify_nonce )
600
-        $nonce = $this->request->getRequestParam('autosavenonce');
601
-        $this->_verify_nonce($nonce, 'autosave');
602
-        // make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
603
-        if (! defined('DOING_AUTOSAVE')) {
604
-            define('DOING_AUTOSAVE', true);
605
-        }
606
-        // if we made it here then the nonce checked out.  Let's run our methods and actions
607
-        $autosave = "_ee_autosave_{$this->_current_view}";
608
-        if (method_exists($this, $autosave)) {
609
-            $this->$autosave();
610
-        } else {
611
-            $this->_template_args['success'] = true;
612
-        }
613
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
614
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
615
-        // now let's return json
616
-        $this->_return_json();
617
-    }
618
-
619
-
620
-    /**
621
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
622
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
623
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
624
-     *
625
-     * @return void
626
-     * @throws EE_Error
627
-     * @throws ReflectionException
628
-     */
629
-    protected function _extend_page_config_for_cpt()
630
-    {
631
-        // before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
632
-        if ($this->raw_req_page !== $this->page_slug) {
633
-            return;
634
-        }
635
-        // set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
636
-        if (! empty($this->_cpt_object)) {
637
-            $this->_page_routes = array_merge(
638
-                [
639
-                    'create_new' => '_create_new_cpt_item',
640
-                    'edit'       => '_edit_cpt_item',
641
-                ],
642
-                $this->_page_routes
643
-            );
644
-            $this->_page_config = array_merge(
645
-                [
646
-                    'create_new' => [
647
-                        'nav'           => [
648
-                            'label' => $this->_cpt_object->labels->add_new_item,
649
-                            'order' => 5,
650
-                        ],
651
-                        'require_nonce' => false,
652
-                    ],
653
-                    'edit'       => [
654
-                        'nav'           => [
655
-                            'label'      => $this->_cpt_object->labels->edit_item,
656
-                            'order'      => 5,
657
-                            'persistent' => false,
658
-                            'url'        => '',
659
-                        ],
660
-                        'require_nonce' => false,
661
-                    ],
662
-                ],
663
-                $this->_page_config
664
-            );
665
-        }
666
-        // load the next section only if this is a matching cpt route as set in the cpt routes array.
667
-        if (! isset($this->_cpt_routes[ $this->_req_action ])) {
668
-            return;
669
-        }
670
-        $this->_cpt_route = true;
671
-        // $this->_cpt_route = isset($this->_cpt_routes[ $this->_req_action ]);
672
-        // add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
673
-        if (empty($this->_cpt_object)) {
674
-            $msg = sprintf(
675
-                esc_html__(
676
-                    'This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).',
677
-                    'event_espresso'
678
-                ),
679
-                $this->page_slug,
680
-                $this->_req_action,
681
-                get_class($this)
682
-            );
683
-            throw new EE_Error($msg);
684
-        }
685
-        $this->_set_model_object($this->request->getRequestParam('post'));
686
-    }
687
-
688
-
689
-    /**
690
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
691
-     *
692
-     * @param int    $id       The id to retrieve the model object for. If empty we set a default object.
693
-     * @param bool   $ignore_route_check
694
-     * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
695
-     * @throws EE_Error
696
-     * @throws InvalidArgumentException
697
-     * @throws InvalidDataTypeException
698
-     * @throws InvalidInterfaceException
699
-     * @throws ReflectionException
700
-     */
701
-    protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
702
-    {
703
-        $model = null;
704
-        if (
705
-            empty($this->_cpt_model_names)
706
-            || (
707
-                ! $ignore_route_check
708
-                && ! isset($this->_cpt_routes[ $this->_req_action ])
709
-            )
710
-            || (
711
-                $this->_cpt_model_obj instanceof EE_CPT_Base
712
-                && $this->_cpt_model_obj->ID() === $id
713
-            )
714
-        ) {
715
-            // get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
716
-            return;
717
-        }
718
-        // if ignore_route_check is true, then get the model name via CustomPostTypeDefinitions
719
-        if ($ignore_route_check) {
720
-            $post_type = get_post_type($id);
721
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
722
-            $custom_post_types = $this->loader->getShared(
723
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
724
-            );
725
-            $model_names       = $custom_post_types->getCustomPostTypeModelNames($post_type);
726
-            if (isset($model_names[ $post_type ])) {
727
-                $model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
728
-            }
729
-        } else {
730
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
731
-        }
732
-        if ($model instanceof EEM_Base) {
733
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
734
-        }
735
-        do_action(
736
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
737
-            $this->_cpt_model_obj,
738
-            $req_type
739
-        );
740
-    }
741
-
742
-
743
-    /**
744
-     * admin_init_global
745
-     * This runs all the code that we want executed within the WP admin_init hook.
746
-     * This method executes for ALL EE Admin pages.
747
-     *
748
-     * @return void
749
-     */
750
-    public function admin_init_global()
751
-    {
752
-        $post = $this->request->getRequestParam('post');
753
-        // its possible this is a new save so let's catch that instead
754
-        $post           = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
755
-        $post_type      = $post instanceof WP_Post ? $post->post_type : false;
756
-        $current_route  = isset($this->_req_data['current_route'])
757
-            ? $this->_req_data['current_route']
758
-            : 'shouldneverwork';
759
-        $route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
760
-            ? $this->_cpt_routes[ $current_route ]
761
-            : '';
762
-        add_filter('get_delete_post_link', [$this, 'modify_delete_post_link'], 10, 3);
763
-        add_filter('get_edit_post_link', [$this, 'modify_edit_post_link'], 10, 3);
764
-        if ($post_type === $route_to_check) {
765
-            add_filter('redirect_post_location', [$this, 'cpt_post_location_redirect'], 10, 2);
766
-        }
767
-        // now let's filter redirect if we're on a revision page and the revision is for an event CPT.
768
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
769
-        if (! empty($revision)) {
770
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
771
-            // doing a restore?
772
-            if (! empty($action) && $action === 'restore') {
773
-                // get post for revision
774
-                $rev_post   = get_post($revision);
775
-                $rev_parent = get_post($rev_post->post_parent);
776
-                // only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
777
-                if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
778
-                    add_filter('wp_redirect', [$this, 'revision_redirect'], 10, 2);
779
-                    // restores of revisions
780
-                    add_action('wp_restore_post_revision', [$this, 'restore_revision'], 10, 2);
781
-                }
782
-            }
783
-        }
784
-        // NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
785
-        if ($post_type && $post_type === $route_to_check) {
786
-            // $post_id, $post
787
-            add_action('save_post', [$this, 'insert_update'], 10, 3);
788
-            // $post_id
789
-            add_action('trashed_post', [$this, 'before_trash_cpt_item'], 10);
790
-            add_action('trashed_post', [$this, 'dont_permanently_delete_ee_cpts'], 10);
791
-            add_action('untrashed_post', [$this, 'before_restore_cpt_item'], 10);
792
-            add_action('after_delete_post', [$this, 'before_delete_cpt_item'], 10);
793
-        }
794
-    }
795
-
796
-
797
-    /**
798
-     * Callback for the WordPress trashed_post hook.
799
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
800
-     *
801
-     * @param int $post_id
802
-     * @throws EE_Error
803
-     * @throws ReflectionException
804
-     */
805
-    public function before_trash_cpt_item($post_id)
806
-    {
807
-        $this->_set_model_object($post_id, true, 'trash');
808
-        // if our cpt object isn't existent then get out immediately.
809
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
810
-            return;
811
-        }
812
-        $this->trash_cpt_item($post_id);
813
-    }
814
-
815
-
816
-    /**
817
-     * Callback for the WordPress untrashed_post hook.
818
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
819
-     *
820
-     * @param $post_id
821
-     * @throws EE_Error
822
-     * @throws ReflectionException
823
-     */
824
-    public function before_restore_cpt_item($post_id)
825
-    {
826
-        $this->_set_model_object($post_id, true, 'restore');
827
-        // if our cpt object isn't existent then get out immediately.
828
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
829
-            return;
830
-        }
831
-        $this->restore_cpt_item($post_id);
832
-    }
833
-
834
-
835
-    /**
836
-     * Callback for the WordPress after_delete_post hook.
837
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
838
-     *
839
-     * @param $post_id
840
-     * @throws EE_Error
841
-     * @throws ReflectionException
842
-     */
843
-    public function before_delete_cpt_item($post_id)
844
-    {
845
-        $this->_set_model_object($post_id, true, 'delete');
846
-        // if our cpt object isn't existent then get out immediately.
847
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
848
-            return;
849
-        }
850
-        $this->delete_cpt_item($post_id);
851
-    }
852
-
853
-
854
-    /**
855
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
856
-     * accordingly.
857
-     *
858
-     * @return void
859
-     * @throws EE_Error
860
-     * @throws ReflectionException
861
-     */
862
-    public function verify_cpt_object()
863
-    {
864
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
865
-        // verify event object
866
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
867
-            throw new EE_Error(
868
-                sprintf(
869
-                    esc_html__(
870
-                        'Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
871
-                        'event_espresso'
872
-                    ),
873
-                    $label
874
-                )
875
-            );
876
-        }
877
-        // if auto-draft then throw an error
878
-        if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
879
-            EE_Error::overwrite_errors();
880
-            EE_Error::add_error(
881
-                sprintf(
882
-                    esc_html__(
883
-                        'This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.',
884
-                        'event_espresso'
885
-                    ),
886
-                    $label
887
-                ),
888
-                __FILE__,
889
-                __FUNCTION__,
890
-                __LINE__
891
-            );
892
-        }
893
-    }
894
-
895
-
896
-    /**
897
-     * admin_footer_scripts_global
898
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
899
-     * will apply on ALL EE_Admin pages.
900
-     *
901
-     * @return void
902
-     */
903
-    public function admin_footer_scripts_global()
904
-    {
905
-        $this->_add_admin_page_ajax_loading_img();
906
-        $this->_add_admin_page_overlay();
907
-    }
908
-
909
-
910
-    /**
911
-     * add in any global scripts for cpt routes
912
-     *
913
-     * @return void
914
-     * @throws EE_Error
915
-     */
916
-    public function load_global_scripts_styles()
917
-    {
918
-        parent::load_global_scripts_styles();
919
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
920
-            // setup custom post status object for localize script but only if we've got a cpt object
921
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
922
-            if (! empty($statuses)) {
923
-                // get ALL statuses!
924
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
925
-                // setup object
926
-                $ee_cpt_statuses = [];
927
-                foreach ($statuses as $status => $label) {
928
-                    $ee_cpt_statuses[ $status ] = [
929
-                        'label'      => $label,
930
-                        'save_label' => sprintf(
931
-                            wp_strip_all_tags(__('Save as %s', 'event_espresso')),
932
-                            $label
933
-                        ),
934
-                    ];
935
-                }
936
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
937
-            }
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
944
-     * insert/updates
945
-     *
946
-     * @param int     $post_id ID of post being updated
947
-     * @param WP_Post $post    Post object from WP
948
-     * @param bool    $update  Whether this is an update or a new save.
949
-     * @return void
950
-     * @throws EE_Error
951
-     * @throws ReflectionException
952
-     */
953
-    public function insert_update($post_id, $post, $update)
954
-    {
955
-        // make sure that if this is a revision OR trash action that we don't do any updates!
956
-        if (
957
-            isset($this->_req_data['action'])
958
-            && (
959
-                $this->_req_data['action'] === 'restore'
960
-                || $this->_req_data['action'] === 'trash'
961
-            )
962
-        ) {
963
-            return;
964
-        }
965
-        $this->_set_model_object($post_id, true, 'insert_update');
966
-        // if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
967
-        if (
968
-            $update
969
-            && (
970
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
971
-                || $this->_cpt_model_obj->ID() !== $post_id
972
-            )
973
-        ) {
974
-            return;
975
-        }
976
-        // check for autosave and update our req_data property accordingly.
977
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
533
+		}
534
+		return $return;
535
+	}
536
+
537
+
538
+	/**
539
+	 * add our custom post status dropdown on the wp post page for this cpt
540
+	 *
541
+	 * @return void
542
+	 */
543
+	public function custom_post_stati_dropdown()
544
+	{
545
+
546
+		$statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
547
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
548
+			? $statuses[ $this->_cpt_model_obj->status() ]
549
+			: '';
550
+		$template_args    = [
551
+			'cur_status'            => $this->_cpt_model_obj->status(),
552
+			'statuses'              => $statuses,
553
+			'cur_status_label'      => $cur_status_label,
554
+			'localized_status_save' => sprintf(esc_html__('Save %s', 'event_espresso'), $cur_status_label),
555
+		];
556
+		// we'll add a trash post status (WP doesn't add one for some reason)
557
+		if ($this->_cpt_model_obj->status() === 'trash') {
558
+			$template_args['cur_status_label'] = esc_html__('Trashed', 'event_espresso');
559
+			$statuses['trash']                 = esc_html__('Trashed', 'event_espresso');
560
+			$template_args['statuses']         = $statuses;
561
+		}
562
+
563
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
564
+		EEH_Template::display_template($template, $template_args);
565
+	}
566
+
567
+
568
+	public function setup_autosave_hooks()
569
+	{
570
+		$this->_set_autosave_containers();
571
+		$this->_load_autosave_scripts_styles();
572
+	}
573
+
574
+
575
+	/**
576
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a post object (available
577
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
578
+	 * for the nonce in here, but then this method looks for two things:
579
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
580
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
581
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
582
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
583
+	 * template args.
584
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
585
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
586
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
587
+	 *    $this->_template_args['data']['items'] = array(
588
+	 *        'event-datetime-ids' => '1,2,3';
589
+	 *    );
590
+	 *    Keep in mind the following things:
591
+	 *    - "where" index is for the input with the id as that string.
592
+	 *    - "what" index is what will be used for the value of that input.
593
+	 *
594
+	 * @return void
595
+	 * @throws EE_Error
596
+	 */
597
+	public function do_extra_autosave_stuff()
598
+	{
599
+		// next let's check for the autosave nonce (we'll use _verify_nonce )
600
+		$nonce = $this->request->getRequestParam('autosavenonce');
601
+		$this->_verify_nonce($nonce, 'autosave');
602
+		// make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
603
+		if (! defined('DOING_AUTOSAVE')) {
604
+			define('DOING_AUTOSAVE', true);
605
+		}
606
+		// if we made it here then the nonce checked out.  Let's run our methods and actions
607
+		$autosave = "_ee_autosave_{$this->_current_view}";
608
+		if (method_exists($this, $autosave)) {
609
+			$this->$autosave();
610
+		} else {
611
+			$this->_template_args['success'] = true;
612
+		}
613
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
614
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
615
+		// now let's return json
616
+		$this->_return_json();
617
+	}
618
+
619
+
620
+	/**
621
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
622
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
623
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
624
+	 *
625
+	 * @return void
626
+	 * @throws EE_Error
627
+	 * @throws ReflectionException
628
+	 */
629
+	protected function _extend_page_config_for_cpt()
630
+	{
631
+		// before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
632
+		if ($this->raw_req_page !== $this->page_slug) {
633
+			return;
634
+		}
635
+		// set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
636
+		if (! empty($this->_cpt_object)) {
637
+			$this->_page_routes = array_merge(
638
+				[
639
+					'create_new' => '_create_new_cpt_item',
640
+					'edit'       => '_edit_cpt_item',
641
+				],
642
+				$this->_page_routes
643
+			);
644
+			$this->_page_config = array_merge(
645
+				[
646
+					'create_new' => [
647
+						'nav'           => [
648
+							'label' => $this->_cpt_object->labels->add_new_item,
649
+							'order' => 5,
650
+						],
651
+						'require_nonce' => false,
652
+					],
653
+					'edit'       => [
654
+						'nav'           => [
655
+							'label'      => $this->_cpt_object->labels->edit_item,
656
+							'order'      => 5,
657
+							'persistent' => false,
658
+							'url'        => '',
659
+						],
660
+						'require_nonce' => false,
661
+					],
662
+				],
663
+				$this->_page_config
664
+			);
665
+		}
666
+		// load the next section only if this is a matching cpt route as set in the cpt routes array.
667
+		if (! isset($this->_cpt_routes[ $this->_req_action ])) {
668
+			return;
669
+		}
670
+		$this->_cpt_route = true;
671
+		// $this->_cpt_route = isset($this->_cpt_routes[ $this->_req_action ]);
672
+		// add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
673
+		if (empty($this->_cpt_object)) {
674
+			$msg = sprintf(
675
+				esc_html__(
676
+					'This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).',
677
+					'event_espresso'
678
+				),
679
+				$this->page_slug,
680
+				$this->_req_action,
681
+				get_class($this)
682
+			);
683
+			throw new EE_Error($msg);
684
+		}
685
+		$this->_set_model_object($this->request->getRequestParam('post'));
686
+	}
687
+
688
+
689
+	/**
690
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
691
+	 *
692
+	 * @param int    $id       The id to retrieve the model object for. If empty we set a default object.
693
+	 * @param bool   $ignore_route_check
694
+	 * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
695
+	 * @throws EE_Error
696
+	 * @throws InvalidArgumentException
697
+	 * @throws InvalidDataTypeException
698
+	 * @throws InvalidInterfaceException
699
+	 * @throws ReflectionException
700
+	 */
701
+	protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
702
+	{
703
+		$model = null;
704
+		if (
705
+			empty($this->_cpt_model_names)
706
+			|| (
707
+				! $ignore_route_check
708
+				&& ! isset($this->_cpt_routes[ $this->_req_action ])
709
+			)
710
+			|| (
711
+				$this->_cpt_model_obj instanceof EE_CPT_Base
712
+				&& $this->_cpt_model_obj->ID() === $id
713
+			)
714
+		) {
715
+			// get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
716
+			return;
717
+		}
718
+		// if ignore_route_check is true, then get the model name via CustomPostTypeDefinitions
719
+		if ($ignore_route_check) {
720
+			$post_type = get_post_type($id);
721
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
722
+			$custom_post_types = $this->loader->getShared(
723
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
724
+			);
725
+			$model_names       = $custom_post_types->getCustomPostTypeModelNames($post_type);
726
+			if (isset($model_names[ $post_type ])) {
727
+				$model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
728
+			}
729
+		} else {
730
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
731
+		}
732
+		if ($model instanceof EEM_Base) {
733
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
734
+		}
735
+		do_action(
736
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
737
+			$this->_cpt_model_obj,
738
+			$req_type
739
+		);
740
+	}
741
+
742
+
743
+	/**
744
+	 * admin_init_global
745
+	 * This runs all the code that we want executed within the WP admin_init hook.
746
+	 * This method executes for ALL EE Admin pages.
747
+	 *
748
+	 * @return void
749
+	 */
750
+	public function admin_init_global()
751
+	{
752
+		$post = $this->request->getRequestParam('post');
753
+		// its possible this is a new save so let's catch that instead
754
+		$post           = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
755
+		$post_type      = $post instanceof WP_Post ? $post->post_type : false;
756
+		$current_route  = isset($this->_req_data['current_route'])
757
+			? $this->_req_data['current_route']
758
+			: 'shouldneverwork';
759
+		$route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
760
+			? $this->_cpt_routes[ $current_route ]
761
+			: '';
762
+		add_filter('get_delete_post_link', [$this, 'modify_delete_post_link'], 10, 3);
763
+		add_filter('get_edit_post_link', [$this, 'modify_edit_post_link'], 10, 3);
764
+		if ($post_type === $route_to_check) {
765
+			add_filter('redirect_post_location', [$this, 'cpt_post_location_redirect'], 10, 2);
766
+		}
767
+		// now let's filter redirect if we're on a revision page and the revision is for an event CPT.
768
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
769
+		if (! empty($revision)) {
770
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
771
+			// doing a restore?
772
+			if (! empty($action) && $action === 'restore') {
773
+				// get post for revision
774
+				$rev_post   = get_post($revision);
775
+				$rev_parent = get_post($rev_post->post_parent);
776
+				// only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
777
+				if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
778
+					add_filter('wp_redirect', [$this, 'revision_redirect'], 10, 2);
779
+					// restores of revisions
780
+					add_action('wp_restore_post_revision', [$this, 'restore_revision'], 10, 2);
781
+				}
782
+			}
783
+		}
784
+		// NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
785
+		if ($post_type && $post_type === $route_to_check) {
786
+			// $post_id, $post
787
+			add_action('save_post', [$this, 'insert_update'], 10, 3);
788
+			// $post_id
789
+			add_action('trashed_post', [$this, 'before_trash_cpt_item'], 10);
790
+			add_action('trashed_post', [$this, 'dont_permanently_delete_ee_cpts'], 10);
791
+			add_action('untrashed_post', [$this, 'before_restore_cpt_item'], 10);
792
+			add_action('after_delete_post', [$this, 'before_delete_cpt_item'], 10);
793
+		}
794
+	}
795
+
796
+
797
+	/**
798
+	 * Callback for the WordPress trashed_post hook.
799
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
800
+	 *
801
+	 * @param int $post_id
802
+	 * @throws EE_Error
803
+	 * @throws ReflectionException
804
+	 */
805
+	public function before_trash_cpt_item($post_id)
806
+	{
807
+		$this->_set_model_object($post_id, true, 'trash');
808
+		// if our cpt object isn't existent then get out immediately.
809
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
810
+			return;
811
+		}
812
+		$this->trash_cpt_item($post_id);
813
+	}
814
+
815
+
816
+	/**
817
+	 * Callback for the WordPress untrashed_post hook.
818
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
819
+	 *
820
+	 * @param $post_id
821
+	 * @throws EE_Error
822
+	 * @throws ReflectionException
823
+	 */
824
+	public function before_restore_cpt_item($post_id)
825
+	{
826
+		$this->_set_model_object($post_id, true, 'restore');
827
+		// if our cpt object isn't existent then get out immediately.
828
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
829
+			return;
830
+		}
831
+		$this->restore_cpt_item($post_id);
832
+	}
833
+
834
+
835
+	/**
836
+	 * Callback for the WordPress after_delete_post hook.
837
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
838
+	 *
839
+	 * @param $post_id
840
+	 * @throws EE_Error
841
+	 * @throws ReflectionException
842
+	 */
843
+	public function before_delete_cpt_item($post_id)
844
+	{
845
+		$this->_set_model_object($post_id, true, 'delete');
846
+		// if our cpt object isn't existent then get out immediately.
847
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
848
+			return;
849
+		}
850
+		$this->delete_cpt_item($post_id);
851
+	}
852
+
853
+
854
+	/**
855
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
856
+	 * accordingly.
857
+	 *
858
+	 * @return void
859
+	 * @throws EE_Error
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function verify_cpt_object()
863
+	{
864
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
865
+		// verify event object
866
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
867
+			throw new EE_Error(
868
+				sprintf(
869
+					esc_html__(
870
+						'Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
871
+						'event_espresso'
872
+					),
873
+					$label
874
+				)
875
+			);
876
+		}
877
+		// if auto-draft then throw an error
878
+		if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
879
+			EE_Error::overwrite_errors();
880
+			EE_Error::add_error(
881
+				sprintf(
882
+					esc_html__(
883
+						'This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.',
884
+						'event_espresso'
885
+					),
886
+					$label
887
+				),
888
+				__FILE__,
889
+				__FUNCTION__,
890
+				__LINE__
891
+			);
892
+		}
893
+	}
894
+
895
+
896
+	/**
897
+	 * admin_footer_scripts_global
898
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
899
+	 * will apply on ALL EE_Admin pages.
900
+	 *
901
+	 * @return void
902
+	 */
903
+	public function admin_footer_scripts_global()
904
+	{
905
+		$this->_add_admin_page_ajax_loading_img();
906
+		$this->_add_admin_page_overlay();
907
+	}
908
+
909
+
910
+	/**
911
+	 * add in any global scripts for cpt routes
912
+	 *
913
+	 * @return void
914
+	 * @throws EE_Error
915
+	 */
916
+	public function load_global_scripts_styles()
917
+	{
918
+		parent::load_global_scripts_styles();
919
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
920
+			// setup custom post status object for localize script but only if we've got a cpt object
921
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
922
+			if (! empty($statuses)) {
923
+				// get ALL statuses!
924
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
925
+				// setup object
926
+				$ee_cpt_statuses = [];
927
+				foreach ($statuses as $status => $label) {
928
+					$ee_cpt_statuses[ $status ] = [
929
+						'label'      => $label,
930
+						'save_label' => sprintf(
931
+							wp_strip_all_tags(__('Save as %s', 'event_espresso')),
932
+							$label
933
+						),
934
+					];
935
+				}
936
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
937
+			}
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
944
+	 * insert/updates
945
+	 *
946
+	 * @param int     $post_id ID of post being updated
947
+	 * @param WP_Post $post    Post object from WP
948
+	 * @param bool    $update  Whether this is an update or a new save.
949
+	 * @return void
950
+	 * @throws EE_Error
951
+	 * @throws ReflectionException
952
+	 */
953
+	public function insert_update($post_id, $post, $update)
954
+	{
955
+		// make sure that if this is a revision OR trash action that we don't do any updates!
956
+		if (
957
+			isset($this->_req_data['action'])
958
+			&& (
959
+				$this->_req_data['action'] === 'restore'
960
+				|| $this->_req_data['action'] === 'trash'
961
+			)
962
+		) {
963
+			return;
964
+		}
965
+		$this->_set_model_object($post_id, true, 'insert_update');
966
+		// if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
967
+		if (
968
+			$update
969
+			&& (
970
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
971
+				|| $this->_cpt_model_obj->ID() !== $post_id
972
+			)
973
+		) {
974
+			return;
975
+		}
976
+		// check for autosave and update our req_data property accordingly.
977
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
978 978
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
979 979
 
980 980
                 foreach ( (array) $values as $key => $value ) {
@@ -984,539 +984,539 @@  discard block
 block discarded – undo
984 984
 
985 985
         }/**/ // TODO reactivate after autosave is implemented in 4.2
986 986
 
987
-        // take care of updating any selected page_template IF this cpt supports it.
988
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
989
-            // wp version aware.
990
-            if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
991
-                $page_templates = wp_get_theme()->get_page_templates();
992
-            } else {
993
-                $post->page_template = $this->_req_data['page_template'];
994
-                $page_templates      = wp_get_theme()->get_page_templates($post);
995
-            }
996
-            if (
997
-                'default' != $this->_req_data['page_template']
998
-                && ! isset($page_templates[ $this->_req_data['page_template'] ])
999
-            ) {
1000
-                EE_Error::add_error(
1001
-                    esc_html__('Invalid Page Template.', 'event_espresso'),
1002
-                    __FILE__,
1003
-                    __FUNCTION__,
1004
-                    __LINE__
1005
-                );
1006
-            } else {
1007
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
1008
-            }
1009
-        }
1010
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
1011
-            return;
1012
-        } //TODO we'll remove this after reimplementing autosave in 4.2
1013
-        $this->_insert_update_cpt_item($post_id, $post);
1014
-    }
1015
-
1016
-
1017
-    /**
1018
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
1019
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
1020
-     * so we don't have to check for our CPT.
1021
-     *
1022
-     * @param int $post_id ID of the post
1023
-     * @return void
1024
-     */
1025
-    public function dont_permanently_delete_ee_cpts($post_id)
1026
-    {
1027
-        // only do this if we're actually processing one of our CPTs
1028
-        // if our cpt object isn't existent then get out immediately.
1029
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1030
-            return;
1031
-        }
1032
-        delete_post_meta($post_id, '_wp_trash_meta_status');
1033
-        delete_post_meta($post_id, '_wp_trash_meta_time');
1034
-        // our cpts may have comments so let's take care of that too
1035
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
1041
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1042
-     * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1043
-     *
1044
-     * @param int $post_id     ID of cpt item
1045
-     * @param int $revision_id ID of revision being restored
1046
-     * @return void
1047
-     */
1048
-    public function restore_revision($post_id, $revision_id)
1049
-    {
1050
-        $this->_restore_cpt_item($post_id, $revision_id);
1051
-        // global action
1052
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1053
-        // class specific action so you can limit hooking into a specific page.
1054
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * @param int $post_id     ID of cpt item
1060
-     * @param int $revision_id ID of revision for item
1061
-     * @return void
1062
-     * @see restore_revision() for details
1063
-     */
1064
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
1065
-
1066
-
1067
-    /**
1068
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
1069
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1070
-     * To fix we have to reset the current_screen using the page_slug
1071
-     * (which is identical - or should be - to our registered_post_type id.)
1072
-     * Also, since the core WP file loads the admin_header.php for WP
1073
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1074
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1075
-     *
1076
-     * @return void
1077
-     * @throws EE_Error
1078
-     */
1079
-    public function modify_current_screen()
1080
-    {
1081
-        // ONLY do this if the current page_route IS a cpt route
1082
-        if (! $this->_cpt_route) {
1083
-            return;
1084
-        }
1085
-        // routing things REALLY early b/c this is a cpt admin page
1086
-        set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1087
-        $this->_current_screen       = get_current_screen();
1088
-        $this->_current_screen->base = 'event-espresso';
1089
-        $this->_add_help_tabs(); // we make sure we add any help tabs back in!
1090
-        /*try {
987
+		// take care of updating any selected page_template IF this cpt supports it.
988
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
989
+			// wp version aware.
990
+			if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
991
+				$page_templates = wp_get_theme()->get_page_templates();
992
+			} else {
993
+				$post->page_template = $this->_req_data['page_template'];
994
+				$page_templates      = wp_get_theme()->get_page_templates($post);
995
+			}
996
+			if (
997
+				'default' != $this->_req_data['page_template']
998
+				&& ! isset($page_templates[ $this->_req_data['page_template'] ])
999
+			) {
1000
+				EE_Error::add_error(
1001
+					esc_html__('Invalid Page Template.', 'event_espresso'),
1002
+					__FILE__,
1003
+					__FUNCTION__,
1004
+					__LINE__
1005
+				);
1006
+			} else {
1007
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
1008
+			}
1009
+		}
1010
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
1011
+			return;
1012
+		} //TODO we'll remove this after reimplementing autosave in 4.2
1013
+		$this->_insert_update_cpt_item($post_id, $post);
1014
+	}
1015
+
1016
+
1017
+	/**
1018
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
1019
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
1020
+	 * so we don't have to check for our CPT.
1021
+	 *
1022
+	 * @param int $post_id ID of the post
1023
+	 * @return void
1024
+	 */
1025
+	public function dont_permanently_delete_ee_cpts($post_id)
1026
+	{
1027
+		// only do this if we're actually processing one of our CPTs
1028
+		// if our cpt object isn't existent then get out immediately.
1029
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1030
+			return;
1031
+		}
1032
+		delete_post_meta($post_id, '_wp_trash_meta_status');
1033
+		delete_post_meta($post_id, '_wp_trash_meta_time');
1034
+		// our cpts may have comments so let's take care of that too
1035
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
1041
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1042
+	 * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1043
+	 *
1044
+	 * @param int $post_id     ID of cpt item
1045
+	 * @param int $revision_id ID of revision being restored
1046
+	 * @return void
1047
+	 */
1048
+	public function restore_revision($post_id, $revision_id)
1049
+	{
1050
+		$this->_restore_cpt_item($post_id, $revision_id);
1051
+		// global action
1052
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1053
+		// class specific action so you can limit hooking into a specific page.
1054
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * @param int $post_id     ID of cpt item
1060
+	 * @param int $revision_id ID of revision for item
1061
+	 * @return void
1062
+	 * @see restore_revision() for details
1063
+	 */
1064
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
1065
+
1066
+
1067
+	/**
1068
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
1069
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1070
+	 * To fix we have to reset the current_screen using the page_slug
1071
+	 * (which is identical - or should be - to our registered_post_type id.)
1072
+	 * Also, since the core WP file loads the admin_header.php for WP
1073
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1074
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1075
+	 *
1076
+	 * @return void
1077
+	 * @throws EE_Error
1078
+	 */
1079
+	public function modify_current_screen()
1080
+	{
1081
+		// ONLY do this if the current page_route IS a cpt route
1082
+		if (! $this->_cpt_route) {
1083
+			return;
1084
+		}
1085
+		// routing things REALLY early b/c this is a cpt admin page
1086
+		set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1087
+		$this->_current_screen       = get_current_screen();
1088
+		$this->_current_screen->base = 'event-espresso';
1089
+		$this->_add_help_tabs(); // we make sure we add any help tabs back in!
1090
+		/*try {
1091 1091
             $this->_route_admin_request();
1092 1092
         } catch ( EE_Error $e ) {
1093 1093
             $e->get_error();
1094 1094
         }/**/
1095
-    }
1096
-
1097
-
1098
-    /**
1099
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1100
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1101
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1102
-     * default to be.
1103
-     *
1104
-     * @param string $title The new title (or existing if there is no editor_title defined)
1105
-     * @return string
1106
-     */
1107
-    public function add_custom_editor_default_title($title)
1108
-    {
1109
-        return $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ] ?? $title;
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1115
-     *
1116
-     * @param string $shortlink   The already generated shortlink
1117
-     * @param int    $id          Post ID for this item
1118
-     * @param string $context     The context for the link
1119
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1120
-     * @return string
1121
-     */
1122
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1123
-    {
1124
-        if (! empty($id) && get_option('permalink_structure') !== '') {
1125
-            $post = get_post($id);
1126
-            if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1127
-                $shortlink = home_url('?p=' . $post->ID);
1128
-            }
1129
-        }
1130
-        return $shortlink;
1131
-    }
1132
-
1133
-
1134
-    /**
1135
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1136
-     * already run in modify_current_screen())
1137
-     *
1138
-     * @return void
1139
-     * @throws EE_Error
1140
-     * @throws ReflectionException
1141
-     */
1142
-    public function route_admin_request()
1143
-    {
1144
-        if ($this->_cpt_route) {
1145
-            return;
1146
-        }
1147
-        try {
1148
-            $this->_route_admin_request();
1149
-        } catch (EE_Error $e) {
1150
-            $e->get_error();
1151
-        }
1152
-    }
1153
-
1154
-
1155
-    /**
1156
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1157
-     *
1158
-     * @return void
1159
-     */
1160
-    public function cpt_post_form_hidden_input()
1161
-    {
1162
-        // we're also going to add the route value and the current page so we can direct autosave parsing correctly
1163
-        echo '
1095
+	}
1096
+
1097
+
1098
+	/**
1099
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1100
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1101
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1102
+	 * default to be.
1103
+	 *
1104
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1105
+	 * @return string
1106
+	 */
1107
+	public function add_custom_editor_default_title($title)
1108
+	{
1109
+		return $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ] ?? $title;
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1115
+	 *
1116
+	 * @param string $shortlink   The already generated shortlink
1117
+	 * @param int    $id          Post ID for this item
1118
+	 * @param string $context     The context for the link
1119
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1120
+	 * @return string
1121
+	 */
1122
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1123
+	{
1124
+		if (! empty($id) && get_option('permalink_structure') !== '') {
1125
+			$post = get_post($id);
1126
+			if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1127
+				$shortlink = home_url('?p=' . $post->ID);
1128
+			}
1129
+		}
1130
+		return $shortlink;
1131
+	}
1132
+
1133
+
1134
+	/**
1135
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1136
+	 * already run in modify_current_screen())
1137
+	 *
1138
+	 * @return void
1139
+	 * @throws EE_Error
1140
+	 * @throws ReflectionException
1141
+	 */
1142
+	public function route_admin_request()
1143
+	{
1144
+		if ($this->_cpt_route) {
1145
+			return;
1146
+		}
1147
+		try {
1148
+			$this->_route_admin_request();
1149
+		} catch (EE_Error $e) {
1150
+			$e->get_error();
1151
+		}
1152
+	}
1153
+
1154
+
1155
+	/**
1156
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1157
+	 *
1158
+	 * @return void
1159
+	 */
1160
+	public function cpt_post_form_hidden_input()
1161
+	{
1162
+		// we're also going to add the route value and the current page so we can direct autosave parsing correctly
1163
+		echo '
1164 1164
         <input type="hidden" name="ee_cpt_item_redirect_url" value="' . esc_url_raw($this->_admin_base_url) . '"/>
1165 1165
         <div id="ee-cpt-hidden-inputs">
1166 1166
             <input type="hidden" id="current_route" name="current_route" value="' . esc_attr($this->_current_view) . '"/>
1167 1167
             <input type="hidden" id="current_page" name="current_page" value="' . esc_attr($this->page_slug) . '"/>
1168 1168
         </div>';
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1174
-     *
1175
-     * @param string $location Original location url
1176
-     * @param int    $status   Status for http header
1177
-     * @return string           new (or original) url to redirect to.
1178
-     * @throws EE_Error
1179
-     */
1180
-    public function revision_redirect($location, $status)
1181
-    {
1182
-        // get revision
1183
-        $rev_id = $this->_req_data['revision'] ?? null;
1184
-        // can't do anything without revision so let's get out if not present
1185
-        if (empty($rev_id)) {
1186
-            return $location;
1187
-        }
1188
-        // get rev_post_data
1189
-        $rev        = get_post($rev_id);
1190
-        $admin_url  = $this->_admin_base_url;
1191
-        $query_args = [
1192
-            'action'   => 'edit',
1193
-            'post'     => $rev->post_parent,
1194
-            'revision' => $rev_id,
1195
-            'message'  => 5,
1196
-        ];
1197
-        $this->_process_notices($query_args, true);
1198
-        return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $admin_url);
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1204
-     *
1205
-     * @param string $link    the original generated link
1206
-     * @param int    $id      post id
1207
-     * @param string $context optional, defaults to display.  How to write the '&'
1208
-     * @return string          the link
1209
-     */
1210
-    public function modify_edit_post_link($link, $id, $context)
1211
-    {
1212
-        $post = get_post($id);
1213
-        if (
1214
-            ! isset($this->_req_data['action'])
1215
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1216
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1217
-        ) {
1218
-            return $link;
1219
-        }
1220
-        $query_args = [
1221
-            'action' => $this->_cpt_edit_routes[ $post->post_type ] ?? 'edit',
1222
-            'post'   => $id,
1223
-        ];
1224
-        return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1230
-     * our routes.
1231
-     *
1232
-     * @param string $delete_link  original delete link
1233
-     * @param int    $post_id      id of cpt object
1234
-     * @param bool   $force_delete whether this is forcing a hard delete instead of trash
1235
-     * @return string new delete link
1236
-     * @throws EE_Error
1237
-     * @throws ReflectionException
1238
-     */
1239
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1240
-    {
1241
-        $post = get_post($post_id);
1242
-
1243
-        if (
1244
-            empty($this->_req_data['action'])
1245
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1246
-            || ! $post instanceof WP_Post
1247
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1248
-        ) {
1249
-            return $delete_link;
1250
-        }
1251
-        $this->_set_model_object($post->ID, true);
1252
-
1253
-        // returns something like `trash_event` or `trash_attendee` or `trash_venue`
1254
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1255
-
1256
-        return EE_Admin_Page::add_query_args_and_nonce(
1257
-            [
1258
-                'page'   => $this->_req_data['page'],
1259
-                'action' => $action,
1260
-                $this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1261
-                         => $post->ID,
1262
-            ],
1263
-            admin_url()
1264
-        );
1265
-    }
1266
-
1267
-
1268
-    /**
1269
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1270
-     * so that we can hijack the default redirect locations for wp custom post types
1271
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1272
-     *
1273
-     * @param string $location This is the incoming currently set redirect location
1274
-     * @param string $post_id  This is the 'ID' value of the wp_posts table
1275
-     * @return string           the new location to redirect to
1276
-     * @throws EE_Error
1277
-     */
1278
-    public function cpt_post_location_redirect($location, $post_id)
1279
-    {
1280
-        // we DO have a match so let's setup the url
1281
-        // we have to get the post to determine our route
1282
-        $post       = get_post($post_id);
1283
-        $edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1284
-        // shared query_args
1285
-        $query_args = ['action' => $edit_route, 'post' => $post_id];
1286
-        $admin_url  = $this->_admin_base_url;
1287
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1288
-            $status = get_post_status($post_id);
1289
-            if (isset($this->_req_data['publish'])) {
1290
-                switch ($status) {
1291
-                    case 'pending':
1292
-                        $message = 8;
1293
-                        break;
1294
-                    case 'future':
1295
-                        $message = 9;
1296
-                        break;
1297
-                    default:
1298
-                        $message = 6;
1299
-                }
1300
-            } else {
1301
-                $message = 'draft' === $status ? 10 : 1;
1302
-            }
1303
-        } elseif (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1304
-            $message = 2;
1305
-        } elseif (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1306
-            $message = 3;
1307
-        } elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1308
-            $message = 7;
1309
-        } else {
1310
-            $message = 4;
1311
-        }
1312
-        // change the message if the post type is not viewable on the frontend
1313
-        $this->_cpt_object = get_post_type_object($post->post_type);
1314
-        $message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1315
-        $query_args        = array_merge(['message' => $message], $query_args);
1316
-        $this->_process_notices($query_args, true);
1317
-        return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $admin_url);
1318
-    }
1319
-
1320
-
1321
-    /**
1322
-     * This method is called to inject nav tabs on core WP cpt pages
1323
-     *
1324
-     * @return void
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function inject_nav_tabs()
1328
-    {
1329
-        echo wp_kses($this->_get_main_nav_tabs(), AllowedTags::getWithFormTags());
1330
-    }
1331
-
1332
-
1333
-    /**
1334
-     * This just sets up the post update messages when an update form is loaded
1335
-     *
1336
-     * @param array $messages the original messages array
1337
-     * @return array           the new messages array
1338
-     */
1339
-    public function post_update_messages($messages)
1340
-    {
1341
-        global $post;
1342
-        $id       = $this->request->getRequestParam('post');
1343
-        $id       = empty($id) && is_object($post) ? $post->ID : null;
1344
-        $revision = $this->request->getRequestParam('revision', 0, 'int');
1345
-
1346
-        $messages[ $post->post_type ] = [
1347
-            0  => '', // Unused. Messages start at index 1.
1348
-            1  => sprintf(
1349
-                esc_html__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1350
-                $this->_cpt_object->labels->singular_name,
1351
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1352
-                '</a>'
1353
-            ),
1354
-            2  => esc_html__('Custom field updated', 'event_espresso'),
1355
-            3  => esc_html__('Custom field deleted.', 'event_espresso'),
1356
-            4  => sprintf(esc_html__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1357
-            5  => $revision
1358
-                ? sprintf(
1359
-                    esc_html__('%s restored to revision from %s', 'event_espresso'),
1360
-                    $this->_cpt_object->labels->singular_name,
1361
-                    wp_post_revision_title($revision, false)
1362
-                )
1363
-                : false,
1364
-            6  => sprintf(
1365
-                esc_html__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1366
-                $this->_cpt_object->labels->singular_name,
1367
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1368
-                '</a>'
1369
-            ),
1370
-            7  => sprintf(esc_html__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1371
-            8  => sprintf(
1372
-                esc_html__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1373
-                $this->_cpt_object->labels->singular_name,
1374
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1375
-                '</a>'
1376
-            ),
1377
-            9  => sprintf(
1378
-                esc_html__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1379
-                $this->_cpt_object->labels->singular_name,
1380
-                '<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1381
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1382
-                '</a>'
1383
-            ),
1384
-            10 => sprintf(
1385
-                esc_html__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1386
-                $this->_cpt_object->labels->singular_name,
1387
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1388
-                '</a>'
1389
-            ),
1390
-        ];
1391
-        return $messages;
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * default method for the 'create_new' route for cpt admin pages.
1397
-     * For reference what to include in here, see wp-admin/post-new.php
1398
-     *
1399
-     * @return void
1400
-     */
1401
-    protected function _create_new_cpt_item()
1402
-    {
1403
-        // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1404
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1405
-        $post_type        = $this->_cpt_routes[ $this->_req_action ];
1406
-        $post_type_object = $this->_cpt_object;
1407
-        $title            = $post_type_object->labels->add_new_item;
1408
-        $post             = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1409
-        add_action('admin_print_styles', [$this, 'add_new_admin_page_global']);
1410
-        // modify the default editor title field with default title.
1411
-        add_filter('enter_title_here', [$this, 'add_custom_editor_default_title'], 10);
1412
-        $this->loadEditorTemplate(true);
1413
-    }
1414
-
1415
-
1416
-    /**
1417
-     * Enqueues auto-save and loads the editor template
1418
-     *
1419
-     * @param bool $creating
1420
-     */
1421
-    private function loadEditorTemplate($creating = true)
1422
-    {
1423
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1424
-        // these vars are used by the template
1425
-        $editing = true;
1426
-        $post_ID = $post->ID;
1427
-        if (apply_filters('FHEE__EE_Admin_Page_CPT___create_new_cpt_item__replace_editor', false, $post) === false) {
1428
-            // only enqueue autosave when creating event (necessary to get permalink/url generated)
1429
-            // otherwise EE doesn't support autosave fully, so to prevent user confusion we disable it in edit context.
1430
-            if ($creating) {
1431
-                wp_enqueue_script('autosave');
1432
-            } elseif (
1433
-                isset($this->_cpt_routes[ $this->_req_data['action'] ])
1434
-                && ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1435
-            ) {
1436
-                $create_new_action = apply_filters(
1437
-                    'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1438
-                    'create_new',
1439
-                    $this
1440
-                );
1441
-                $post_new_file = EE_Admin_Page::add_query_args_and_nonce(
1442
-                    array(
1443
-                        'action' => $create_new_action,
1444
-                        'page'   => $this->page_slug,
1445
-                    ),
1446
-                    'admin.php'
1447
-                );
1448
-            }
1449
-            include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1450
-        }
1451
-    }
1452
-
1453
-
1454
-    public function add_new_admin_page_global()
1455
-    {
1456
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1457
-        ?>
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1174
+	 *
1175
+	 * @param string $location Original location url
1176
+	 * @param int    $status   Status for http header
1177
+	 * @return string           new (or original) url to redirect to.
1178
+	 * @throws EE_Error
1179
+	 */
1180
+	public function revision_redirect($location, $status)
1181
+	{
1182
+		// get revision
1183
+		$rev_id = $this->_req_data['revision'] ?? null;
1184
+		// can't do anything without revision so let's get out if not present
1185
+		if (empty($rev_id)) {
1186
+			return $location;
1187
+		}
1188
+		// get rev_post_data
1189
+		$rev        = get_post($rev_id);
1190
+		$admin_url  = $this->_admin_base_url;
1191
+		$query_args = [
1192
+			'action'   => 'edit',
1193
+			'post'     => $rev->post_parent,
1194
+			'revision' => $rev_id,
1195
+			'message'  => 5,
1196
+		];
1197
+		$this->_process_notices($query_args, true);
1198
+		return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $admin_url);
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1204
+	 *
1205
+	 * @param string $link    the original generated link
1206
+	 * @param int    $id      post id
1207
+	 * @param string $context optional, defaults to display.  How to write the '&'
1208
+	 * @return string          the link
1209
+	 */
1210
+	public function modify_edit_post_link($link, $id, $context)
1211
+	{
1212
+		$post = get_post($id);
1213
+		if (
1214
+			! isset($this->_req_data['action'])
1215
+			|| ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1216
+			|| $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1217
+		) {
1218
+			return $link;
1219
+		}
1220
+		$query_args = [
1221
+			'action' => $this->_cpt_edit_routes[ $post->post_type ] ?? 'edit',
1222
+			'post'   => $id,
1223
+		];
1224
+		return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1230
+	 * our routes.
1231
+	 *
1232
+	 * @param string $delete_link  original delete link
1233
+	 * @param int    $post_id      id of cpt object
1234
+	 * @param bool   $force_delete whether this is forcing a hard delete instead of trash
1235
+	 * @return string new delete link
1236
+	 * @throws EE_Error
1237
+	 * @throws ReflectionException
1238
+	 */
1239
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1240
+	{
1241
+		$post = get_post($post_id);
1242
+
1243
+		if (
1244
+			empty($this->_req_data['action'])
1245
+			|| ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1246
+			|| ! $post instanceof WP_Post
1247
+			|| $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1248
+		) {
1249
+			return $delete_link;
1250
+		}
1251
+		$this->_set_model_object($post->ID, true);
1252
+
1253
+		// returns something like `trash_event` or `trash_attendee` or `trash_venue`
1254
+		$action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1255
+
1256
+		return EE_Admin_Page::add_query_args_and_nonce(
1257
+			[
1258
+				'page'   => $this->_req_data['page'],
1259
+				'action' => $action,
1260
+				$this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1261
+						 => $post->ID,
1262
+			],
1263
+			admin_url()
1264
+		);
1265
+	}
1266
+
1267
+
1268
+	/**
1269
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1270
+	 * so that we can hijack the default redirect locations for wp custom post types
1271
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1272
+	 *
1273
+	 * @param string $location This is the incoming currently set redirect location
1274
+	 * @param string $post_id  This is the 'ID' value of the wp_posts table
1275
+	 * @return string           the new location to redirect to
1276
+	 * @throws EE_Error
1277
+	 */
1278
+	public function cpt_post_location_redirect($location, $post_id)
1279
+	{
1280
+		// we DO have a match so let's setup the url
1281
+		// we have to get the post to determine our route
1282
+		$post       = get_post($post_id);
1283
+		$edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1284
+		// shared query_args
1285
+		$query_args = ['action' => $edit_route, 'post' => $post_id];
1286
+		$admin_url  = $this->_admin_base_url;
1287
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1288
+			$status = get_post_status($post_id);
1289
+			if (isset($this->_req_data['publish'])) {
1290
+				switch ($status) {
1291
+					case 'pending':
1292
+						$message = 8;
1293
+						break;
1294
+					case 'future':
1295
+						$message = 9;
1296
+						break;
1297
+					default:
1298
+						$message = 6;
1299
+				}
1300
+			} else {
1301
+				$message = 'draft' === $status ? 10 : 1;
1302
+			}
1303
+		} elseif (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1304
+			$message = 2;
1305
+		} elseif (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1306
+			$message = 3;
1307
+		} elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1308
+			$message = 7;
1309
+		} else {
1310
+			$message = 4;
1311
+		}
1312
+		// change the message if the post type is not viewable on the frontend
1313
+		$this->_cpt_object = get_post_type_object($post->post_type);
1314
+		$message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1315
+		$query_args        = array_merge(['message' => $message], $query_args);
1316
+		$this->_process_notices($query_args, true);
1317
+		return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $admin_url);
1318
+	}
1319
+
1320
+
1321
+	/**
1322
+	 * This method is called to inject nav tabs on core WP cpt pages
1323
+	 *
1324
+	 * @return void
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function inject_nav_tabs()
1328
+	{
1329
+		echo wp_kses($this->_get_main_nav_tabs(), AllowedTags::getWithFormTags());
1330
+	}
1331
+
1332
+
1333
+	/**
1334
+	 * This just sets up the post update messages when an update form is loaded
1335
+	 *
1336
+	 * @param array $messages the original messages array
1337
+	 * @return array           the new messages array
1338
+	 */
1339
+	public function post_update_messages($messages)
1340
+	{
1341
+		global $post;
1342
+		$id       = $this->request->getRequestParam('post');
1343
+		$id       = empty($id) && is_object($post) ? $post->ID : null;
1344
+		$revision = $this->request->getRequestParam('revision', 0, 'int');
1345
+
1346
+		$messages[ $post->post_type ] = [
1347
+			0  => '', // Unused. Messages start at index 1.
1348
+			1  => sprintf(
1349
+				esc_html__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1350
+				$this->_cpt_object->labels->singular_name,
1351
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1352
+				'</a>'
1353
+			),
1354
+			2  => esc_html__('Custom field updated', 'event_espresso'),
1355
+			3  => esc_html__('Custom field deleted.', 'event_espresso'),
1356
+			4  => sprintf(esc_html__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1357
+			5  => $revision
1358
+				? sprintf(
1359
+					esc_html__('%s restored to revision from %s', 'event_espresso'),
1360
+					$this->_cpt_object->labels->singular_name,
1361
+					wp_post_revision_title($revision, false)
1362
+				)
1363
+				: false,
1364
+			6  => sprintf(
1365
+				esc_html__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1366
+				$this->_cpt_object->labels->singular_name,
1367
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1368
+				'</a>'
1369
+			),
1370
+			7  => sprintf(esc_html__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1371
+			8  => sprintf(
1372
+				esc_html__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1373
+				$this->_cpt_object->labels->singular_name,
1374
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1375
+				'</a>'
1376
+			),
1377
+			9  => sprintf(
1378
+				esc_html__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1379
+				$this->_cpt_object->labels->singular_name,
1380
+				'<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1381
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1382
+				'</a>'
1383
+			),
1384
+			10 => sprintf(
1385
+				esc_html__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1386
+				$this->_cpt_object->labels->singular_name,
1387
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1388
+				'</a>'
1389
+			),
1390
+		];
1391
+		return $messages;
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * default method for the 'create_new' route for cpt admin pages.
1397
+	 * For reference what to include in here, see wp-admin/post-new.php
1398
+	 *
1399
+	 * @return void
1400
+	 */
1401
+	protected function _create_new_cpt_item()
1402
+	{
1403
+		// gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1404
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1405
+		$post_type        = $this->_cpt_routes[ $this->_req_action ];
1406
+		$post_type_object = $this->_cpt_object;
1407
+		$title            = $post_type_object->labels->add_new_item;
1408
+		$post             = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1409
+		add_action('admin_print_styles', [$this, 'add_new_admin_page_global']);
1410
+		// modify the default editor title field with default title.
1411
+		add_filter('enter_title_here', [$this, 'add_custom_editor_default_title'], 10);
1412
+		$this->loadEditorTemplate(true);
1413
+	}
1414
+
1415
+
1416
+	/**
1417
+	 * Enqueues auto-save and loads the editor template
1418
+	 *
1419
+	 * @param bool $creating
1420
+	 */
1421
+	private function loadEditorTemplate($creating = true)
1422
+	{
1423
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1424
+		// these vars are used by the template
1425
+		$editing = true;
1426
+		$post_ID = $post->ID;
1427
+		if (apply_filters('FHEE__EE_Admin_Page_CPT___create_new_cpt_item__replace_editor', false, $post) === false) {
1428
+			// only enqueue autosave when creating event (necessary to get permalink/url generated)
1429
+			// otherwise EE doesn't support autosave fully, so to prevent user confusion we disable it in edit context.
1430
+			if ($creating) {
1431
+				wp_enqueue_script('autosave');
1432
+			} elseif (
1433
+				isset($this->_cpt_routes[ $this->_req_data['action'] ])
1434
+				&& ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1435
+			) {
1436
+				$create_new_action = apply_filters(
1437
+					'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1438
+					'create_new',
1439
+					$this
1440
+				);
1441
+				$post_new_file = EE_Admin_Page::add_query_args_and_nonce(
1442
+					array(
1443
+						'action' => $create_new_action,
1444
+						'page'   => $this->page_slug,
1445
+					),
1446
+					'admin.php'
1447
+				);
1448
+			}
1449
+			include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1450
+		}
1451
+	}
1452
+
1453
+
1454
+	public function add_new_admin_page_global()
1455
+	{
1456
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1457
+		?>
1458 1458
         <script type="text/javascript">
1459 1459
             adminpage = '<?php echo esc_js($admin_page); ?>';
1460 1460
         </script>
1461 1461
         <?php
1462
-    }
1463
-
1464
-
1465
-    /**
1466
-     * default method for the 'edit' route for cpt admin pages
1467
-     * For reference on what to put in here, refer to wp-admin/post.php
1468
-     *
1469
-     * @return string   template for edit cpt form
1470
-     */
1471
-    protected function _edit_cpt_item()
1472
-    {
1473
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1474
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1475
-        $post    = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1476
-        if (empty($post)) {
1477
-            wp_die(esc_html__(
1478
-                'You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?',
1479
-                'event_espresso'
1480
-            ));
1481
-        }
1482
-
1483
-        $post_lock = $this->request->getRequestParam('get-post-lock');
1484
-        if ($post_lock) {
1485
-            wp_set_post_lock($post_id);
1486
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1487
-            exit();
1488
-        }
1489
-
1490
-        // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1491
-        $post_type        = $this->_cpt_routes[ $this->_req_action ];
1492
-        $post_type_object = $this->_cpt_object;
1493
-
1494
-        if (! wp_check_post_lock($post->ID)) {
1495
-            wp_set_post_lock($post->ID);
1496
-        }
1497
-        add_action('admin_footer', '_admin_notice_post_locked');
1498
-        if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1499
-            wp_enqueue_script('admin-comments');
1500
-            enqueue_comment_hotkeys_js();
1501
-        }
1502
-        add_action('admin_print_styles', [$this, 'add_new_admin_page_global']);
1503
-        // modify the default editor title field with default title.
1504
-        add_filter('enter_title_here', [$this, 'add_custom_editor_default_title'], 10);
1505
-        $this->loadEditorTemplate(false);
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * some getters
1512
-     */
1513
-    /**
1514
-     * This returns the protected _cpt_model_obj property
1515
-     *
1516
-     * @return EE_CPT_Base
1517
-     */
1518
-    public function get_cpt_model_obj()
1519
-    {
1520
-        return $this->_cpt_model_obj;
1521
-    }
1462
+	}
1463
+
1464
+
1465
+	/**
1466
+	 * default method for the 'edit' route for cpt admin pages
1467
+	 * For reference on what to put in here, refer to wp-admin/post.php
1468
+	 *
1469
+	 * @return string   template for edit cpt form
1470
+	 */
1471
+	protected function _edit_cpt_item()
1472
+	{
1473
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1474
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1475
+		$post    = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1476
+		if (empty($post)) {
1477
+			wp_die(esc_html__(
1478
+				'You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?',
1479
+				'event_espresso'
1480
+			));
1481
+		}
1482
+
1483
+		$post_lock = $this->request->getRequestParam('get-post-lock');
1484
+		if ($post_lock) {
1485
+			wp_set_post_lock($post_id);
1486
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1487
+			exit();
1488
+		}
1489
+
1490
+		// template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1491
+		$post_type        = $this->_cpt_routes[ $this->_req_action ];
1492
+		$post_type_object = $this->_cpt_object;
1493
+
1494
+		if (! wp_check_post_lock($post->ID)) {
1495
+			wp_set_post_lock($post->ID);
1496
+		}
1497
+		add_action('admin_footer', '_admin_notice_post_locked');
1498
+		if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1499
+			wp_enqueue_script('admin-comments');
1500
+			enqueue_comment_hotkeys_js();
1501
+		}
1502
+		add_action('admin_print_styles', [$this, 'add_new_admin_page_global']);
1503
+		// modify the default editor title field with default title.
1504
+		add_filter('enter_title_here', [$this, 'add_custom_editor_default_title'], 10);
1505
+		$this->loadEditorTemplate(false);
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * some getters
1512
+	 */
1513
+	/**
1514
+	 * This returns the protected _cpt_model_obj property
1515
+	 *
1516
+	 * @return EE_CPT_Base
1517
+	 */
1518
+	public function get_cpt_model_obj()
1519
+	{
1520
+		return $this->_cpt_model_obj;
1521
+	}
1522 1522
 }
Please login to merge, or discard this patch.
Spacing   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
      */
160 160
     protected function getLoader()
161 161
     {
162
-        if (! $this->loader instanceof LoaderInterface) {
162
+        if ( ! $this->loader instanceof LoaderInterface) {
163 163
             $this->loader = LoaderFactory::getLoader();
164 164
         }
165 165
         return $this->loader;
@@ -183,15 +183,15 @@  discard block
 block discarded – undo
183 183
             ],
184 184
             $this->_cpt_routes
185 185
         );
186
-        $cpt_route_action  = isset($this->_cpt_routes[ $this->raw_req_action ])
187
-            ? $this->_cpt_routes[ $this->raw_req_action ]
186
+        $cpt_route_action = isset($this->_cpt_routes[$this->raw_req_action])
187
+            ? $this->_cpt_routes[$this->raw_req_action]
188 188
             : null;
189 189
         // let's see if the current route has a value for cpt_object_slug. if it does, we use that instead of the page
190 190
         $page              = $this->raw_req_page ?: $this->page_slug;
191 191
         $page              = $cpt_route_action ?: $page;
192 192
         $this->_cpt_object = get_post_type_object($page);
193 193
         // tweak pagenow for page loading.
194
-        if (! $this->_pagenow_map) {
194
+        if ( ! $this->_pagenow_map) {
195 195
             $this->_pagenow_map = [
196 196
                 'create_new' => 'post-new.php',
197 197
                 'edit'       => 'post.php',
@@ -217,10 +217,10 @@  discard block
 block discarded – undo
217 217
         // possibly reset pagenow.
218 218
         if (
219 219
             $this->page_slug === $this->raw_req_page
220
-            && isset($this->_pagenow_map[ $this->raw_req_action ])
220
+            && isset($this->_pagenow_map[$this->raw_req_action])
221 221
         ) {
222 222
             global $pagenow, $hook_suffix;
223
-            $pagenow     = $this->_pagenow_map[ $this->raw_req_action ];
223
+            $pagenow     = $this->_pagenow_map[$this->raw_req_action];
224 224
             $hook_suffix = $pagenow;
225 225
         }
226 226
     }
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
         if (empty($wp_meta_boxes)) {
253 253
             return;
254 254
         }
255
-        $current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : [];
255
+        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : [];
256 256
         foreach ($current_metaboxes as $box_context) {
257 257
             foreach ($box_context as $box_details) {
258 258
                 foreach ($box_details as $box) {
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
             $this
287 287
         );
288 288
         $containers = apply_filters(
289
-            'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
289
+            'FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
290 290
             $containers,
291 291
             $this
292 292
         );
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
     protected function _load_page_dependencies()
324 324
     {
325 325
         // we only add stuff if this is a cpt_route!
326
-        if (! $this->_cpt_route) {
326
+        if ( ! $this->_cpt_route) {
327 327
             parent::_load_page_dependencies();
328 328
             return;
329 329
         }
@@ -347,16 +347,16 @@  discard block
 block discarded – undo
347 347
         add_filter('pre_get_shortlink', [$this, 'add_shortlink_button_to_editor'], 10, 4);
348 348
         // This basically allows us to change the title of the "publish" metabox area
349 349
         // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
350
-        if (! empty($this->_labels['publishbox'])) {
350
+        if ( ! empty($this->_labels['publishbox'])) {
351 351
             $box_label = is_array($this->_labels['publishbox'])
352
-                         && isset($this->_labels['publishbox'][ $this->_req_action ])
353
-                ? $this->_labels['publishbox'][ $this->_req_action ]
352
+                         && isset($this->_labels['publishbox'][$this->_req_action])
353
+                ? $this->_labels['publishbox'][$this->_req_action]
354 354
                 : $this->_labels['publishbox'];
355 355
             $this->addMetaBox(
356 356
                 'submitdiv',
357 357
                 $box_label,
358 358
                 'post_submit_meta_box',
359
-                $this->_cpt_routes[ $this->_req_action ],
359
+                $this->_cpt_routes[$this->_req_action],
360 360
                 'side',
361 361
                 'core'
362 362
             );
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
                 'page_templates',
368 368
                 esc_html__('Page Template', 'event_espresso'),
369 369
                 [$this, 'page_template_meta_box'],
370
-                $this->_cpt_routes[ $this->_req_action ],
370
+                $this->_cpt_routes[$this->_req_action],
371 371
                 'side',
372 372
                 'default'
373 373
             );
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
         // This is for any plugins that are doing things properly
400 400
         // and hooking into the load page hook for core wp cpt routes.
401 401
         global $pagenow;
402
-        add_action('load-' . $pagenow, [$this, 'modify_current_screen'], 20);
403
-        do_action('load-' . $pagenow);
402
+        add_action('load-'.$pagenow, [$this, 'modify_current_screen'], 20);
403
+        do_action('load-'.$pagenow);
404 404
         add_action('admin_enqueue_scripts', [$this, 'setup_autosave_hooks'], 30);
405 405
         // we route REALLY early.
406 406
         try {
@@ -429,8 +429,8 @@  discard block
 block discarded – undo
429 429
                 'admin.php?page=espresso_registrations&action=contact_list',
430 430
             ],
431 431
             1 => [
432
-                'edit.php?post_type=' . $this->_cpt_object->name,
433
-                'admin.php?page=' . $this->_cpt_object->name,
432
+                'edit.php?post_type='.$this->_cpt_object->name,
433
+                'admin.php?page='.$this->_cpt_object->name,
434 434
             ],
435 435
         ];
436 436
         foreach ($routes_to_match as $route_matches) {
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
             'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
460 460
         );
461 461
         $cpt_args          = $custom_post_types->getDefinitions();
462
-        $cpt_args          = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : [];
462
+        $cpt_args          = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : [];
463 463
         $cpt_has_support   = ! empty($cpt_args['page_templates']);
464 464
 
465 465
         // if the installed version of WP is > 4.7 we do some additional checks.
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
             // if there are $post_templates for this cpt, then we return false for this method because
469 469
             // that means we aren't going to load our page template manager and leave that up to the native
470 470
             // cpt template manager.
471
-            $cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
471
+            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
472 472
         }
473 473
 
474 474
         return $cpt_has_support;
@@ -525,8 +525,8 @@  discard block
 block discarded – undo
525 525
         if ('publish' !== get_post_status($post)) {
526 526
             $return .= '
527 527
             <span id="view-post-btn">
528
-                <a target="_blank" href="' . get_preview_post_link($id) . '" class="button button--secondary">
529
-                    ' . esc_html__('Preview', 'event_espresso') . '
528
+                <a target="_blank" href="' . get_preview_post_link($id).'" class="button button--secondary">
529
+                    ' . esc_html__('Preview', 'event_espresso').'
530 530
                 </a>
531 531
             </span>
532 532
             ';
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 
546 546
         $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
547 547
         $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
548
-            ? $statuses[ $this->_cpt_model_obj->status() ]
548
+            ? $statuses[$this->_cpt_model_obj->status()]
549 549
             : '';
550 550
         $template_args    = [
551 551
             'cur_status'            => $this->_cpt_model_obj->status(),
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
             $template_args['statuses']         = $statuses;
561 561
         }
562 562
 
563
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
563
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
564 564
         EEH_Template::display_template($template, $template_args);
565 565
     }
566 566
 
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
         $nonce = $this->request->getRequestParam('autosavenonce');
601 601
         $this->_verify_nonce($nonce, 'autosave');
602 602
         // make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
603
-        if (! defined('DOING_AUTOSAVE')) {
603
+        if ( ! defined('DOING_AUTOSAVE')) {
604 604
             define('DOING_AUTOSAVE', true);
605 605
         }
606 606
         // if we made it here then the nonce checked out.  Let's run our methods and actions
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
             $this->_template_args['success'] = true;
612 612
         }
613 613
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
614
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
614
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
615 615
         // now let's return json
616 616
         $this->_return_json();
617 617
     }
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
             return;
634 634
         }
635 635
         // set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
636
-        if (! empty($this->_cpt_object)) {
636
+        if ( ! empty($this->_cpt_object)) {
637 637
             $this->_page_routes = array_merge(
638 638
                 [
639 639
                     'create_new' => '_create_new_cpt_item',
@@ -664,7 +664,7 @@  discard block
 block discarded – undo
664 664
             );
665 665
         }
666 666
         // load the next section only if this is a matching cpt route as set in the cpt routes array.
667
-        if (! isset($this->_cpt_routes[ $this->_req_action ])) {
667
+        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
668 668
             return;
669 669
         }
670 670
         $this->_cpt_route = true;
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
             empty($this->_cpt_model_names)
706 706
             || (
707 707
                 ! $ignore_route_check
708
-                && ! isset($this->_cpt_routes[ $this->_req_action ])
708
+                && ! isset($this->_cpt_routes[$this->_req_action])
709 709
             )
710 710
             || (
711 711
                 $this->_cpt_model_obj instanceof EE_CPT_Base
@@ -723,11 +723,11 @@  discard block
 block discarded – undo
723 723
                 'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
724 724
             );
725 725
             $model_names       = $custom_post_types->getCustomPostTypeModelNames($post_type);
726
-            if (isset($model_names[ $post_type ])) {
727
-                $model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
726
+            if (isset($model_names[$post_type])) {
727
+                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
728 728
             }
729 729
         } else {
730
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
730
+            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
731 731
         }
732 732
         if ($model instanceof EEM_Base) {
733 733
             $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
@@ -756,8 +756,8 @@  discard block
 block discarded – undo
756 756
         $current_route  = isset($this->_req_data['current_route'])
757 757
             ? $this->_req_data['current_route']
758 758
             : 'shouldneverwork';
759
-        $route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
760
-            ? $this->_cpt_routes[ $current_route ]
759
+        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
760
+            ? $this->_cpt_routes[$current_route]
761 761
             : '';
762 762
         add_filter('get_delete_post_link', [$this, 'modify_delete_post_link'], 10, 3);
763 763
         add_filter('get_edit_post_link', [$this, 'modify_edit_post_link'], 10, 3);
@@ -766,10 +766,10 @@  discard block
 block discarded – undo
766 766
         }
767 767
         // now let's filter redirect if we're on a revision page and the revision is for an event CPT.
768 768
         $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
769
-        if (! empty($revision)) {
769
+        if ( ! empty($revision)) {
770 770
             $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
771 771
             // doing a restore?
772
-            if (! empty($action) && $action === 'restore') {
772
+            if ( ! empty($action) && $action === 'restore') {
773 773
                 // get post for revision
774 774
                 $rev_post   = get_post($revision);
775 775
                 $rev_parent = get_post($rev_post->post_parent);
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
     {
807 807
         $this->_set_model_object($post_id, true, 'trash');
808 808
         // if our cpt object isn't existent then get out immediately.
809
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
809
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
810 810
             return;
811 811
         }
812 812
         $this->trash_cpt_item($post_id);
@@ -825,7 +825,7 @@  discard block
 block discarded – undo
825 825
     {
826 826
         $this->_set_model_object($post_id, true, 'restore');
827 827
         // if our cpt object isn't existent then get out immediately.
828
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
828
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
829 829
             return;
830 830
         }
831 831
         $this->restore_cpt_item($post_id);
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
     {
845 845
         $this->_set_model_object($post_id, true, 'delete');
846 846
         // if our cpt object isn't existent then get out immediately.
847
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
847
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
848 848
             return;
849 849
         }
850 850
         $this->delete_cpt_item($post_id);
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
     {
864 864
         $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
865 865
         // verify event object
866
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
866
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
867 867
             throw new EE_Error(
868 868
                 sprintf(
869 869
                     esc_html__(
@@ -919,13 +919,13 @@  discard block
 block discarded – undo
919 919
         if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
920 920
             // setup custom post status object for localize script but only if we've got a cpt object
921 921
             $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
922
-            if (! empty($statuses)) {
922
+            if ( ! empty($statuses)) {
923 923
                 // get ALL statuses!
924 924
                 $statuses = $this->_cpt_model_obj->get_all_post_statuses();
925 925
                 // setup object
926 926
                 $ee_cpt_statuses = [];
927 927
                 foreach ($statuses as $status => $label) {
928
-                    $ee_cpt_statuses[ $status ] = [
928
+                    $ee_cpt_statuses[$status] = [
929 929
                         'label'      => $label,
930 930
                         'save_label' => sprintf(
931 931
                             wp_strip_all_tags(__('Save as %s', 'event_espresso')),
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
             }
996 996
             if (
997 997
                 'default' != $this->_req_data['page_template']
998
-                && ! isset($page_templates[ $this->_req_data['page_template'] ])
998
+                && ! isset($page_templates[$this->_req_data['page_template']])
999 999
             ) {
1000 1000
                 EE_Error::add_error(
1001 1001
                     esc_html__('Invalid Page Template.', 'event_espresso'),
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
     {
1027 1027
         // only do this if we're actually processing one of our CPTs
1028 1028
         // if our cpt object isn't existent then get out immediately.
1029
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1029
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1030 1030
             return;
1031 1031
         }
1032 1032
         delete_post_meta($post_id, '_wp_trash_meta_status');
@@ -1051,7 +1051,7 @@  discard block
 block discarded – undo
1051 1051
         // global action
1052 1052
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1053 1053
         // class specific action so you can limit hooking into a specific page.
1054
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1054
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
1055 1055
     }
1056 1056
 
1057 1057
 
@@ -1079,11 +1079,11 @@  discard block
 block discarded – undo
1079 1079
     public function modify_current_screen()
1080 1080
     {
1081 1081
         // ONLY do this if the current page_route IS a cpt route
1082
-        if (! $this->_cpt_route) {
1082
+        if ( ! $this->_cpt_route) {
1083 1083
             return;
1084 1084
         }
1085 1085
         // routing things REALLY early b/c this is a cpt admin page
1086
-        set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1086
+        set_current_screen($this->_cpt_routes[$this->_req_action]);
1087 1087
         $this->_current_screen       = get_current_screen();
1088 1088
         $this->_current_screen->base = 'event-espresso';
1089 1089
         $this->_add_help_tabs(); // we make sure we add any help tabs back in!
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
      */
1107 1107
     public function add_custom_editor_default_title($title)
1108 1108
     {
1109
-        return $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ] ?? $title;
1109
+        return $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]] ?? $title;
1110 1110
     }
1111 1111
 
1112 1112
 
@@ -1121,10 +1121,10 @@  discard block
 block discarded – undo
1121 1121
      */
1122 1122
     public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1123 1123
     {
1124
-        if (! empty($id) && get_option('permalink_structure') !== '') {
1124
+        if ( ! empty($id) && get_option('permalink_structure') !== '') {
1125 1125
             $post = get_post($id);
1126 1126
             if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1127
-                $shortlink = home_url('?p=' . $post->ID);
1127
+                $shortlink = home_url('?p='.$post->ID);
1128 1128
             }
1129 1129
         }
1130 1130
         return $shortlink;
@@ -1161,10 +1161,10 @@  discard block
 block discarded – undo
1161 1161
     {
1162 1162
         // we're also going to add the route value and the current page so we can direct autosave parsing correctly
1163 1163
         echo '
1164
-        <input type="hidden" name="ee_cpt_item_redirect_url" value="' . esc_url_raw($this->_admin_base_url) . '"/>
1164
+        <input type="hidden" name="ee_cpt_item_redirect_url" value="' . esc_url_raw($this->_admin_base_url).'"/>
1165 1165
         <div id="ee-cpt-hidden-inputs">
1166
-            <input type="hidden" id="current_route" name="current_route" value="' . esc_attr($this->_current_view) . '"/>
1167
-            <input type="hidden" id="current_page" name="current_page" value="' . esc_attr($this->page_slug) . '"/>
1166
+            <input type="hidden" id="current_route" name="current_route" value="' . esc_attr($this->_current_view).'"/>
1167
+            <input type="hidden" id="current_page" name="current_page" value="' . esc_attr($this->page_slug).'"/>
1168 1168
         </div>';
1169 1169
     }
1170 1170
 
@@ -1212,13 +1212,13 @@  discard block
 block discarded – undo
1212 1212
         $post = get_post($id);
1213 1213
         if (
1214 1214
             ! isset($this->_req_data['action'])
1215
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1216
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1215
+            || ! isset($this->_cpt_routes[$this->_req_data['action']])
1216
+            || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1217 1217
         ) {
1218 1218
             return $link;
1219 1219
         }
1220 1220
         $query_args = [
1221
-            'action' => $this->_cpt_edit_routes[ $post->post_type ] ?? 'edit',
1221
+            'action' => $this->_cpt_edit_routes[$post->post_type] ?? 'edit',
1222 1222
             'post'   => $id,
1223 1223
         ];
1224 1224
         return EE_Admin_Page_CPT::add_query_args_and_nonce($query_args, $this->_admin_base_url);
@@ -1242,16 +1242,16 @@  discard block
 block discarded – undo
1242 1242
 
1243 1243
         if (
1244 1244
             empty($this->_req_data['action'])
1245
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1245
+            || ! isset($this->_cpt_routes[$this->_req_data['action']])
1246 1246
             || ! $post instanceof WP_Post
1247
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1247
+            || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1248 1248
         ) {
1249 1249
             return $delete_link;
1250 1250
         }
1251 1251
         $this->_set_model_object($post->ID, true);
1252 1252
 
1253 1253
         // returns something like `trash_event` or `trash_attendee` or `trash_venue`
1254
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1254
+        $action = 'trash_'.str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1255 1255
 
1256 1256
         return EE_Admin_Page::add_query_args_and_nonce(
1257 1257
             [
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
         // we DO have a match so let's setup the url
1281 1281
         // we have to get the post to determine our route
1282 1282
         $post       = get_post($post_id);
1283
-        $edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1283
+        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1284 1284
         // shared query_args
1285 1285
         $query_args = ['action' => $edit_route, 'post' => $post_id];
1286 1286
         $admin_url  = $this->_admin_base_url;
@@ -1343,12 +1343,12 @@  discard block
 block discarded – undo
1343 1343
         $id       = empty($id) && is_object($post) ? $post->ID : null;
1344 1344
         $revision = $this->request->getRequestParam('revision', 0, 'int');
1345 1345
 
1346
-        $messages[ $post->post_type ] = [
1346
+        $messages[$post->post_type] = [
1347 1347
             0  => '', // Unused. Messages start at index 1.
1348 1348
             1  => sprintf(
1349 1349
                 esc_html__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1350 1350
                 $this->_cpt_object->labels->singular_name,
1351
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1351
+                '<a href="'.esc_url(get_permalink($id)).'">',
1352 1352
                 '</a>'
1353 1353
             ),
1354 1354
             2  => esc_html__('Custom field updated', 'event_espresso'),
@@ -1364,27 +1364,27 @@  discard block
 block discarded – undo
1364 1364
             6  => sprintf(
1365 1365
                 esc_html__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1366 1366
                 $this->_cpt_object->labels->singular_name,
1367
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1367
+                '<a href="'.esc_url(get_permalink($id)).'">',
1368 1368
                 '</a>'
1369 1369
             ),
1370 1370
             7  => sprintf(esc_html__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1371 1371
             8  => sprintf(
1372 1372
                 esc_html__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1373 1373
                 $this->_cpt_object->labels->singular_name,
1374
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1374
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1375 1375
                 '</a>'
1376 1376
             ),
1377 1377
             9  => sprintf(
1378 1378
                 esc_html__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1379 1379
                 $this->_cpt_object->labels->singular_name,
1380
-                '<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1381
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1380
+                '<strong>'.date_i18n('M j, Y @ G:i', strtotime($post->post_date)).'</strong>',
1381
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1382 1382
                 '</a>'
1383 1383
             ),
1384 1384
             10 => sprintf(
1385 1385
                 esc_html__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1386 1386
                 $this->_cpt_object->labels->singular_name,
1387
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1387
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1388 1388
                 '</a>'
1389 1389
             ),
1390 1390
         ];
@@ -1402,10 +1402,10 @@  discard block
 block discarded – undo
1402 1402
     {
1403 1403
         // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1404 1404
         global $post, $title, $is_IE, $post_type, $post_type_object;
1405
-        $post_type        = $this->_cpt_routes[ $this->_req_action ];
1405
+        $post_type        = $this->_cpt_routes[$this->_req_action];
1406 1406
         $post_type_object = $this->_cpt_object;
1407 1407
         $title            = $post_type_object->labels->add_new_item;
1408
-        $post             = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1408
+        $post             = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1409 1409
         add_action('admin_print_styles', [$this, 'add_new_admin_page_global']);
1410 1410
         // modify the default editor title field with default title.
1411 1411
         add_filter('enter_title_here', [$this, 'add_custom_editor_default_title'], 10);
@@ -1430,8 +1430,8 @@  discard block
 block discarded – undo
1430 1430
             if ($creating) {
1431 1431
                 wp_enqueue_script('autosave');
1432 1432
             } elseif (
1433
-                isset($this->_cpt_routes[ $this->_req_data['action'] ])
1434
-                && ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1433
+                isset($this->_cpt_routes[$this->_req_data['action']])
1434
+                && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1435 1435
             ) {
1436 1436
                 $create_new_action = apply_filters(
1437 1437
                     'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
@@ -1446,7 +1446,7 @@  discard block
 block discarded – undo
1446 1446
                     'admin.php'
1447 1447
                 );
1448 1448
             }
1449
-            include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1449
+            include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1450 1450
         }
1451 1451
     }
1452 1452
 
@@ -1488,14 +1488,14 @@  discard block
 block discarded – undo
1488 1488
         }
1489 1489
 
1490 1490
         // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1491
-        $post_type        = $this->_cpt_routes[ $this->_req_action ];
1491
+        $post_type        = $this->_cpt_routes[$this->_req_action];
1492 1492
         $post_type_object = $this->_cpt_object;
1493 1493
 
1494
-        if (! wp_check_post_lock($post->ID)) {
1494
+        if ( ! wp_check_post_lock($post->ID)) {
1495 1495
             wp_set_post_lock($post->ID);
1496 1496
         }
1497 1497
         add_action('admin_footer', '_admin_notice_post_locked');
1498
-        if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1498
+        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1499 1499
             wp_enqueue_script('admin-comments');
1500 1500
             enqueue_comment_hotkeys_js();
1501 1501
         }
Please login to merge, or discard this patch.
core/domain/services/graphql/types/Event.php 2 patches
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -24,225 +24,225 @@
 block discarded – undo
24 24
  */
25 25
 class Event extends TypeBase
26 26
 {
27
-    /**
28
-     * Event constructor.
29
-     *
30
-     * @param EEM_Event $event_model
31
-     */
32
-    public function __construct(EEM_Event $event_model)
33
-    {
34
-        $this->setName($this->namespace . 'Event');
35
-        $this->setIsCustomPostType(true);
36
-        parent::__construct($event_model);
37
-    }
27
+	/**
28
+	 * Event constructor.
29
+	 *
30
+	 * @param EEM_Event $event_model
31
+	 */
32
+	public function __construct(EEM_Event $event_model)
33
+	{
34
+		$this->setName($this->namespace . 'Event');
35
+		$this->setIsCustomPostType(true);
36
+		parent::__construct($event_model);
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * @return GraphQLFieldInterface[]
42
-     */
43
-    public function getFields(): array
44
-    {
45
-        return apply_filters(
46
-            'FHEE__EventEspresso_core_domain_services_graphql_types__event_fields',
47
-            [
48
-                new GraphQLField(
49
-                    'allowDonations',
50
-                    'Boolean',
51
-                    'donations',
52
-                    esc_html__('Accept Donations?', 'event_espresso')
53
-                ),
54
-                new GraphQLField(
55
-                    'allowOverflow',
56
-                    'Boolean',
57
-                    'allow_overflow',
58
-                    esc_html__('Enable Wait List for Event', 'event_espresso')
59
-                ),
60
-                new GraphQLField(
61
-                    'altRegPage',
62
-                    'String',
63
-                    'external_url',
64
-                    esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso')
65
-                ),
66
-                new GraphQLOutputField(
67
-                    'cacheId',
68
-                    ['non_null' => 'String'],
69
-                    null,
70
-                    esc_html__('The cache ID of the object.', 'event_espresso')
71
-                ),
72
-                new GraphQLField(
73
-                    'created',
74
-                    'String',
75
-                    'created',
76
-                    esc_html__('Date/Time Event Created', 'event_espresso')
77
-                ),
78
-                new GraphQLOutputField(
79
-                    'dbId',
80
-                    ['non_null' => 'Int'],
81
-                    'ID',
82
-                    esc_html__('The event ID.', 'event_espresso')
83
-                ),
84
-                new GraphQLField(
85
-                    'defaultRegStatus',
86
-                    $this->namespace . 'RegistrationStatusEnum',
87
-                    'default_registration_status',
88
-                    esc_html__('Default Event Registration Status', 'event_espresso')
89
-                ),
90
-                new GraphQLField(
91
-                    'description',
92
-                    'String',
93
-                    'description',
94
-                    esc_html__('Event Description', 'event_espresso')
95
-                ),
96
-                new GraphQLField(
97
-                    'displayDescription',
98
-                    'Boolean',
99
-                    'display_description',
100
-                    esc_html__('Display Description Flag', 'event_espresso')
101
-                ),
102
-                new GraphQLField(
103
-                    'displayTicketSelector',
104
-                    'Boolean',
105
-                    'display_ticket_selector',
106
-                    esc_html__('Display Ticket Selector Flag', 'event_espresso')
107
-                ),
108
-                new GraphQLOutputField(
109
-                    'isActive',
110
-                    'Boolean',
111
-                    'is_active',
112
-                    esc_html__('Flag indicating event is active', 'event_espresso')
113
-                ),
114
-                new GraphQLOutputField(
115
-                    'isCancelled',
116
-                    'Boolean',
117
-                    'is_cancelled',
118
-                    esc_html__('Flag indicating whether the event is marked as cancelled', 'event_espresso')
119
-                ),
120
-                new GraphQLOutputField(
121
-                    'isExpired',
122
-                    'Boolean',
123
-                    'is_expired',
124
-                    esc_html__('Flag indicating event is expired or not', 'event_espresso')
125
-                ),
126
-                new GraphQLOutputField(
127
-                    'isInactive',
128
-                    'Boolean',
129
-                    'is_inactive',
130
-                    esc_html__('Flag indicating event is inactive', 'event_espresso')
131
-                ),
132
-                new GraphQLOutputField(
133
-                    'isPostponed',
134
-                    'Boolean',
135
-                    'is_postponed',
136
-                    esc_html__('Flag indicating whether the event is marked as postponed', 'event_espresso')
137
-                ),
138
-                new GraphQLOutputField(
139
-                    'isSoldOut',
140
-                    'Boolean',
141
-                    'is_sold_out',
142
-                    esc_html__(
143
-                        'Flag indicating whether the tickets sold for the event, met or exceed the registration limit',
144
-                        'event_espresso'
145
-                    )
146
-                ),
147
-                new GraphQLOutputField(
148
-                    'isUpcoming',
149
-                    'Boolean',
150
-                    'is_upcoming',
151
-                    esc_html__('Whether the event is upcoming', 'event_espresso')
152
-                ),
153
-                new GraphQLInputField(
154
-                    'manager',
155
-                    'String',
156
-                    null,
157
-                    esc_html__('Globally unique event ID for the event manager', 'event_espresso')
158
-                ),
159
-                new GraphQLOutputField(
160
-                    'manager',
161
-                    'User',
162
-                    null,
163
-                    esc_html__('Event Manager', 'event_espresso')
164
-                ),
165
-                new GraphQLField(
166
-                    'maxRegistrations',
167
-                    'Int',
168
-                    'additional_limit',
169
-                    esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso')
170
-                ),
171
-                new GraphQLField(
172
-                    'memberOnly',
173
-                    'Boolean',
174
-                    'member_only',
175
-                    esc_html__('Member-Only Event Flag', 'event_espresso')
176
-                ),
177
-                new GraphQLField(
178
-                    'name',
179
-                    'String',
180
-                    'name',
181
-                    esc_html__('Event Name', 'event_espresso')
182
-                ),
183
-                new GraphQLField(
184
-                    'order',
185
-                    'Int',
186
-                    'order',
187
-                    esc_html__('Event Menu Order', 'event_espresso')
188
-                ),
189
-                new GraphQLField(
190
-                    'phoneNumber',
191
-                    'String',
192
-                    'phone',
193
-                    esc_html__('Event Phone Number', 'event_espresso')
194
-                ),
195
-                new GraphQLField(
196
-                    'shortDescription',
197
-                    'String',
198
-                    'short_description',
199
-                    esc_html__('Event Short Description', 'event_espresso')
200
-                ),
201
-                new GraphQLField(
202
-                    'timezoneString',
203
-                    'String',
204
-                    'timezone_string',
205
-                    esc_html__('Timezone (name) for Event times', 'event_espresso')
206
-                ),
207
-                new GraphQLField(
208
-                    'visibleOn',
209
-                    'String',
210
-                    'visible_on',
211
-                    esc_html__('Event Visible Date', 'event_espresso')
212
-                ),
213
-                new GraphQLField(
214
-                    'venue',
215
-                    'String',
216
-                    null,
217
-                    esc_html__('Event venue ID', 'event_espresso'),
218
-                    null,
219
-                    function (EE_Event $source) {
220
-                        $venue_ID = $source->venue_ID();
221
-                        return $venue_ID
222
-                            // Since venue is a CPT, $type will be 'post'
223
-                            ? Relay::toGlobalId('post', $venue_ID)
224
-                            : null;
225
-                    }
226
-                ),
227
-            ],
228
-            $this->name,
229
-            $this->model
230
-        );
231
-    }
40
+	/**
41
+	 * @return GraphQLFieldInterface[]
42
+	 */
43
+	public function getFields(): array
44
+	{
45
+		return apply_filters(
46
+			'FHEE__EventEspresso_core_domain_services_graphql_types__event_fields',
47
+			[
48
+				new GraphQLField(
49
+					'allowDonations',
50
+					'Boolean',
51
+					'donations',
52
+					esc_html__('Accept Donations?', 'event_espresso')
53
+				),
54
+				new GraphQLField(
55
+					'allowOverflow',
56
+					'Boolean',
57
+					'allow_overflow',
58
+					esc_html__('Enable Wait List for Event', 'event_espresso')
59
+				),
60
+				new GraphQLField(
61
+					'altRegPage',
62
+					'String',
63
+					'external_url',
64
+					esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso')
65
+				),
66
+				new GraphQLOutputField(
67
+					'cacheId',
68
+					['non_null' => 'String'],
69
+					null,
70
+					esc_html__('The cache ID of the object.', 'event_espresso')
71
+				),
72
+				new GraphQLField(
73
+					'created',
74
+					'String',
75
+					'created',
76
+					esc_html__('Date/Time Event Created', 'event_espresso')
77
+				),
78
+				new GraphQLOutputField(
79
+					'dbId',
80
+					['non_null' => 'Int'],
81
+					'ID',
82
+					esc_html__('The event ID.', 'event_espresso')
83
+				),
84
+				new GraphQLField(
85
+					'defaultRegStatus',
86
+					$this->namespace . 'RegistrationStatusEnum',
87
+					'default_registration_status',
88
+					esc_html__('Default Event Registration Status', 'event_espresso')
89
+				),
90
+				new GraphQLField(
91
+					'description',
92
+					'String',
93
+					'description',
94
+					esc_html__('Event Description', 'event_espresso')
95
+				),
96
+				new GraphQLField(
97
+					'displayDescription',
98
+					'Boolean',
99
+					'display_description',
100
+					esc_html__('Display Description Flag', 'event_espresso')
101
+				),
102
+				new GraphQLField(
103
+					'displayTicketSelector',
104
+					'Boolean',
105
+					'display_ticket_selector',
106
+					esc_html__('Display Ticket Selector Flag', 'event_espresso')
107
+				),
108
+				new GraphQLOutputField(
109
+					'isActive',
110
+					'Boolean',
111
+					'is_active',
112
+					esc_html__('Flag indicating event is active', 'event_espresso')
113
+				),
114
+				new GraphQLOutputField(
115
+					'isCancelled',
116
+					'Boolean',
117
+					'is_cancelled',
118
+					esc_html__('Flag indicating whether the event is marked as cancelled', 'event_espresso')
119
+				),
120
+				new GraphQLOutputField(
121
+					'isExpired',
122
+					'Boolean',
123
+					'is_expired',
124
+					esc_html__('Flag indicating event is expired or not', 'event_espresso')
125
+				),
126
+				new GraphQLOutputField(
127
+					'isInactive',
128
+					'Boolean',
129
+					'is_inactive',
130
+					esc_html__('Flag indicating event is inactive', 'event_espresso')
131
+				),
132
+				new GraphQLOutputField(
133
+					'isPostponed',
134
+					'Boolean',
135
+					'is_postponed',
136
+					esc_html__('Flag indicating whether the event is marked as postponed', 'event_espresso')
137
+				),
138
+				new GraphQLOutputField(
139
+					'isSoldOut',
140
+					'Boolean',
141
+					'is_sold_out',
142
+					esc_html__(
143
+						'Flag indicating whether the tickets sold for the event, met or exceed the registration limit',
144
+						'event_espresso'
145
+					)
146
+				),
147
+				new GraphQLOutputField(
148
+					'isUpcoming',
149
+					'Boolean',
150
+					'is_upcoming',
151
+					esc_html__('Whether the event is upcoming', 'event_espresso')
152
+				),
153
+				new GraphQLInputField(
154
+					'manager',
155
+					'String',
156
+					null,
157
+					esc_html__('Globally unique event ID for the event manager', 'event_espresso')
158
+				),
159
+				new GraphQLOutputField(
160
+					'manager',
161
+					'User',
162
+					null,
163
+					esc_html__('Event Manager', 'event_espresso')
164
+				),
165
+				new GraphQLField(
166
+					'maxRegistrations',
167
+					'Int',
168
+					'additional_limit',
169
+					esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso')
170
+				),
171
+				new GraphQLField(
172
+					'memberOnly',
173
+					'Boolean',
174
+					'member_only',
175
+					esc_html__('Member-Only Event Flag', 'event_espresso')
176
+				),
177
+				new GraphQLField(
178
+					'name',
179
+					'String',
180
+					'name',
181
+					esc_html__('Event Name', 'event_espresso')
182
+				),
183
+				new GraphQLField(
184
+					'order',
185
+					'Int',
186
+					'order',
187
+					esc_html__('Event Menu Order', 'event_espresso')
188
+				),
189
+				new GraphQLField(
190
+					'phoneNumber',
191
+					'String',
192
+					'phone',
193
+					esc_html__('Event Phone Number', 'event_espresso')
194
+				),
195
+				new GraphQLField(
196
+					'shortDescription',
197
+					'String',
198
+					'short_description',
199
+					esc_html__('Event Short Description', 'event_espresso')
200
+				),
201
+				new GraphQLField(
202
+					'timezoneString',
203
+					'String',
204
+					'timezone_string',
205
+					esc_html__('Timezone (name) for Event times', 'event_espresso')
206
+				),
207
+				new GraphQLField(
208
+					'visibleOn',
209
+					'String',
210
+					'visible_on',
211
+					esc_html__('Event Visible Date', 'event_espresso')
212
+				),
213
+				new GraphQLField(
214
+					'venue',
215
+					'String',
216
+					null,
217
+					esc_html__('Event venue ID', 'event_espresso'),
218
+					null,
219
+					function (EE_Event $source) {
220
+						$venue_ID = $source->venue_ID();
221
+						return $venue_ID
222
+							// Since venue is a CPT, $type will be 'post'
223
+							? Relay::toGlobalId('post', $venue_ID)
224
+							: null;
225
+					}
226
+				),
227
+			],
228
+			$this->name,
229
+			$this->model
230
+		);
231
+	}
232 232
 
233 233
 
234
-    /**
235
-     * Extends the existing WP GraphQL mutations.
236
-     *
237
-     * @since $VID:$
238
-     */
239
-    public function extendMutations()
240
-    {
241
-        add_action(
242
-            'graphql_post_object_mutation_update_additional_data',
243
-            EventUpdate::mutateFields($this->model, $this),
244
-            10,
245
-            6
246
-        );
247
-    }
234
+	/**
235
+	 * Extends the existing WP GraphQL mutations.
236
+	 *
237
+	 * @since $VID:$
238
+	 */
239
+	public function extendMutations()
240
+	{
241
+		add_action(
242
+			'graphql_post_object_mutation_update_additional_data',
243
+			EventUpdate::mutateFields($this->model, $this),
244
+			10,
245
+			6
246
+		);
247
+	}
248 248
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
      */
32 32
     public function __construct(EEM_Event $event_model)
33 33
     {
34
-        $this->setName($this->namespace . 'Event');
34
+        $this->setName($this->namespace.'Event');
35 35
         $this->setIsCustomPostType(true);
36 36
         parent::__construct($event_model);
37 37
     }
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
                 ),
84 84
                 new GraphQLField(
85 85
                     'defaultRegStatus',
86
-                    $this->namespace . 'RegistrationStatusEnum',
86
+                    $this->namespace.'RegistrationStatusEnum',
87 87
                     'default_registration_status',
88 88
                     esc_html__('Default Event Registration Status', 'event_espresso')
89 89
                 ),
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
                     null,
217 217
                     esc_html__('Event venue ID', 'event_espresso'),
218 218
                     null,
219
-                    function (EE_Event $source) {
219
+                    function(EE_Event $source) {
220 220
                         $venue_ID = $source->venue_ID();
221 221
                         return $venue_ID
222 222
                             // Since venue is a CPT, $type will be 'post'
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 2 patches
Indentation   +729 added lines, -729 removed lines patch added patch discarded remove patch
@@ -27,733 +27,733 @@
 block discarded – undo
27 27
  */
28 28
 class EventSpacesCalculator
29 29
 {
30
-    /**
31
-     * @var EE_Event $event
32
-     */
33
-    private $event;
34
-
35
-    /**
36
-     * @var array $datetime_query_params
37
-     */
38
-    private $datetime_query_params;
39
-
40
-    /**
41
-     * @var EE_Ticket[] $active_tickets
42
-     */
43
-    private $active_tickets = [];
44
-
45
-    /**
46
-     * @var EE_Datetime[] $datetimes
47
-     */
48
-    private $datetimes = [];
49
-
50
-    /**
51
-     * Array of Ticket IDs grouped by Datetime
52
-     *
53
-     * @var array $datetimes
54
-     */
55
-    private $datetime_tickets = [];
56
-
57
-    /**
58
-     * Max spaces for each Datetime (reg limit - previous sold)
59
-     *
60
-     * @var array $datetime_spaces
61
-     */
62
-    private $datetime_spaces = [];
63
-
64
-    /**
65
-     * Array of Datetime IDs grouped by Ticket
66
-     *
67
-     * @var array[] $ticket_datetimes
68
-     */
69
-    private $ticket_datetimes = [];
70
-
71
-    /**
72
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
73
-     *
74
-     * @var array $ticket_quantities
75
-     */
76
-    private $ticket_quantities = [];
77
-
78
-    /**
79
-     * total quantity of sold and reserved for each ticket
80
-     *
81
-     * @var array $tickets_sold
82
-     */
83
-    private $tickets_sold = [];
84
-
85
-    /**
86
-     * total spaces available across all datetimes
87
-     *
88
-     * @var array $total_spaces
89
-     */
90
-    private $total_spaces = [];
91
-
92
-    /**
93
-     * @var boolean $debug
94
-     */
95
-    private $debug = false; // true false
96
-
97
-    /**
98
-     * @var int|float|null $spaces_remaining
99
-     */
100
-    private $spaces_remaining;
101
-
102
-    /**
103
-     * @var int|float|null $total_spaces_available
104
-     */
105
-    private $total_spaces_available;
106
-
107
-
108
-    /**
109
-     * EventSpacesCalculator constructor.
110
-     *
111
-     * @param EE_Event $event
112
-     * @param array    $datetime_query_params
113
-     * @throws EE_Error
114
-     * @throws ReflectionException
115
-     */
116
-    public function __construct(EE_Event $event, array $datetime_query_params = [])
117
-    {
118
-        if ($this->debug) {
119
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
120
-            EEH_Debug_Tools::printr((string) $event->ID(), 'For event', __FILE__, __LINE__);
121
-        }
122
-        $this->event                 = $event;
123
-        $this->datetime_query_params = $datetime_query_params + ['order_by' => ['DTT_reg_limit' => 'ASC']];
124
-        $this->setHooks();
125
-    }
126
-
127
-
128
-    /**
129
-     * @return void
130
-     */
131
-    private function setHooks()
132
-    {
133
-        add_action('AHEE__EE_Ticket__increase_sold', [$this, 'clearResults']);
134
-        add_action('AHEE__EE_Ticket__decrease_sold', [$this, 'clearResults']);
135
-        add_action('AHEE__EE_Datetime__increase_sold', [$this, 'clearResults']);
136
-        add_action('AHEE__EE_Datetime__decrease_sold', [$this, 'clearResults']);
137
-        add_action('AHEE__EE_Ticket__increase_reserved', [$this, 'clearResults']);
138
-        add_action('AHEE__EE_Ticket__decrease_reserved', [$this, 'clearResults']);
139
-        add_action('AHEE__EE_Datetime__increase_reserved', [$this, 'clearResults']);
140
-        add_action('AHEE__EE_Datetime__decrease_reserved', [$this, 'clearResults']);
141
-    }
142
-
143
-
144
-    /**
145
-     * @return void
146
-     */
147
-    public function clearResults()
148
-    {
149
-        if ($this->debug) {
150
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
151
-        }
152
-        $this->spaces_remaining       = null;
153
-        $this->total_spaces_available = null;
154
-    }
155
-
156
-
157
-    /**
158
-     * @return EE_Ticket[]
159
-     * @throws EE_Error
160
-     * @throws InvalidDataTypeException
161
-     * @throws InvalidInterfaceException
162
-     * @throws InvalidArgumentException
163
-     * @throws ReflectionException
164
-     */
165
-    public function getActiveTickets(): array
166
-    {
167
-        if (empty($this->active_tickets)) {
168
-            $this->active_tickets = $this->event->tickets(
169
-                [
170
-                    ['TKT_deleted' => false],
171
-                    'order_by' => ['TKT_qty' => 'ASC'],
172
-                ]
173
-            );
174
-        }
175
-        return $this->active_tickets;
176
-    }
177
-
178
-
179
-    /**
180
-     * @param EE_Ticket[] $active_tickets
181
-     * @throws EE_Error
182
-     * @throws DomainException
183
-     * @throws UnexpectedEntityException
184
-     * @throws ReflectionException
185
-     */
186
-    public function setActiveTickets(array $active_tickets = [])
187
-    {
188
-        if (! empty($active_tickets)) {
189
-            foreach ($active_tickets as $active_ticket) {
190
-                $this->validateTicket($active_ticket);
191
-            }
192
-            // sort incoming array by ticket quantity (asc)
193
-            usort(
194
-                $active_tickets,
195
-                function (EE_Ticket $a, EE_Ticket $b) {
196
-                    if ($a->qty() === $b->qty()) {
197
-                        return 0;
198
-                    }
199
-                    return ($a->qty() < $b->qty())
200
-                        ? -1
201
-                        : 1;
202
-                }
203
-            );
204
-        }
205
-        $this->active_tickets = $active_tickets;
206
-    }
207
-
208
-
209
-    /**
210
-     * @param $ticket
211
-     * @throws DomainException
212
-     * @throws EE_Error
213
-     * @throws UnexpectedEntityException
214
-     * @throws ReflectionException
215
-     */
216
-    private function validateTicket($ticket)
217
-    {
218
-        if (! $ticket instanceof EE_Ticket) {
219
-            throw new DomainException(
220
-                esc_html__(
221
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
222
-                    'event_espresso'
223
-                )
224
-            );
225
-        }
226
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
227
-            throw new DomainException(
228
-                sprintf(
229
-                    esc_html__(
230
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
231
-                        'event_espresso'
232
-                    ),
233
-                    $ticket->get_event_ID(),
234
-                    $this->event->ID()
235
-                )
236
-            );
237
-        }
238
-    }
239
-
240
-
241
-    /**
242
-     * @return EE_Datetime[]
243
-     */
244
-    public function getDatetimes(): array
245
-    {
246
-        return $this->datetimes;
247
-    }
248
-
249
-
250
-    /**
251
-     * @param EE_Datetime $datetime
252
-     * @throws EE_Error
253
-     * @throws DomainException
254
-     * @throws ReflectionException
255
-     */
256
-    public function setDatetime(EE_Datetime $datetime)
257
-    {
258
-        if ($datetime->event()->ID() !== $this->event->ID()) {
259
-            throw new DomainException(
260
-                sprintf(
261
-                    esc_html__(
262
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
263
-                        'event_espresso'
264
-                    ),
265
-                    $datetime->event()->ID(),
266
-                    $this->event->ID()
267
-                )
268
-            );
269
-        }
270
-        $this->datetimes[ $datetime->ID() ] = $datetime;
271
-    }
272
-
273
-
274
-    /**
275
-     * calculate spaces remaining based on "saleable" tickets
276
-     *
277
-     * @return int|float
278
-     * @throws EE_Error
279
-     * @throws DomainException
280
-     * @throws UnexpectedEntityException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidArgumentException
284
-     * @throws ReflectionException
285
-     */
286
-    public function spacesRemaining()
287
-    {
288
-        if ($this->debug) {
289
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
290
-        }
291
-        if ($this->spaces_remaining === null) {
292
-            $this->initialize();
293
-            $this->spaces_remaining = $this->calculate();
294
-        }
295
-        return $this->spaces_remaining;
296
-    }
297
-
298
-
299
-    /**
300
-     * calculates total available spaces for an event with no regard for sold tickets
301
-     *
302
-     * @return int|float
303
-     * @throws EE_Error
304
-     * @throws DomainException
305
-     * @throws UnexpectedEntityException
306
-     * @throws InvalidDataTypeException
307
-     * @throws InvalidInterfaceException
308
-     * @throws InvalidArgumentException
309
-     * @throws ReflectionException
310
-     */
311
-    public function totalSpacesAvailable()
312
-    {
313
-        if ($this->debug) {
314
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
315
-        }
316
-        if ($this->total_spaces_available === null) {
317
-            $this->initialize();
318
-            $this->total_spaces_available = $this->calculate(false);
319
-        }
320
-        return $this->total_spaces_available;
321
-    }
322
-
323
-
324
-    /**
325
-     * Loops through the active tickets for the event
326
-     * and builds a series of data arrays that will be used for calculating
327
-     * the total maximum available spaces, as well as the spaces remaining.
328
-     * Because ticket quantities affect datetime spaces and vice versa,
329
-     * we need to be constantly updating these data arrays as things change,
330
-     * which is the entire reason for their existence.
331
-     *
332
-     * @throws EE_Error
333
-     * @throws DomainException
334
-     * @throws UnexpectedEntityException
335
-     * @throws InvalidDataTypeException
336
-     * @throws InvalidInterfaceException
337
-     * @throws InvalidArgumentException
338
-     * @throws ReflectionException
339
-     */
340
-    private function initialize()
341
-    {
342
-        if ($this->debug) {
343
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
344
-        }
345
-        $this->datetime_tickets  = [];
346
-        $this->datetime_spaces   = [];
347
-        $this->ticket_datetimes  = [];
348
-        $this->ticket_quantities = [];
349
-        $this->tickets_sold      = [];
350
-        $this->total_spaces      = [];
351
-        $active_tickets          = $this->getActiveTickets();
352
-        if (! empty($active_tickets)) {
353
-            foreach ($active_tickets as $ticket) {
354
-                $this->validateTicket($ticket);
355
-                // we need to index our data arrays using strings for the purpose of sorting,
356
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
357
-                $ticket_identifier = "T{$ticket->ID()}";
358
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket,
359
-                // unless the ticket is past its "sell until" date, in which case the qty will be 0
360
-                $max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
361
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
362
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
363
-                foreach ($ticket_datetimes as $datetime) {
364
-                    // save all datetimes
365
-                    $this->setDatetime($datetime);
366
-                    $datetime_identifier = "D{$datetime->ID()}";
367
-                    $reg_limit           = $datetime->reg_limit();
368
-                    // ticket quantity can not exceed datetime reg limit
369
-                    $max_tickets = min($max_tickets, $reg_limit);
370
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
371
-                    // we are going to move all of our data into the following arrays:
372
-                    // datetime spaces initially represents the reg limit for each datetime,
373
-                    // but this will get adjusted as tickets are accounted for
374
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
375
-                    // just an array of ticket IDs grouped by datetime
376
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
377
-                    // and an array of datetime IDs grouped by ticket
378
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
379
-                }
380
-                // total quantity of sold and reserved for each ticket
381
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
382
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
383
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
384
-            }
385
-        }
386
-        // sort datetime spaces by reg limit, but maintain our string indexes
387
-        asort($this->datetime_spaces, SORT_NUMERIC);
388
-        // datetime tickets need to be sorted in the SAME order as the above array...
389
-        // so we'll just use array_merge() to take the structure of datetime_spaces
390
-        // but overwrite all of the data with that from datetime_tickets
391
-        $this->datetime_tickets = array_merge(
392
-            $this->datetime_spaces,
393
-            $this->datetime_tickets
394
-        );
395
-        if ($this->debug) {
396
-            EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
397
-            EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
398
-            EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
399
-        }
400
-    }
401
-
402
-
403
-    /**
404
-     * performs calculations on initialized data
405
-     *
406
-     * @param bool $consider_sold
407
-     * @return int|float
408
-     */
409
-    private function calculate(bool $consider_sold = true)
410
-    {
411
-        if ($this->debug) {
412
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
413
-            EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
414
-        }
415
-        if ($consider_sold) {
416
-            // subtract amounts sold from all ticket quantities and datetime spaces
417
-            $this->adjustTicketQuantitiesDueToSales();
418
-        }
419
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
420
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
421
-        }
422
-        // total spaces available is just the sum of the spaces available for each datetime
423
-        $spaces_remaining = array_sum($this->total_spaces);
424
-        if ($this->debug) {
425
-            EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
426
-            EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
427
-            EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
428
-        }
429
-        return $spaces_remaining;
430
-    }
431
-
432
-
433
-    /**
434
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
435
-     */
436
-    private function adjustTicketQuantitiesDueToSales()
437
-    {
438
-        if ($this->debug) {
439
-            EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
440
-        }
441
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
442
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
443
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
444
-                // don't let values go below zero
445
-                $this->ticket_quantities[ $ticket_identifier ] = max(
446
-                    $this->ticket_quantities[ $ticket_identifier ],
447
-                    0
448
-                );
449
-                if ($this->debug) {
450
-                    EEH_Debug_Tools::printr(
451
-                        "$tickets_sold sales for ticket $ticket_identifier ",
452
-                        'subtracting',
453
-                        __FILE__,
454
-                        __LINE__
455
-                    );
456
-                }
457
-            }
458
-            if (
459
-                isset($this->ticket_datetimes[ $ticket_identifier ])
460
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
461
-            ) {
462
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
463
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
464
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
465
-                        // don't let values go below zero
466
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
467
-                            $this->datetime_spaces[ $ticket_datetime ],
468
-                            0
469
-                        );
470
-                        if ($this->debug) {
471
-                            EEH_Debug_Tools::printr(
472
-                                "$tickets_sold sales for datetime $ticket_datetime ",
473
-                                'subtracting',
474
-                                __FILE__,
475
-                                __LINE__
476
-                            );
477
-                        }
478
-                    }
479
-                }
480
-            }
481
-        }
482
-    }
483
-
484
-
485
-    /**
486
-     * @param string $datetime_identifier
487
-     * @param array  $tickets
488
-     */
489
-    private function trackAvailableSpacesForDatetimes(string $datetime_identifier, array $tickets)
490
-    {
491
-        // make sure a reg limit is set for the datetime
492
-        $reg_limit = $this->datetime_spaces[ $datetime_identifier ] ?? 0;
493
-        // and bail if it is not
494
-        if (! $reg_limit) {
495
-            if ($this->debug) {
496
-                EEH_Debug_Tools::printr('AT CAPACITY', " . $datetime_identifier", __FILE__, __LINE__);
497
-            }
498
-            return;
499
-        }
500
-        if ($this->debug) {
501
-            EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
502
-            EEH_Debug_Tools::printr(
503
-                "$reg_limit",
504
-                'REG LIMIT',
505
-                __FILE__,
506
-                __LINE__
507
-            );
508
-        }
509
-        // number of allocated spaces always starts at zero
510
-        $spaces_allocated                           = 0;
511
-        $this->total_spaces[ $datetime_identifier ] = 0;
512
-        foreach ($tickets as $ticket_identifier) {
513
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
514
-                $datetime_identifier,
515
-                $reg_limit,
516
-                $ticket_identifier,
517
-                $spaces_allocated
518
-            );
519
-        }
520
-        // spaces can't be negative
521
-        $spaces_allocated = max($spaces_allocated, 0);
522
-        if ($spaces_allocated) {
523
-            // track any non-zero values
524
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
525
-            if ($this->debug) {
526
-                EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
527
-            }
528
-        } else {
529
-            if ($this->debug) {
530
-                EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
531
-            }
532
-        }
533
-        if ($this->debug) {
534
-            EEH_Debug_Tools::printr(
535
-                $this->total_spaces[ $datetime_identifier ],
536
-                '$total_spaces',
537
-                __FILE__,
538
-                __LINE__
539
-            );
540
-            EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
541
-            EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
542
-        }
543
-    }
544
-
545
-
546
-    /**
547
-     * @param string $datetime_identifier
548
-     * @param int|float $reg_limit
549
-     * @param string $ticket_identifier
550
-     * @param int|float $spaces_allocated
551
-     * @return int|float
552
-     */
553
-    private function calculateAvailableSpacesForTicket(
554
-        string $datetime_identifier,
555
-        $reg_limit,
556
-        string $ticket_identifier,
557
-        $spaces_allocated
558
-    ) {
559
-        // make sure ticket quantity is set
560
-        $ticket_quantity = $this->ticket_quantities[ $ticket_identifier ] ?? 0;
561
-        if ($this->debug) {
562
-            EEH_Debug_Tools::printr("$spaces_allocated", '$spaces_allocated', __FILE__, __LINE__);
563
-            EEH_Debug_Tools::printr(
564
-                "$ticket_quantity",
565
-                "ticket $ticket_identifier quantity: ",
566
-                __FILE__,
567
-                __LINE__,
568
-                2
569
-            );
570
-        }
571
-        if ($ticket_quantity) {
572
-            if ($this->debug) {
573
-                EEH_Debug_Tools::printr(
574
-                    ($spaces_allocated <= $reg_limit)
575
-                        ? 'true'
576
-                        : 'false',
577
-                    ' . spaces_allocated <= reg_limit = ',
578
-                    __FILE__,
579
-                    __LINE__
580
-                );
581
-            }
582
-            // if the datetime is NOT at full capacity yet
583
-            if ($spaces_allocated <= $reg_limit) {
584
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
585
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
586
-                //  or the maximum ticket quantity
587
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
588
-                // adjust the available quantity in our tracking array
589
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
590
-                // and increment spaces allocated for this datetime
591
-                $spaces_allocated += $ticket_quantity;
592
-                $at_capacity      = $spaces_allocated >= $reg_limit;
593
-                if ($this->debug) {
594
-                    EEH_Debug_Tools::printr(
595
-                        "$ticket_quantity $ticket_identifier tickets",
596
-                        ' > > allocate ',
597
-                        __FILE__,
598
-                        __LINE__,
599
-                        3
600
-                    );
601
-                    if ($at_capacity) {
602
-                        EEH_Debug_Tools::printr('AT CAPACITY', " . $datetime_identifier", __FILE__, __LINE__, 3);
603
-                    }
604
-                }
605
-                // now adjust all other datetimes that allow access to this ticket
606
-                $this->adjustDatetimes(
607
-                    $datetime_identifier,
608
-                    $ticket_identifier,
609
-                    $ticket_quantity,
610
-                    $at_capacity
611
-                );
612
-            }
613
-        }
614
-        return $spaces_allocated;
615
-    }
616
-
617
-
618
-    /**
619
-     * subtracts ticket amounts from all datetime reg limits
620
-     * that allow access to the ticket specified,
621
-     * because that ticket could be used
622
-     * to attend any of the datetimes it has access to
623
-     *
624
-     * @param string $datetime_identifier
625
-     * @param string $ticket_identifier
626
-     * @param bool   $at_capacity
627
-     * @param int|float $ticket_quantity
628
-     */
629
-    private function adjustDatetimes(
630
-        string $datetime_identifier,
631
-        string $ticket_identifier,
632
-        $ticket_quantity,
633
-        bool $at_capacity
634
-    ) {
635
-        /** @var array $datetime_tickets */
636
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
637
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
638
-                continue;
639
-            }
640
-            $adjusted = $this->adjustDatetimeSpaces(
641
-                $datetime_ID,
642
-                $ticket_identifier,
643
-                $ticket_quantity
644
-            );
645
-            // skip to next ticket if nothing changed
646
-            if (! ($adjusted || $at_capacity)) {
647
-                continue;
648
-            }
649
-            // then all of it's tickets are now unavailable
650
-            foreach ($datetime_tickets as $datetime_ticket) {
651
-                if (
652
-                    ($ticket_identifier === $datetime_ticket || $at_capacity)
653
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
654
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
655
-                ) {
656
-                    if ($this->debug) {
657
-                        EEH_Debug_Tools::printr(
658
-                            $datetime_ticket,
659
-                            ' . . . adjust ticket quantities for',
660
-                            __FILE__,
661
-                            __LINE__
662
-                        );
663
-                    }
664
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
665
-                    // otherwise just subtract the ticket quantity
666
-                    $new_quantity = $at_capacity
667
-                        ? 0
668
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
669
-                    // don't let ticket quantity go below zero
670
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
671
-                    if ($this->debug) {
672
-                        EEH_Debug_Tools::printr(
673
-                            $at_capacity
674
-                                ? "0 because Datetime $datetime_identifier is at capacity"
675
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
676
-                            " . . . . $datetime_ticket quantity set to ",
677
-                            __FILE__,
678
-                            __LINE__
679
-                        );
680
-                    }
681
-                }
682
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
683
-                if ($datetime_ticket === $ticket_identifier) {
684
-                    if (
685
-                        isset($this->ticket_datetimes[ $datetime_ticket ])
686
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
687
-                    ) {
688
-                        if ($this->debug) {
689
-                            EEH_Debug_Tools::printr(
690
-                                $datetime_ticket,
691
-                                ' . . adjust other Datetimes for',
692
-                                __FILE__,
693
-                                __LINE__
694
-                            );
695
-                        }
696
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
697
-                            // don't adjust the current datetime twice
698
-                            if ($datetime !== $datetime_identifier) {
699
-                                $this->adjustDatetimeSpaces(
700
-                                    $datetime,
701
-                                    $datetime_ticket,
702
-                                    $ticket_quantity
703
-                                );
704
-                            }
705
-                        }
706
-                    }
707
-                }
708
-            }
709
-        }
710
-    }
711
-
712
-
713
-    /**
714
-     * @param string $datetime_identifier
715
-     * @param string $ticket_identifier
716
-     * @param int|float $ticket_quantity
717
-     * @return bool
718
-     */
719
-    private function adjustDatetimeSpaces(
720
-        string $datetime_identifier,
721
-        string $ticket_identifier,
722
-        $ticket_quantity = 0
723
-    ): bool {
724
-        // does datetime have spaces available?
725
-        // and does the supplied ticket have access to this datetime ?
726
-        if (
727
-            $this->datetime_spaces[ $datetime_identifier ] > 0
728
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
729
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
730
-        ) {
731
-            if ($this->debug) {
732
-                EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
733
-                EEH_Debug_Tools::printr(
734
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
735
-                    " . . current  $datetime_identifier spaces available",
736
-                    __FILE__,
737
-                    __LINE__
738
-                );
739
-            }
740
-            // then decrement the available spaces for the datetime
741
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
742
-            // but don't let quantities go below zero
743
-            $this->datetime_spaces[ $datetime_identifier ] = max(
744
-                $this->datetime_spaces[ $datetime_identifier ],
745
-                0
746
-            );
747
-            if ($this->debug) {
748
-                EEH_Debug_Tools::printr(
749
-                    "$ticket_quantity",
750
-                    " . . . $datetime_identifier capacity reduced by",
751
-                    __FILE__,
752
-                    __LINE__
753
-                );
754
-            }
755
-            return true;
756
-        }
757
-        return false;
758
-    }
30
+	/**
31
+	 * @var EE_Event $event
32
+	 */
33
+	private $event;
34
+
35
+	/**
36
+	 * @var array $datetime_query_params
37
+	 */
38
+	private $datetime_query_params;
39
+
40
+	/**
41
+	 * @var EE_Ticket[] $active_tickets
42
+	 */
43
+	private $active_tickets = [];
44
+
45
+	/**
46
+	 * @var EE_Datetime[] $datetimes
47
+	 */
48
+	private $datetimes = [];
49
+
50
+	/**
51
+	 * Array of Ticket IDs grouped by Datetime
52
+	 *
53
+	 * @var array $datetimes
54
+	 */
55
+	private $datetime_tickets = [];
56
+
57
+	/**
58
+	 * Max spaces for each Datetime (reg limit - previous sold)
59
+	 *
60
+	 * @var array $datetime_spaces
61
+	 */
62
+	private $datetime_spaces = [];
63
+
64
+	/**
65
+	 * Array of Datetime IDs grouped by Ticket
66
+	 *
67
+	 * @var array[] $ticket_datetimes
68
+	 */
69
+	private $ticket_datetimes = [];
70
+
71
+	/**
72
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
73
+	 *
74
+	 * @var array $ticket_quantities
75
+	 */
76
+	private $ticket_quantities = [];
77
+
78
+	/**
79
+	 * total quantity of sold and reserved for each ticket
80
+	 *
81
+	 * @var array $tickets_sold
82
+	 */
83
+	private $tickets_sold = [];
84
+
85
+	/**
86
+	 * total spaces available across all datetimes
87
+	 *
88
+	 * @var array $total_spaces
89
+	 */
90
+	private $total_spaces = [];
91
+
92
+	/**
93
+	 * @var boolean $debug
94
+	 */
95
+	private $debug = false; // true false
96
+
97
+	/**
98
+	 * @var int|float|null $spaces_remaining
99
+	 */
100
+	private $spaces_remaining;
101
+
102
+	/**
103
+	 * @var int|float|null $total_spaces_available
104
+	 */
105
+	private $total_spaces_available;
106
+
107
+
108
+	/**
109
+	 * EventSpacesCalculator constructor.
110
+	 *
111
+	 * @param EE_Event $event
112
+	 * @param array    $datetime_query_params
113
+	 * @throws EE_Error
114
+	 * @throws ReflectionException
115
+	 */
116
+	public function __construct(EE_Event $event, array $datetime_query_params = [])
117
+	{
118
+		if ($this->debug) {
119
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
120
+			EEH_Debug_Tools::printr((string) $event->ID(), 'For event', __FILE__, __LINE__);
121
+		}
122
+		$this->event                 = $event;
123
+		$this->datetime_query_params = $datetime_query_params + ['order_by' => ['DTT_reg_limit' => 'ASC']];
124
+		$this->setHooks();
125
+	}
126
+
127
+
128
+	/**
129
+	 * @return void
130
+	 */
131
+	private function setHooks()
132
+	{
133
+		add_action('AHEE__EE_Ticket__increase_sold', [$this, 'clearResults']);
134
+		add_action('AHEE__EE_Ticket__decrease_sold', [$this, 'clearResults']);
135
+		add_action('AHEE__EE_Datetime__increase_sold', [$this, 'clearResults']);
136
+		add_action('AHEE__EE_Datetime__decrease_sold', [$this, 'clearResults']);
137
+		add_action('AHEE__EE_Ticket__increase_reserved', [$this, 'clearResults']);
138
+		add_action('AHEE__EE_Ticket__decrease_reserved', [$this, 'clearResults']);
139
+		add_action('AHEE__EE_Datetime__increase_reserved', [$this, 'clearResults']);
140
+		add_action('AHEE__EE_Datetime__decrease_reserved', [$this, 'clearResults']);
141
+	}
142
+
143
+
144
+	/**
145
+	 * @return void
146
+	 */
147
+	public function clearResults()
148
+	{
149
+		if ($this->debug) {
150
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
151
+		}
152
+		$this->spaces_remaining       = null;
153
+		$this->total_spaces_available = null;
154
+	}
155
+
156
+
157
+	/**
158
+	 * @return EE_Ticket[]
159
+	 * @throws EE_Error
160
+	 * @throws InvalidDataTypeException
161
+	 * @throws InvalidInterfaceException
162
+	 * @throws InvalidArgumentException
163
+	 * @throws ReflectionException
164
+	 */
165
+	public function getActiveTickets(): array
166
+	{
167
+		if (empty($this->active_tickets)) {
168
+			$this->active_tickets = $this->event->tickets(
169
+				[
170
+					['TKT_deleted' => false],
171
+					'order_by' => ['TKT_qty' => 'ASC'],
172
+				]
173
+			);
174
+		}
175
+		return $this->active_tickets;
176
+	}
177
+
178
+
179
+	/**
180
+	 * @param EE_Ticket[] $active_tickets
181
+	 * @throws EE_Error
182
+	 * @throws DomainException
183
+	 * @throws UnexpectedEntityException
184
+	 * @throws ReflectionException
185
+	 */
186
+	public function setActiveTickets(array $active_tickets = [])
187
+	{
188
+		if (! empty($active_tickets)) {
189
+			foreach ($active_tickets as $active_ticket) {
190
+				$this->validateTicket($active_ticket);
191
+			}
192
+			// sort incoming array by ticket quantity (asc)
193
+			usort(
194
+				$active_tickets,
195
+				function (EE_Ticket $a, EE_Ticket $b) {
196
+					if ($a->qty() === $b->qty()) {
197
+						return 0;
198
+					}
199
+					return ($a->qty() < $b->qty())
200
+						? -1
201
+						: 1;
202
+				}
203
+			);
204
+		}
205
+		$this->active_tickets = $active_tickets;
206
+	}
207
+
208
+
209
+	/**
210
+	 * @param $ticket
211
+	 * @throws DomainException
212
+	 * @throws EE_Error
213
+	 * @throws UnexpectedEntityException
214
+	 * @throws ReflectionException
215
+	 */
216
+	private function validateTicket($ticket)
217
+	{
218
+		if (! $ticket instanceof EE_Ticket) {
219
+			throw new DomainException(
220
+				esc_html__(
221
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
222
+					'event_espresso'
223
+				)
224
+			);
225
+		}
226
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
227
+			throw new DomainException(
228
+				sprintf(
229
+					esc_html__(
230
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
231
+						'event_espresso'
232
+					),
233
+					$ticket->get_event_ID(),
234
+					$this->event->ID()
235
+				)
236
+			);
237
+		}
238
+	}
239
+
240
+
241
+	/**
242
+	 * @return EE_Datetime[]
243
+	 */
244
+	public function getDatetimes(): array
245
+	{
246
+		return $this->datetimes;
247
+	}
248
+
249
+
250
+	/**
251
+	 * @param EE_Datetime $datetime
252
+	 * @throws EE_Error
253
+	 * @throws DomainException
254
+	 * @throws ReflectionException
255
+	 */
256
+	public function setDatetime(EE_Datetime $datetime)
257
+	{
258
+		if ($datetime->event()->ID() !== $this->event->ID()) {
259
+			throw new DomainException(
260
+				sprintf(
261
+					esc_html__(
262
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
263
+						'event_espresso'
264
+					),
265
+					$datetime->event()->ID(),
266
+					$this->event->ID()
267
+				)
268
+			);
269
+		}
270
+		$this->datetimes[ $datetime->ID() ] = $datetime;
271
+	}
272
+
273
+
274
+	/**
275
+	 * calculate spaces remaining based on "saleable" tickets
276
+	 *
277
+	 * @return int|float
278
+	 * @throws EE_Error
279
+	 * @throws DomainException
280
+	 * @throws UnexpectedEntityException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidArgumentException
284
+	 * @throws ReflectionException
285
+	 */
286
+	public function spacesRemaining()
287
+	{
288
+		if ($this->debug) {
289
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
290
+		}
291
+		if ($this->spaces_remaining === null) {
292
+			$this->initialize();
293
+			$this->spaces_remaining = $this->calculate();
294
+		}
295
+		return $this->spaces_remaining;
296
+	}
297
+
298
+
299
+	/**
300
+	 * calculates total available spaces for an event with no regard for sold tickets
301
+	 *
302
+	 * @return int|float
303
+	 * @throws EE_Error
304
+	 * @throws DomainException
305
+	 * @throws UnexpectedEntityException
306
+	 * @throws InvalidDataTypeException
307
+	 * @throws InvalidInterfaceException
308
+	 * @throws InvalidArgumentException
309
+	 * @throws ReflectionException
310
+	 */
311
+	public function totalSpacesAvailable()
312
+	{
313
+		if ($this->debug) {
314
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
315
+		}
316
+		if ($this->total_spaces_available === null) {
317
+			$this->initialize();
318
+			$this->total_spaces_available = $this->calculate(false);
319
+		}
320
+		return $this->total_spaces_available;
321
+	}
322
+
323
+
324
+	/**
325
+	 * Loops through the active tickets for the event
326
+	 * and builds a series of data arrays that will be used for calculating
327
+	 * the total maximum available spaces, as well as the spaces remaining.
328
+	 * Because ticket quantities affect datetime spaces and vice versa,
329
+	 * we need to be constantly updating these data arrays as things change,
330
+	 * which is the entire reason for their existence.
331
+	 *
332
+	 * @throws EE_Error
333
+	 * @throws DomainException
334
+	 * @throws UnexpectedEntityException
335
+	 * @throws InvalidDataTypeException
336
+	 * @throws InvalidInterfaceException
337
+	 * @throws InvalidArgumentException
338
+	 * @throws ReflectionException
339
+	 */
340
+	private function initialize()
341
+	{
342
+		if ($this->debug) {
343
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
344
+		}
345
+		$this->datetime_tickets  = [];
346
+		$this->datetime_spaces   = [];
347
+		$this->ticket_datetimes  = [];
348
+		$this->ticket_quantities = [];
349
+		$this->tickets_sold      = [];
350
+		$this->total_spaces      = [];
351
+		$active_tickets          = $this->getActiveTickets();
352
+		if (! empty($active_tickets)) {
353
+			foreach ($active_tickets as $ticket) {
354
+				$this->validateTicket($ticket);
355
+				// we need to index our data arrays using strings for the purpose of sorting,
356
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
357
+				$ticket_identifier = "T{$ticket->ID()}";
358
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket,
359
+				// unless the ticket is past its "sell until" date, in which case the qty will be 0
360
+				$max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
361
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
362
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
363
+				foreach ($ticket_datetimes as $datetime) {
364
+					// save all datetimes
365
+					$this->setDatetime($datetime);
366
+					$datetime_identifier = "D{$datetime->ID()}";
367
+					$reg_limit           = $datetime->reg_limit();
368
+					// ticket quantity can not exceed datetime reg limit
369
+					$max_tickets = min($max_tickets, $reg_limit);
370
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
371
+					// we are going to move all of our data into the following arrays:
372
+					// datetime spaces initially represents the reg limit for each datetime,
373
+					// but this will get adjusted as tickets are accounted for
374
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
375
+					// just an array of ticket IDs grouped by datetime
376
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
377
+					// and an array of datetime IDs grouped by ticket
378
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
379
+				}
380
+				// total quantity of sold and reserved for each ticket
381
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
382
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
383
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
384
+			}
385
+		}
386
+		// sort datetime spaces by reg limit, but maintain our string indexes
387
+		asort($this->datetime_spaces, SORT_NUMERIC);
388
+		// datetime tickets need to be sorted in the SAME order as the above array...
389
+		// so we'll just use array_merge() to take the structure of datetime_spaces
390
+		// but overwrite all of the data with that from datetime_tickets
391
+		$this->datetime_tickets = array_merge(
392
+			$this->datetime_spaces,
393
+			$this->datetime_tickets
394
+		);
395
+		if ($this->debug) {
396
+			EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
397
+			EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
398
+			EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
399
+		}
400
+	}
401
+
402
+
403
+	/**
404
+	 * performs calculations on initialized data
405
+	 *
406
+	 * @param bool $consider_sold
407
+	 * @return int|float
408
+	 */
409
+	private function calculate(bool $consider_sold = true)
410
+	{
411
+		if ($this->debug) {
412
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
413
+			EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
414
+		}
415
+		if ($consider_sold) {
416
+			// subtract amounts sold from all ticket quantities and datetime spaces
417
+			$this->adjustTicketQuantitiesDueToSales();
418
+		}
419
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
420
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
421
+		}
422
+		// total spaces available is just the sum of the spaces available for each datetime
423
+		$spaces_remaining = array_sum($this->total_spaces);
424
+		if ($this->debug) {
425
+			EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
426
+			EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
427
+			EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
428
+		}
429
+		return $spaces_remaining;
430
+	}
431
+
432
+
433
+	/**
434
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
435
+	 */
436
+	private function adjustTicketQuantitiesDueToSales()
437
+	{
438
+		if ($this->debug) {
439
+			EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
440
+		}
441
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
442
+			if (isset($this->ticket_quantities[ $ticket_identifier ])) {
443
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
444
+				// don't let values go below zero
445
+				$this->ticket_quantities[ $ticket_identifier ] = max(
446
+					$this->ticket_quantities[ $ticket_identifier ],
447
+					0
448
+				);
449
+				if ($this->debug) {
450
+					EEH_Debug_Tools::printr(
451
+						"$tickets_sold sales for ticket $ticket_identifier ",
452
+						'subtracting',
453
+						__FILE__,
454
+						__LINE__
455
+					);
456
+				}
457
+			}
458
+			if (
459
+				isset($this->ticket_datetimes[ $ticket_identifier ])
460
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
461
+			) {
462
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
463
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
464
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
465
+						// don't let values go below zero
466
+						$this->datetime_spaces[ $ticket_datetime ] = max(
467
+							$this->datetime_spaces[ $ticket_datetime ],
468
+							0
469
+						);
470
+						if ($this->debug) {
471
+							EEH_Debug_Tools::printr(
472
+								"$tickets_sold sales for datetime $ticket_datetime ",
473
+								'subtracting',
474
+								__FILE__,
475
+								__LINE__
476
+							);
477
+						}
478
+					}
479
+				}
480
+			}
481
+		}
482
+	}
483
+
484
+
485
+	/**
486
+	 * @param string $datetime_identifier
487
+	 * @param array  $tickets
488
+	 */
489
+	private function trackAvailableSpacesForDatetimes(string $datetime_identifier, array $tickets)
490
+	{
491
+		// make sure a reg limit is set for the datetime
492
+		$reg_limit = $this->datetime_spaces[ $datetime_identifier ] ?? 0;
493
+		// and bail if it is not
494
+		if (! $reg_limit) {
495
+			if ($this->debug) {
496
+				EEH_Debug_Tools::printr('AT CAPACITY', " . $datetime_identifier", __FILE__, __LINE__);
497
+			}
498
+			return;
499
+		}
500
+		if ($this->debug) {
501
+			EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
502
+			EEH_Debug_Tools::printr(
503
+				"$reg_limit",
504
+				'REG LIMIT',
505
+				__FILE__,
506
+				__LINE__
507
+			);
508
+		}
509
+		// number of allocated spaces always starts at zero
510
+		$spaces_allocated                           = 0;
511
+		$this->total_spaces[ $datetime_identifier ] = 0;
512
+		foreach ($tickets as $ticket_identifier) {
513
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
514
+				$datetime_identifier,
515
+				$reg_limit,
516
+				$ticket_identifier,
517
+				$spaces_allocated
518
+			);
519
+		}
520
+		// spaces can't be negative
521
+		$spaces_allocated = max($spaces_allocated, 0);
522
+		if ($spaces_allocated) {
523
+			// track any non-zero values
524
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
525
+			if ($this->debug) {
526
+				EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
527
+			}
528
+		} else {
529
+			if ($this->debug) {
530
+				EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
531
+			}
532
+		}
533
+		if ($this->debug) {
534
+			EEH_Debug_Tools::printr(
535
+				$this->total_spaces[ $datetime_identifier ],
536
+				'$total_spaces',
537
+				__FILE__,
538
+				__LINE__
539
+			);
540
+			EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
541
+			EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
542
+		}
543
+	}
544
+
545
+
546
+	/**
547
+	 * @param string $datetime_identifier
548
+	 * @param int|float $reg_limit
549
+	 * @param string $ticket_identifier
550
+	 * @param int|float $spaces_allocated
551
+	 * @return int|float
552
+	 */
553
+	private function calculateAvailableSpacesForTicket(
554
+		string $datetime_identifier,
555
+		$reg_limit,
556
+		string $ticket_identifier,
557
+		$spaces_allocated
558
+	) {
559
+		// make sure ticket quantity is set
560
+		$ticket_quantity = $this->ticket_quantities[ $ticket_identifier ] ?? 0;
561
+		if ($this->debug) {
562
+			EEH_Debug_Tools::printr("$spaces_allocated", '$spaces_allocated', __FILE__, __LINE__);
563
+			EEH_Debug_Tools::printr(
564
+				"$ticket_quantity",
565
+				"ticket $ticket_identifier quantity: ",
566
+				__FILE__,
567
+				__LINE__,
568
+				2
569
+			);
570
+		}
571
+		if ($ticket_quantity) {
572
+			if ($this->debug) {
573
+				EEH_Debug_Tools::printr(
574
+					($spaces_allocated <= $reg_limit)
575
+						? 'true'
576
+						: 'false',
577
+					' . spaces_allocated <= reg_limit = ',
578
+					__FILE__,
579
+					__LINE__
580
+				);
581
+			}
582
+			// if the datetime is NOT at full capacity yet
583
+			if ($spaces_allocated <= $reg_limit) {
584
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
585
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
586
+				//  or the maximum ticket quantity
587
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
588
+				// adjust the available quantity in our tracking array
589
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
590
+				// and increment spaces allocated for this datetime
591
+				$spaces_allocated += $ticket_quantity;
592
+				$at_capacity      = $spaces_allocated >= $reg_limit;
593
+				if ($this->debug) {
594
+					EEH_Debug_Tools::printr(
595
+						"$ticket_quantity $ticket_identifier tickets",
596
+						' > > allocate ',
597
+						__FILE__,
598
+						__LINE__,
599
+						3
600
+					);
601
+					if ($at_capacity) {
602
+						EEH_Debug_Tools::printr('AT CAPACITY', " . $datetime_identifier", __FILE__, __LINE__, 3);
603
+					}
604
+				}
605
+				// now adjust all other datetimes that allow access to this ticket
606
+				$this->adjustDatetimes(
607
+					$datetime_identifier,
608
+					$ticket_identifier,
609
+					$ticket_quantity,
610
+					$at_capacity
611
+				);
612
+			}
613
+		}
614
+		return $spaces_allocated;
615
+	}
616
+
617
+
618
+	/**
619
+	 * subtracts ticket amounts from all datetime reg limits
620
+	 * that allow access to the ticket specified,
621
+	 * because that ticket could be used
622
+	 * to attend any of the datetimes it has access to
623
+	 *
624
+	 * @param string $datetime_identifier
625
+	 * @param string $ticket_identifier
626
+	 * @param bool   $at_capacity
627
+	 * @param int|float $ticket_quantity
628
+	 */
629
+	private function adjustDatetimes(
630
+		string $datetime_identifier,
631
+		string $ticket_identifier,
632
+		$ticket_quantity,
633
+		bool $at_capacity
634
+	) {
635
+		/** @var array $datetime_tickets */
636
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
637
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
638
+				continue;
639
+			}
640
+			$adjusted = $this->adjustDatetimeSpaces(
641
+				$datetime_ID,
642
+				$ticket_identifier,
643
+				$ticket_quantity
644
+			);
645
+			// skip to next ticket if nothing changed
646
+			if (! ($adjusted || $at_capacity)) {
647
+				continue;
648
+			}
649
+			// then all of it's tickets are now unavailable
650
+			foreach ($datetime_tickets as $datetime_ticket) {
651
+				if (
652
+					($ticket_identifier === $datetime_ticket || $at_capacity)
653
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
654
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
655
+				) {
656
+					if ($this->debug) {
657
+						EEH_Debug_Tools::printr(
658
+							$datetime_ticket,
659
+							' . . . adjust ticket quantities for',
660
+							__FILE__,
661
+							__LINE__
662
+						);
663
+					}
664
+					// if this datetime is at full capacity, set any tracked available quantities to zero
665
+					// otherwise just subtract the ticket quantity
666
+					$new_quantity = $at_capacity
667
+						? 0
668
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
669
+					// don't let ticket quantity go below zero
670
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
671
+					if ($this->debug) {
672
+						EEH_Debug_Tools::printr(
673
+							$at_capacity
674
+								? "0 because Datetime $datetime_identifier is at capacity"
675
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
676
+							" . . . . $datetime_ticket quantity set to ",
677
+							__FILE__,
678
+							__LINE__
679
+						);
680
+					}
681
+				}
682
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
683
+				if ($datetime_ticket === $ticket_identifier) {
684
+					if (
685
+						isset($this->ticket_datetimes[ $datetime_ticket ])
686
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
687
+					) {
688
+						if ($this->debug) {
689
+							EEH_Debug_Tools::printr(
690
+								$datetime_ticket,
691
+								' . . adjust other Datetimes for',
692
+								__FILE__,
693
+								__LINE__
694
+							);
695
+						}
696
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
697
+							// don't adjust the current datetime twice
698
+							if ($datetime !== $datetime_identifier) {
699
+								$this->adjustDatetimeSpaces(
700
+									$datetime,
701
+									$datetime_ticket,
702
+									$ticket_quantity
703
+								);
704
+							}
705
+						}
706
+					}
707
+				}
708
+			}
709
+		}
710
+	}
711
+
712
+
713
+	/**
714
+	 * @param string $datetime_identifier
715
+	 * @param string $ticket_identifier
716
+	 * @param int|float $ticket_quantity
717
+	 * @return bool
718
+	 */
719
+	private function adjustDatetimeSpaces(
720
+		string $datetime_identifier,
721
+		string $ticket_identifier,
722
+		$ticket_quantity = 0
723
+	): bool {
724
+		// does datetime have spaces available?
725
+		// and does the supplied ticket have access to this datetime ?
726
+		if (
727
+			$this->datetime_spaces[ $datetime_identifier ] > 0
728
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
729
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
730
+		) {
731
+			if ($this->debug) {
732
+				EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
733
+				EEH_Debug_Tools::printr(
734
+					"{$this->datetime_spaces[ $datetime_identifier ]}",
735
+					" . . current  $datetime_identifier spaces available",
736
+					__FILE__,
737
+					__LINE__
738
+				);
739
+			}
740
+			// then decrement the available spaces for the datetime
741
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
742
+			// but don't let quantities go below zero
743
+			$this->datetime_spaces[ $datetime_identifier ] = max(
744
+				$this->datetime_spaces[ $datetime_identifier ],
745
+				0
746
+			);
747
+			if ($this->debug) {
748
+				EEH_Debug_Tools::printr(
749
+					"$ticket_quantity",
750
+					" . . . $datetime_identifier capacity reduced by",
751
+					__FILE__,
752
+					__LINE__
753
+				);
754
+			}
755
+			return true;
756
+		}
757
+		return false;
758
+	}
759 759
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -185,14 +185,14 @@  discard block
 block discarded – undo
185 185
      */
186 186
     public function setActiveTickets(array $active_tickets = [])
187 187
     {
188
-        if (! empty($active_tickets)) {
188
+        if ( ! empty($active_tickets)) {
189 189
             foreach ($active_tickets as $active_ticket) {
190 190
                 $this->validateTicket($active_ticket);
191 191
             }
192 192
             // sort incoming array by ticket quantity (asc)
193 193
             usort(
194 194
                 $active_tickets,
195
-                function (EE_Ticket $a, EE_Ticket $b) {
195
+                function(EE_Ticket $a, EE_Ticket $b) {
196 196
                     if ($a->qty() === $b->qty()) {
197 197
                         return 0;
198 198
                     }
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
      */
216 216
     private function validateTicket($ticket)
217 217
     {
218
-        if (! $ticket instanceof EE_Ticket) {
218
+        if ( ! $ticket instanceof EE_Ticket) {
219 219
             throw new DomainException(
220 220
                 esc_html__(
221 221
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
                 )
268 268
             );
269 269
         }
270
-        $this->datetimes[ $datetime->ID() ] = $datetime;
270
+        $this->datetimes[$datetime->ID()] = $datetime;
271 271
     }
272 272
 
273 273
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
         $this->tickets_sold      = [];
350 350
         $this->total_spaces      = [];
351 351
         $active_tickets          = $this->getActiveTickets();
352
-        if (! empty($active_tickets)) {
352
+        if ( ! empty($active_tickets)) {
353 353
             foreach ($active_tickets as $ticket) {
354 354
                 $this->validateTicket($ticket);
355 355
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -371,16 +371,16 @@  discard block
 block discarded – undo
371 371
                     // we are going to move all of our data into the following arrays:
372 372
                     // datetime spaces initially represents the reg limit for each datetime,
373 373
                     // but this will get adjusted as tickets are accounted for
374
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
374
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
375 375
                     // just an array of ticket IDs grouped by datetime
376
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
376
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
377 377
                     // and an array of datetime IDs grouped by ticket
378
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
378
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
379 379
                 }
380 380
                 // total quantity of sold and reserved for each ticket
381
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
381
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
382 382
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
383
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
383
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
384 384
             }
385 385
         }
386 386
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -439,11 +439,11 @@  discard block
 block discarded – undo
439 439
             EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
440 440
         }
441 441
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
442
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
443
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
442
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
443
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
444 444
                 // don't let values go below zero
445
-                $this->ticket_quantities[ $ticket_identifier ] = max(
446
-                    $this->ticket_quantities[ $ticket_identifier ],
445
+                $this->ticket_quantities[$ticket_identifier] = max(
446
+                    $this->ticket_quantities[$ticket_identifier],
447 447
                     0
448 448
                 );
449 449
                 if ($this->debug) {
@@ -456,15 +456,15 @@  discard block
 block discarded – undo
456 456
                 }
457 457
             }
458 458
             if (
459
-                isset($this->ticket_datetimes[ $ticket_identifier ])
460
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
459
+                isset($this->ticket_datetimes[$ticket_identifier])
460
+                && is_array($this->ticket_datetimes[$ticket_identifier])
461 461
             ) {
462
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
463
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
464
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
462
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
463
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
464
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
465 465
                         // don't let values go below zero
466
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
467
-                            $this->datetime_spaces[ $ticket_datetime ],
466
+                        $this->datetime_spaces[$ticket_datetime] = max(
467
+                            $this->datetime_spaces[$ticket_datetime],
468 468
                             0
469 469
                         );
470 470
                         if ($this->debug) {
@@ -489,9 +489,9 @@  discard block
 block discarded – undo
489 489
     private function trackAvailableSpacesForDatetimes(string $datetime_identifier, array $tickets)
490 490
     {
491 491
         // make sure a reg limit is set for the datetime
492
-        $reg_limit = $this->datetime_spaces[ $datetime_identifier ] ?? 0;
492
+        $reg_limit = $this->datetime_spaces[$datetime_identifier] ?? 0;
493 493
         // and bail if it is not
494
-        if (! $reg_limit) {
494
+        if ( ! $reg_limit) {
495 495
             if ($this->debug) {
496 496
                 EEH_Debug_Tools::printr('AT CAPACITY', " . $datetime_identifier", __FILE__, __LINE__);
497 497
             }
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
         }
509 509
         // number of allocated spaces always starts at zero
510 510
         $spaces_allocated                           = 0;
511
-        $this->total_spaces[ $datetime_identifier ] = 0;
511
+        $this->total_spaces[$datetime_identifier] = 0;
512 512
         foreach ($tickets as $ticket_identifier) {
513 513
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
514 514
                 $datetime_identifier,
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
         $spaces_allocated = max($spaces_allocated, 0);
522 522
         if ($spaces_allocated) {
523 523
             // track any non-zero values
524
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
524
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
525 525
             if ($this->debug) {
526 526
                 EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
527 527
             }
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
         }
533 533
         if ($this->debug) {
534 534
             EEH_Debug_Tools::printr(
535
-                $this->total_spaces[ $datetime_identifier ],
535
+                $this->total_spaces[$datetime_identifier],
536 536
                 '$total_spaces',
537 537
                 __FILE__,
538 538
                 __LINE__
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
         $spaces_allocated
558 558
     ) {
559 559
         // make sure ticket quantity is set
560
-        $ticket_quantity = $this->ticket_quantities[ $ticket_identifier ] ?? 0;
560
+        $ticket_quantity = $this->ticket_quantities[$ticket_identifier] ?? 0;
561 561
         if ($this->debug) {
562 562
             EEH_Debug_Tools::printr("$spaces_allocated", '$spaces_allocated', __FILE__, __LINE__);
563 563
             EEH_Debug_Tools::printr(
@@ -586,10 +586,10 @@  discard block
 block discarded – undo
586 586
                 //  or the maximum ticket quantity
587 587
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
588 588
                 // adjust the available quantity in our tracking array
589
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
589
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
590 590
                 // and increment spaces allocated for this datetime
591 591
                 $spaces_allocated += $ticket_quantity;
592
-                $at_capacity      = $spaces_allocated >= $reg_limit;
592
+                $at_capacity = $spaces_allocated >= $reg_limit;
593 593
                 if ($this->debug) {
594 594
                     EEH_Debug_Tools::printr(
595 595
                         "$ticket_quantity $ticket_identifier tickets",
@@ -643,15 +643,15 @@  discard block
 block discarded – undo
643 643
                 $ticket_quantity
644 644
             );
645 645
             // skip to next ticket if nothing changed
646
-            if (! ($adjusted || $at_capacity)) {
646
+            if ( ! ($adjusted || $at_capacity)) {
647 647
                 continue;
648 648
             }
649 649
             // then all of it's tickets are now unavailable
650 650
             foreach ($datetime_tickets as $datetime_ticket) {
651 651
                 if (
652 652
                     ($ticket_identifier === $datetime_ticket || $at_capacity)
653
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
654
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
653
+                    && isset($this->ticket_quantities[$datetime_ticket])
654
+                    && $this->ticket_quantities[$datetime_ticket] > 0
655 655
                 ) {
656 656
                     if ($this->debug) {
657 657
                         EEH_Debug_Tools::printr(
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
                     // otherwise just subtract the ticket quantity
666 666
                     $new_quantity = $at_capacity
667 667
                         ? 0
668
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
668
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
669 669
                     // don't let ticket quantity go below zero
670
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
670
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
671 671
                     if ($this->debug) {
672 672
                         EEH_Debug_Tools::printr(
673 673
                             $at_capacity
674 674
                                 ? "0 because Datetime $datetime_identifier is at capacity"
675
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
675
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
676 676
                             " . . . . $datetime_ticket quantity set to ",
677 677
                             __FILE__,
678 678
                             __LINE__
@@ -682,8 +682,8 @@  discard block
 block discarded – undo
682 682
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
683 683
                 if ($datetime_ticket === $ticket_identifier) {
684 684
                     if (
685
-                        isset($this->ticket_datetimes[ $datetime_ticket ])
686
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
685
+                        isset($this->ticket_datetimes[$datetime_ticket])
686
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
687 687
                     ) {
688 688
                         if ($this->debug) {
689 689
                             EEH_Debug_Tools::printr(
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
                                 __LINE__
694 694
                             );
695 695
                         }
696
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
696
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
697 697
                             // don't adjust the current datetime twice
698 698
                             if ($datetime !== $datetime_identifier) {
699 699
                                 $this->adjustDatetimeSpaces(
@@ -724,24 +724,24 @@  discard block
 block discarded – undo
724 724
         // does datetime have spaces available?
725 725
         // and does the supplied ticket have access to this datetime ?
726 726
         if (
727
-            $this->datetime_spaces[ $datetime_identifier ] > 0
728
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
729
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
727
+            $this->datetime_spaces[$datetime_identifier] > 0
728
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
729
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
730 730
         ) {
731 731
             if ($this->debug) {
732 732
                 EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
733 733
                 EEH_Debug_Tools::printr(
734
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
734
+                    "{$this->datetime_spaces[$datetime_identifier]}",
735 735
                     " . . current  $datetime_identifier spaces available",
736 736
                     __FILE__,
737 737
                     __LINE__
738 738
                 );
739 739
             }
740 740
             // then decrement the available spaces for the datetime
741
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
741
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
742 742
             // but don't let quantities go below zero
743
-            $this->datetime_spaces[ $datetime_identifier ] = max(
744
-                $this->datetime_spaces[ $datetime_identifier ],
743
+            $this->datetime_spaces[$datetime_identifier] = max(
744
+                $this->datetime_spaces[$datetime_identifier],
745 745
                 0
746 746
             );
747 747
             if ($this->debug) {
Please login to merge, or discard this patch.
core/db_models/EEM_Event.model.php 1 patch
Indentation   +964 added lines, -964 removed lines patch added patch discarded remove patch
@@ -13,968 +13,968 @@
 block discarded – undo
13 13
  */
14 14
 class EEM_Event extends EEM_CPT_Base
15 15
 {
16
-    /**
17
-     * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
18
-     * event
19
-     */
20
-    const sold_out = 'sold_out';
21
-
22
-    /**
23
-     * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
24
-     * date)
25
-     */
26
-    const postponed = 'postponed';
27
-
28
-    /**
29
-     * constant used by status(), indicating that the event will no longer occur
30
-     */
31
-    const cancelled = 'cancelled';
32
-
33
-
34
-    /**
35
-     * @var string
36
-     */
37
-    protected static $_default_reg_status;
38
-
39
-
40
-    /**
41
-     * This is the default for the additional limit field.
42
-     * @var int
43
-     */
44
-    protected static $_default_additional_limit = 10;
45
-
46
-
47
-    /**
48
-     * private instance of the Event object
49
-     *
50
-     * @var EEM_Event
51
-     */
52
-    protected static $_instance;
53
-
54
-
55
-    /**
56
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
57
-     *
58
-     * @param string $timezone
59
-     * @throws EE_Error
60
-     * @throws ReflectionException
61
-     */
62
-    protected function __construct($timezone = null)
63
-    {
64
-        EE_Registry::instance()->load_model('Registration');
65
-        $this->singular_item = esc_html__('Event', 'event_espresso');
66
-        $this->plural_item = esc_html__('Events', 'event_espresso');
67
-        // to remove Cancelled events from the frontend, copy the following filter to your functions.php file
68
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
69
-        // to remove Postponed events from the frontend, copy the following filter to your functions.php file
70
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
71
-        // to remove Sold Out events from the frontend, copy the following filter to your functions.php file
72
-        //  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
73
-        $this->_custom_stati = apply_filters(
74
-            'AFEE__EEM_Event__construct___custom_stati',
75
-            array(
76
-                EEM_Event::cancelled => array(
77
-                    'label'  => esc_html__('Cancelled', 'event_espresso'),
78
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
79
-                ),
80
-                EEM_Event::postponed => array(
81
-                    'label'  => esc_html__('Postponed', 'event_espresso'),
82
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
83
-                ),
84
-                EEM_Event::sold_out  => array(
85
-                    'label'  => esc_html__('Sold Out', 'event_espresso'),
86
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
87
-                ),
88
-            )
89
-        );
90
-        self::$_default_reg_status = empty(self::$_default_reg_status)
91
-            ? EEM_Registration::status_id_pending_payment
92
-            : self::$_default_reg_status;
93
-        $this->_tables = array(
94
-            'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
95
-            'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
96
-        );
97
-        $this->_fields = array(
98
-            'Event_CPT'  => array(
99
-                'EVT_ID'         => new EE_Primary_Key_Int_Field(
100
-                    'ID',
101
-                    esc_html__('Post ID for Event', 'event_espresso')
102
-                ),
103
-                'EVT_name'       => new EE_Plain_Text_Field(
104
-                    'post_title',
105
-                    esc_html__('Event Name', 'event_espresso'),
106
-                    false,
107
-                    ''
108
-                ),
109
-                'EVT_desc'       => new EE_Post_Content_Field(
110
-                    'post_content',
111
-                    esc_html__('Event Description', 'event_espresso'),
112
-                    false,
113
-                    ''
114
-                ),
115
-                'EVT_slug'       => new EE_Slug_Field(
116
-                    'post_name',
117
-                    esc_html__('Event Slug', 'event_espresso'),
118
-                    false,
119
-                    ''
120
-                ),
121
-                'EVT_created'    => new EE_Datetime_Field(
122
-                    'post_date',
123
-                    esc_html__('Date/Time Event Created', 'event_espresso'),
124
-                    false,
125
-                    EE_Datetime_Field::now
126
-                ),
127
-                'EVT_short_desc' => new EE_Simple_HTML_Field(
128
-                    'post_excerpt',
129
-                    esc_html__('Event Short Description', 'event_espresso'),
130
-                    false,
131
-                    ''
132
-                ),
133
-                'EVT_modified'   => new EE_Datetime_Field(
134
-                    'post_modified',
135
-                    esc_html__('Date/Time Event Modified', 'event_espresso'),
136
-                    false,
137
-                    EE_Datetime_Field::now
138
-                ),
139
-                'EVT_wp_user'    => new EE_WP_User_Field(
140
-                    'post_author',
141
-                    esc_html__('Event Creator ID', 'event_espresso'),
142
-                    false
143
-                ),
144
-                'parent'         => new EE_Integer_Field(
145
-                    'post_parent',
146
-                    esc_html__('Event Parent ID', 'event_espresso'),
147
-                    false,
148
-                    0
149
-                ),
150
-                'EVT_order'      => new EE_Integer_Field(
151
-                    'menu_order',
152
-                    esc_html__('Event Menu Order', 'event_espresso'),
153
-                    false,
154
-                    1
155
-                ),
156
-                'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
157
-                // EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
158
-                'status'         => new EE_WP_Post_Status_Field(
159
-                    'post_status',
160
-                    esc_html__('Event Status', 'event_espresso'),
161
-                    false,
162
-                    'draft',
163
-                    $this->_custom_stati
164
-                ),
165
-                'password' => new EE_Password_Field(
166
-                    'post_password',
167
-                    esc_html__('Password', 'event_espresso'),
168
-                    false,
169
-                    '',
170
-                    array(
171
-                        'EVT_desc',
172
-                        'EVT_short_desc',
173
-                        'EVT_display_desc',
174
-                        'EVT_display_ticket_selector',
175
-                        'EVT_visible_on',
176
-                        'EVT_additional_limit',
177
-                        'EVT_default_registration_status',
178
-                        'EVT_member_only',
179
-                        'EVT_phone',
180
-                        'EVT_allow_overflow',
181
-                        'EVT_timezone_string',
182
-                        'EVT_external_URL',
183
-                        'EVT_donations'
184
-                    )
185
-                )
186
-            ),
187
-            'Event_Meta' => array(
188
-                'EVTM_ID'                         => new EE_DB_Only_Float_Field(
189
-                    'EVTM_ID',
190
-                    esc_html__('Event Meta Row ID', 'event_espresso'),
191
-                    false
192
-                ),
193
-                'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
194
-                    'EVT_ID',
195
-                    esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
196
-                    false
197
-                ),
198
-                'VNU_ID' => new EE_Foreign_Key_Int_Field(
199
-                    'VNU_ID',
200
-                    __('Venue ID', 'event_espresso'),
201
-                    false,
202
-                    0,
203
-                    'Venue'
204
-                ),
205
-                'EVT_display_desc'                => new EE_Boolean_Field(
206
-                    'EVT_display_desc',
207
-                    esc_html__('Display Description Flag', 'event_espresso'),
208
-                    false,
209
-                    true
210
-                ),
211
-                'EVT_display_ticket_selector'     => new EE_Boolean_Field(
212
-                    'EVT_display_ticket_selector',
213
-                    esc_html__('Display Ticket Selector Flag', 'event_espresso'),
214
-                    false,
215
-                    true
216
-                ),
217
-                'EVT_visible_on'                  => new EE_Datetime_Field(
218
-                    'EVT_visible_on',
219
-                    esc_html__('Event Visible Date', 'event_espresso'),
220
-                    true,
221
-                    EE_Datetime_Field::now
222
-                ),
223
-                'EVT_additional_limit'            => new EE_Integer_Field(
224
-                    'EVT_additional_limit',
225
-                    esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
226
-                    false,
227
-                    self::$_default_additional_limit
228
-                ),
229
-                'EVT_default_registration_status' => new EE_Enum_Text_Field(
230
-                    'EVT_default_registration_status',
231
-                    esc_html__('Default Registration Status on this Event', 'event_espresso'),
232
-                    false,
233
-                    EEM_Event::$_default_reg_status,
234
-                    EEM_Registration::reg_status_array()
235
-                ),
236
-                'EVT_member_only'                 => new EE_Boolean_Field(
237
-                    'EVT_member_only',
238
-                    esc_html__('Member-Only Event Flag', 'event_espresso'),
239
-                    false,
240
-                    false
241
-                ),
242
-                'EVT_phone'                       => new EE_Plain_Text_Field(
243
-                    'EVT_phone',
244
-                    esc_html__('Event Phone Number', 'event_espresso'),
245
-                    false,
246
-                    ''
247
-                ),
248
-                'EVT_allow_overflow'              => new EE_Boolean_Field(
249
-                    'EVT_allow_overflow',
250
-                    esc_html__('Allow Overflow on Event', 'event_espresso'),
251
-                    false,
252
-                    false
253
-                ),
254
-                'EVT_timezone_string'             => new EE_Plain_Text_Field(
255
-                    'EVT_timezone_string',
256
-                    esc_html__('Timezone (name) for Event times', 'event_espresso'),
257
-                    false,
258
-                    ''
259
-                ),
260
-                'EVT_external_URL'                => new EE_Plain_Text_Field(
261
-                    'EVT_external_URL',
262
-                    esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
263
-                    true
264
-                ),
265
-                'EVT_donations'                   => new EE_Boolean_Field(
266
-                    'EVT_donations',
267
-                    esc_html__('Accept Donations?', 'event_espresso'),
268
-                    false,
269
-                    false
270
-                ),
271
-                'FSC_UUID'                        => new EE_Foreign_Key_String_Field(
272
-                    'FSC_UUID',
273
-                    esc_html__('Registration Form UUID (universally unique identifier)', 'event_espresso'),
274
-                    true,
275
-                    null,
276
-                    'Form_Section',
277
-                    false
278
-                ),
279
-            ),
280
-        );
281
-        $this->_model_relations = array(
282
-            'Attendee'               => new EE_HABTM_Relation('Registration'),
283
-            'Datetime'               => new EE_Has_Many_Relation(),
284
-            'Event_Question_Group'   => new EE_Has_Many_Relation(),
285
-            'Form_Section'           => new EE_Belongs_To_Relation(),
286
-            'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
287
-            'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
288
-            'Registration'           => new EE_Has_Many_Relation(),
289
-            'Term_Relationship'      => new EE_Has_Many_Relation(),
290
-            'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
291
-            'Venue'                  => new EE_Belongs_To_Relation(),
292
-            'WP_User'                => new EE_Belongs_To_Relation(),
293
-        );
294
-        // this model is generally available for reading
295
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
296
-        $this->model_chain_to_password = '';
297
-        parent::__construct($timezone);
298
-    }
299
-
300
-
301
-    /**
302
-     * @param string $default_reg_status
303
-     * @throws EE_Error
304
-     * @throws EE_Error
305
-     */
306
-    public static function set_default_reg_status($default_reg_status)
307
-    {
308
-        self::$_default_reg_status = $default_reg_status;
309
-        // if EEM_Event has already been instantiated,
310
-        // then we need to reset the `EVT_default_reg_status` field to use the new default.
311
-        if (self::$_instance instanceof EEM_Event) {
312
-            $default_reg_status = new EE_Enum_Text_Field(
313
-                'EVT_default_registration_status',
314
-                esc_html__('Default Registration Status on this Event', 'event_espresso'),
315
-                false,
316
-                $default_reg_status,
317
-                EEM_Registration::reg_status_array()
318
-            );
319
-            $default_reg_status->_construct_finalize(
320
-                'Event_Meta',
321
-                'EVT_default_registration_status',
322
-                'EEM_Event'
323
-            );
324
-            self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
325
-        }
326
-    }
327
-
328
-
329
-    /**
330
-     * Used to override the default for the additional limit field.
331
-     * @param $additional_limit
332
-     */
333
-    public static function set_default_additional_limit($additional_limit)
334
-    {
335
-        self::$_default_additional_limit = (int) $additional_limit;
336
-        if (self::$_instance instanceof EEM_Event) {
337
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
338
-                'EVT_additional_limit',
339
-                esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
340
-                false,
341
-                self::$_default_additional_limit
342
-            );
343
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
344
-                'Event_Meta',
345
-                'EVT_additional_limit',
346
-                'EEM_Event'
347
-            );
348
-        }
349
-    }
350
-
351
-
352
-    /**
353
-     * Return what is currently set as the default additional limit for the event.
354
-     * @return int
355
-     */
356
-    public static function get_default_additional_limit()
357
-    {
358
-        return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
359
-    }
360
-
361
-
362
-    /**
363
-     * get_question_groups
364
-     *
365
-     * @return array
366
-     * @throws EE_Error
367
-     * @throws ReflectionException
368
-     */
369
-    public function get_all_question_groups()
370
-    {
371
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
372
-            array(
373
-                array('QSG_deleted' => false),
374
-                'order_by' => array('QSG_order' => 'ASC'),
375
-            )
376
-        );
377
-    }
378
-
379
-
380
-    /**
381
-     * get_question_groups
382
-     *
383
-     * @param int $EVT_ID
384
-     * @return array|bool
385
-     * @throws EE_Error
386
-     * @throws ReflectionException
387
-     */
388
-    public function get_all_event_question_groups($EVT_ID = 0)
389
-    {
390
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
391
-            EE_Error::add_error(
392
-                esc_html__(
393
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
394
-                    'event_espresso'
395
-                ),
396
-                __FILE__,
397
-                __FUNCTION__,
398
-                __LINE__
399
-            );
400
-            return false;
401
-        }
402
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
403
-            array(
404
-                array('EVT_ID' => $EVT_ID),
405
-            )
406
-        );
407
-    }
408
-
409
-
410
-    /**
411
-     * get_question_groups
412
-     *
413
-     * @param int $EVT_ID
414
-     * @param boolean $for_primary_attendee
415
-     * @return array|bool
416
-     * @throws EE_Error
417
-     * @throws InvalidArgumentException
418
-     * @throws ReflectionException
419
-     * @throws InvalidDataTypeException
420
-     * @throws InvalidInterfaceException
421
-     */
422
-    public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
423
-    {
424
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
425
-            EE_Error::add_error(
426
-                esc_html__(
427
-                    // @codingStandardsIgnoreStart
428
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
429
-                    // @codingStandardsIgnoreEnd
430
-                    'event_espresso'
431
-                ),
432
-                __FILE__,
433
-                __FUNCTION__,
434
-                __LINE__
435
-            );
436
-            return false;
437
-        }
438
-        $query_params = [
439
-            [
440
-                'EVT_ID' => $EVT_ID,
441
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true
442
-            ]
443
-        ];
444
-        if ($for_primary_attendee) {
445
-            $query_params[0]['EQG_primary'] = true;
446
-        } else {
447
-            $query_params[0]['EQG_additional'] = true;
448
-        }
449
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
450
-    }
451
-
452
-
453
-    /**
454
-     * get_question_groups
455
-     *
456
-     * @param int $EVT_ID
457
-     * @param EE_Registration $registration
458
-     * @return array|bool
459
-     * @throws EE_Error
460
-     * @throws InvalidArgumentException
461
-     * @throws InvalidDataTypeException
462
-     * @throws InvalidInterfaceException
463
-     * @throws ReflectionException
464
-     */
465
-    public function get_question_groups_for_event($EVT_ID = 0, EE_Registration $registration)
466
-    {
467
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
468
-            EE_Error::add_error(
469
-                esc_html__(
470
-                    'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
471
-                    'event_espresso'
472
-                ),
473
-                __FILE__,
474
-                __FUNCTION__,
475
-                __LINE__
476
-            );
477
-            return false;
478
-        }
479
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
480
-            [
481
-                [
482
-                    'Event_Question_Group.EVT_ID'      => $EVT_ID,
483
-                    'Event_Question_Group.'
484
-                        . EEM_Event_Question_Group::instance()->fieldNameForContext(
485
-                            $registration->is_primary_registrant()
486
-                        ) => true
487
-                ],
488
-                'order_by' => ['QSG_order' => 'ASC'],
489
-            ]
490
-        );
491
-    }
492
-
493
-
494
-    /**
495
-     * get_question_target_db_column
496
-     *
497
-     * @param string $QSG_IDs csv list of $QSG IDs
498
-     * @return array|bool
499
-     * @throws EE_Error
500
-     * @throws ReflectionException
501
-     */
502
-    public function get_questions_in_groups($QSG_IDs = '')
503
-    {
504
-        if (empty($QSG_IDs)) {
505
-            EE_Error::add_error(
506
-                esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
507
-                __FILE__,
508
-                __FUNCTION__,
509
-                __LINE__
510
-            );
511
-            return false;
512
-        }
513
-        return EE_Registry::instance()->load_model('Question')->get_all(
514
-            array(
515
-                array(
516
-                    'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
517
-                    'QST_deleted'           => false,
518
-                    'QST_admin_only'        => is_admin(),
519
-                ),
520
-                'order_by' => 'QST_order',
521
-            )
522
-        );
523
-    }
524
-
525
-
526
-    /**
527
-     * get_options_for_question
528
-     *
529
-     * @param string $QST_IDs csv list of $QST IDs
530
-     * @return array|bool
531
-     * @throws EE_Error
532
-     * @throws ReflectionException
533
-     */
534
-    public function get_options_for_question($QST_IDs)
535
-    {
536
-        if (empty($QST_IDs)) {
537
-            EE_Error::add_error(
538
-                esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
539
-                __FILE__,
540
-                __FUNCTION__,
541
-                __LINE__
542
-            );
543
-            return false;
544
-        }
545
-        return EE_Registry::instance()->load_model('Question_Option')->get_all(
546
-            array(
547
-                array(
548
-                    'Question.QST_ID' => array('IN', $QST_IDs),
549
-                    'QSO_deleted'     => false,
550
-                ),
551
-                'order_by' => 'QSO_ID',
552
-            )
553
-        );
554
-    }
555
-
556
-
557
-    /**
558
-     * Gets all events that are published
559
-     * and have event start time earlier than now and an event end time later than now
560
-     *
561
-     * @param array $query_params  An array of query params to further filter on
562
-     *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
563
-     * @param bool  $count         whether to return the count or not (default FALSE)
564
-     * @return EE_Event[]|int
565
-     * @throws EE_Error
566
-     * @throws ReflectionException
567
-     */
568
-    public function get_active_events($query_params, $count = false)
569
-    {
570
-        if (array_key_exists(0, $query_params)) {
571
-            $where_params = $query_params[0];
572
-            unset($query_params[0]);
573
-        } else {
574
-            $where_params = array();
575
-        }
576
-        // if we have count make sure we don't include group by
577
-        if ($count && isset($query_params['group_by'])) {
578
-            unset($query_params['group_by']);
579
-        }
580
-        // let's add specific query_params for active_events
581
-        // keep in mind this will override any sent status in the query AND any date queries.
582
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
583
-        // if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
584
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
585
-            $where_params['Datetime.DTT_EVT_start******'] = array(
586
-                '<',
587
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
588
-            );
589
-        } else {
590
-            $where_params['Datetime.DTT_EVT_start'] = array(
591
-                '<',
592
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
593
-            );
594
-        }
595
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
596
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
597
-                '>',
598
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
599
-            );
600
-        } else {
601
-            $where_params['Datetime.DTT_EVT_end'] = array(
602
-                '>',
603
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
604
-            );
605
-        }
606
-        $query_params[0] = $where_params;
607
-        // don't use $query_params with count()
608
-        // because we don't want to include additional query clauses like "GROUP BY"
609
-        return $count
610
-            ? $this->count(array($where_params), 'EVT_ID', true)
611
-            : $this->get_all($query_params);
612
-    }
613
-
614
-
615
-    /**
616
-     * get all events that are published and have an event start time later than now
617
-     *
618
-     * @param array $query_params  An array of query params to further filter on
619
-     *                             (Note that status and DTT_EVT_start will be overridden)
620
-     * @param bool  $count         whether to return the count or not (default FALSE)
621
-     * @return EE_Event[]|int
622
-     * @throws EE_Error
623
-     * @throws ReflectionException
624
-     */
625
-    public function get_upcoming_events($query_params, $count = false)
626
-    {
627
-        if (array_key_exists(0, $query_params)) {
628
-            $where_params = $query_params[0];
629
-            unset($query_params[0]);
630
-        } else {
631
-            $where_params = array();
632
-        }
633
-        // if we have count make sure we don't include group by
634
-        if ($count && isset($query_params['group_by'])) {
635
-            unset($query_params['group_by']);
636
-        }
637
-        // let's add specific query_params for active_events
638
-        // keep in mind this will override any sent status in the query AND any date queries.
639
-        // we need to pull events with a status of publish and sold_out
640
-        $event_status = array('publish', EEM_Event::sold_out);
641
-        // check if the user can read private events and if so add the 'private status to the were params'
642
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
643
-            $event_status[] = 'private';
644
-        }
645
-        $where_params['status'] = array('IN', $event_status);
646
-        // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
647
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
648
-            $where_params['Datetime.DTT_EVT_start*****'] = array(
649
-                '>',
650
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
651
-            );
652
-        } else {
653
-            $where_params['Datetime.DTT_EVT_start'] = array(
654
-                '>',
655
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
656
-            );
657
-        }
658
-        $query_params[0] = $where_params;
659
-        // don't use $query_params with count()
660
-        // because we don't want to include additional query clauses like "GROUP BY"
661
-        return $count
662
-            ? $this->count(array($where_params), 'EVT_ID', true)
663
-            : $this->get_all($query_params);
664
-    }
665
-
666
-
667
-    /**
668
-     * Gets all events that are published
669
-     * and have an event end time later than now
670
-     *
671
-     * @param array $query_params  An array of query params to further filter on
672
-     *                             (note that status and DTT_EVT_end will be overridden)
673
-     * @param bool  $count         whether to return the count or not (default FALSE)
674
-     * @return EE_Event[]|int
675
-     * @throws EE_Error
676
-     * @throws ReflectionException
677
-     */
678
-    public function get_active_and_upcoming_events($query_params, $count = false)
679
-    {
680
-        if (array_key_exists(0, $query_params)) {
681
-            $where_params = $query_params[0];
682
-            unset($query_params[0]);
683
-        } else {
684
-            $where_params = array();
685
-        }
686
-        // if we have count make sure we don't include group by
687
-        if ($count && isset($query_params['group_by'])) {
688
-            unset($query_params['group_by']);
689
-        }
690
-        // let's add specific query_params for active_events
691
-        // keep in mind this will override any sent status in the query AND any date queries.
692
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
693
-        // add where params for DTT_EVT_end
694
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
695
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
696
-                '>',
697
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
698
-            );
699
-        } else {
700
-            $where_params['Datetime.DTT_EVT_end'] = array(
701
-                '>',
702
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
703
-            );
704
-        }
705
-        $query_params[0] = $where_params;
706
-        // don't use $query_params with count()
707
-        // because we don't want to include additional query clauses like "GROUP BY"
708
-        return $count
709
-            ? $this->count(array($where_params), 'EVT_ID', true)
710
-            : $this->get_all($query_params);
711
-    }
712
-
713
-
714
-    /**
715
-     * This only returns events that are expired.
716
-     * They may still be published but all their datetimes have expired.
717
-     *
718
-     * @param array $query_params  An array of query params to further filter on
719
-     *                             (note that status and DTT_EVT_end will be overridden)
720
-     * @param bool  $count         whether to return the count or not (default FALSE)
721
-     * @return EE_Event[]|int
722
-     * @throws EE_Error
723
-     * @throws ReflectionException
724
-     */
725
-    public function get_expired_events($query_params, $count = false)
726
-    {
727
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
728
-        // if we have count make sure we don't include group by
729
-        if ($count && isset($query_params['group_by'])) {
730
-            unset($query_params['group_by']);
731
-        }
732
-        // let's add specific query_params for active_events
733
-        // keep in mind this will override any sent status in the query AND any date queries.
734
-        if (isset($where_params['status'])) {
735
-            unset($where_params['status']);
736
-        }
737
-        $exclude_query = $query_params;
738
-        if (isset($exclude_query[0])) {
739
-            unset($exclude_query[0]);
740
-        }
741
-        $exclude_query[0] = array(
742
-            'Datetime.DTT_EVT_end' => array(
743
-                '>',
744
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
745
-            ),
746
-        );
747
-        // first get all events that have datetimes where its not expired.
748
-        $event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
749
-        $event_ids = array_keys($event_ids);
750
-        // if we have any additional query_params, let's add them to the 'AND' condition
751
-        $and_condition = array(
752
-            'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
753
-            'EVT_ID'               => array('NOT IN', $event_ids),
754
-        );
755
-        if (isset($where_params['OR'])) {
756
-            $and_condition['OR'] = $where_params['OR'];
757
-            unset($where_params['OR']);
758
-        }
759
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
760
-            $and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
761
-            unset($where_params['Datetime.DTT_EVT_end']);
762
-        }
763
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
764
-            $and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
765
-            unset($where_params['Datetime.DTT_EVT_start']);
766
-        }
767
-        // merge remaining $where params with the and conditions.
768
-        $where_params['AND'] = array_merge($and_condition, $where_params);
769
-        $query_params[0] = $where_params;
770
-        // don't use $query_params with count()
771
-        // because we don't want to include additional query clauses like "GROUP BY"
772
-        return $count
773
-            ? $this->count(array($where_params), 'EVT_ID', true)
774
-            : $this->get_all($query_params);
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * This basically just returns the events that do not have the publish status.
781
-     *
782
-     * @param  array   $query_params An array of query params to further filter on
783
-     *                               (note that status will be overwritten)
784
-     * @param  boolean $count        whether to return the count or not (default FALSE)
785
-     * @return EE_Event[]|int
786
-     * @throws EE_Error
787
-     */
788
-    public function get_inactive_events($query_params, $count = false)
789
-    {
790
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
791
-        // let's add in specific query_params for inactive events.
792
-        if (isset($where_params['status'])) {
793
-            unset($where_params['status']);
794
-        }
795
-        // if we have count make sure we don't include group by
796
-        if ($count && isset($query_params['group_by'])) {
797
-            unset($query_params['group_by']);
798
-        }
799
-        // if we have any additional query_params, let's add them to the 'AND' condition
800
-        $where_params['AND']['status'] = array('!=', 'publish');
801
-        if (isset($where_params['OR'])) {
802
-            $where_params['AND']['OR'] = $where_params['OR'];
803
-            unset($where_params['OR']);
804
-        }
805
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
806
-            $where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
807
-            unset($where_params['Datetime.DTT_EVT_end']);
808
-        }
809
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
810
-            $where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
811
-            unset($where_params['Datetime.DTT_EVT_start']);
812
-        }
813
-        $query_params[0] = $where_params;
814
-        // don't use $query_params with count()
815
-        // because we don't want to include additional query clauses like "GROUP BY"
816
-        return $count
817
-            ? $this->count(array($where_params), 'EVT_ID', true)
818
-            : $this->get_all($query_params);
819
-    }
820
-
821
-
822
-    /**
823
-     * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
824
-     * because we don't want to override any existing global default prices but instead insert NEW prices that get
825
-     * attached to the event. See parent for param descriptions
826
-     *
827
-     * @param        $id_or_obj
828
-     * @param        $other_model_id_or_obj
829
-     * @param string $relationName
830
-     * @param array  $where_query
831
-     * @return EE_Base_Class
832
-     * @throws EE_Error
833
-     * @throws ReflectionException
834
-     */
835
-    public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
836
-    {
837
-        if ($relationName === 'Price') {
838
-            // let's get the PRC object for the given ID to make sure that we aren't dealing with a default
839
-            $prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
840
-            // if EVT_ID = 0, then this is a default
841
-            if ((int) $prc_chk->get('EVT_ID') === 0) {
842
-                // let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
843
-                $prc_chk->set('PRC_ID', 0);
844
-            }
845
-            // run parent
846
-            return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
847
-        }
848
-        // otherwise carry on as normal
849
-        return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
850
-    }
851
-
852
-
853
-
854
-    /******************** DEPRECATED METHODS ********************/
855
-
856
-
857
-    /**
858
-     * _get_question_target_db_column
859
-     *
860
-     * @param EE_Registration $registration    (so existing answers for registration are included)
861
-     * @param int             $EVT_ID          so all question groups are included for event (not just answers from
862
-     *                                         registration).
863
-     * @return    array
864
-     * @throws ReflectionException
865
-     * @throws EE_Error*@deprecated as of 4.8.32.rc.001. Instead consider using
866
-     *                                         EE_Registration_Custom_Questions_Form located in
867
-     *                                         admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
868
-     * @access     public
869
-     */
870
-    public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
871
-    {
872
-        if (empty($EVT_ID)) {
873
-            throw new EE_Error(esc_html__(
874
-                'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
875
-                'event_espresso'
876
-            ));
877
-        }
878
-        $questions = array();
879
-        // get all question groups for event
880
-        $qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
881
-        if (! empty($qgs)) {
882
-            foreach ($qgs as $qg) {
883
-                $qsts = $qg->questions();
884
-                $questions[ $qg->ID() ] = $qg->model_field_array();
885
-                $questions[ $qg->ID() ]['QSG_questions'] = array();
886
-                foreach ($qsts as $qst) {
887
-                    if ($qst->is_system_question()) {
888
-                        continue;
889
-                    }
890
-                    $answer = EEM_Answer::instance()->get_one(array(
891
-                        array(
892
-                            'QST_ID' => $qst->ID(),
893
-                            'REG_ID' => $registration->ID(),
894
-                        ),
895
-                    ));
896
-                    $answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
897
-                    $qst_name = $qstn_id = $qst->ID();
898
-                    $ans_id = $answer->ID();
899
-                    $qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
900
-                    $input_name = '';
901
-                    $input_id = sanitize_key($qst->display_text());
902
-                    $input_class = '';
903
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ] = $qst->model_field_array();
904
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name'] = 'qstn'
905
-                                                                                           . $input_name
906
-                                                                                           . $qst_name;
907
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id'] = $input_id . '-' . $qstn_id;
908
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
909
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'] = array();
910
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj'] = $qst;
911
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj'] = $answer;
912
-                    // leave responses as-is, don't convert stuff into html entities please!
913
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
914
-                    if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
915
-                        $QSOs = $qst->options(true, $answer->value());
916
-                        if (is_array($QSOs)) {
917
-                            foreach ($QSOs as $QSO_ID => $QSO) {
918
-                                $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] = $QSO->model_field_array();
919
-                            }
920
-                        }
921
-                    }
922
-                }
923
-            }
924
-        }
925
-        return $questions;
926
-    }
927
-
928
-
929
-    /**
930
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
931
-     *                             or an stdClass where each property is the name of a column,
932
-     * @return EE_Base_Class
933
-     * @throws EE_Error
934
-     */
935
-    public function instantiate_class_from_array_or_object($cols_n_values)
936
-    {
937
-        $classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
938
-        if ($classInstance instanceof EE_Event) {
939
-            // events have their timezone defined in the DB, so use it immediately
940
-            $this->set_timezone($classInstance->get_timezone());
941
-        }
942
-        return $classInstance;
943
-    }
944
-
945
-
946
-    /**
947
-     * Deletes the model objects that meet the query params. Note: this method is overridden
948
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
949
-     * as archived, not actually deleted
950
-     *
951
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
952
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
953
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
954
-     *                                deletes regardless of other objects which may depend on it. Its generally
955
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
956
-     *                                DB
957
-     * @return int                    number of rows deleted
958
-     * @throws EE_Error
959
-     */
960
-    public function delete_permanently($query_params, $allow_blocking = true)
961
-    {
962
-        $deleted = parent::delete_permanently($query_params, $allow_blocking);
963
-        if ($deleted) {
964
-            // get list of events with no prices
965
-            $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', []);
966
-            $where = isset($query_params[0]) ? $query_params[0] : [];
967
-            $where_event = isset($where['EVT_ID']) ? $where['EVT_ID'] : ['', ''];
968
-            $where_event_ids = isset($where_event[1]) ? $where_event[1] : '';
969
-            $event_ids = is_string($where_event_ids)
970
-                ? explode(',', $where_event_ids)
971
-                : (array) $where_event_ids;
972
-            array_walk($event_ids, 'trim');
973
-            $event_ids = array_filter($event_ids);
974
-            // remove events from list of events with no prices
975
-            $espresso_no_ticket_prices = array_diff($espresso_no_ticket_prices, $event_ids);
976
-            update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
977
-        }
978
-        return $deleted;
979
-    }
16
+	/**
17
+	 * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
18
+	 * event
19
+	 */
20
+	const sold_out = 'sold_out';
21
+
22
+	/**
23
+	 * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
24
+	 * date)
25
+	 */
26
+	const postponed = 'postponed';
27
+
28
+	/**
29
+	 * constant used by status(), indicating that the event will no longer occur
30
+	 */
31
+	const cancelled = 'cancelled';
32
+
33
+
34
+	/**
35
+	 * @var string
36
+	 */
37
+	protected static $_default_reg_status;
38
+
39
+
40
+	/**
41
+	 * This is the default for the additional limit field.
42
+	 * @var int
43
+	 */
44
+	protected static $_default_additional_limit = 10;
45
+
46
+
47
+	/**
48
+	 * private instance of the Event object
49
+	 *
50
+	 * @var EEM_Event
51
+	 */
52
+	protected static $_instance;
53
+
54
+
55
+	/**
56
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
57
+	 *
58
+	 * @param string $timezone
59
+	 * @throws EE_Error
60
+	 * @throws ReflectionException
61
+	 */
62
+	protected function __construct($timezone = null)
63
+	{
64
+		EE_Registry::instance()->load_model('Registration');
65
+		$this->singular_item = esc_html__('Event', 'event_espresso');
66
+		$this->plural_item = esc_html__('Events', 'event_espresso');
67
+		// to remove Cancelled events from the frontend, copy the following filter to your functions.php file
68
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
69
+		// to remove Postponed events from the frontend, copy the following filter to your functions.php file
70
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
71
+		// to remove Sold Out events from the frontend, copy the following filter to your functions.php file
72
+		//  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
73
+		$this->_custom_stati = apply_filters(
74
+			'AFEE__EEM_Event__construct___custom_stati',
75
+			array(
76
+				EEM_Event::cancelled => array(
77
+					'label'  => esc_html__('Cancelled', 'event_espresso'),
78
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
79
+				),
80
+				EEM_Event::postponed => array(
81
+					'label'  => esc_html__('Postponed', 'event_espresso'),
82
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
83
+				),
84
+				EEM_Event::sold_out  => array(
85
+					'label'  => esc_html__('Sold Out', 'event_espresso'),
86
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
87
+				),
88
+			)
89
+		);
90
+		self::$_default_reg_status = empty(self::$_default_reg_status)
91
+			? EEM_Registration::status_id_pending_payment
92
+			: self::$_default_reg_status;
93
+		$this->_tables = array(
94
+			'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
95
+			'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
96
+		);
97
+		$this->_fields = array(
98
+			'Event_CPT'  => array(
99
+				'EVT_ID'         => new EE_Primary_Key_Int_Field(
100
+					'ID',
101
+					esc_html__('Post ID for Event', 'event_espresso')
102
+				),
103
+				'EVT_name'       => new EE_Plain_Text_Field(
104
+					'post_title',
105
+					esc_html__('Event Name', 'event_espresso'),
106
+					false,
107
+					''
108
+				),
109
+				'EVT_desc'       => new EE_Post_Content_Field(
110
+					'post_content',
111
+					esc_html__('Event Description', 'event_espresso'),
112
+					false,
113
+					''
114
+				),
115
+				'EVT_slug'       => new EE_Slug_Field(
116
+					'post_name',
117
+					esc_html__('Event Slug', 'event_espresso'),
118
+					false,
119
+					''
120
+				),
121
+				'EVT_created'    => new EE_Datetime_Field(
122
+					'post_date',
123
+					esc_html__('Date/Time Event Created', 'event_espresso'),
124
+					false,
125
+					EE_Datetime_Field::now
126
+				),
127
+				'EVT_short_desc' => new EE_Simple_HTML_Field(
128
+					'post_excerpt',
129
+					esc_html__('Event Short Description', 'event_espresso'),
130
+					false,
131
+					''
132
+				),
133
+				'EVT_modified'   => new EE_Datetime_Field(
134
+					'post_modified',
135
+					esc_html__('Date/Time Event Modified', 'event_espresso'),
136
+					false,
137
+					EE_Datetime_Field::now
138
+				),
139
+				'EVT_wp_user'    => new EE_WP_User_Field(
140
+					'post_author',
141
+					esc_html__('Event Creator ID', 'event_espresso'),
142
+					false
143
+				),
144
+				'parent'         => new EE_Integer_Field(
145
+					'post_parent',
146
+					esc_html__('Event Parent ID', 'event_espresso'),
147
+					false,
148
+					0
149
+				),
150
+				'EVT_order'      => new EE_Integer_Field(
151
+					'menu_order',
152
+					esc_html__('Event Menu Order', 'event_espresso'),
153
+					false,
154
+					1
155
+				),
156
+				'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
157
+				// EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
158
+				'status'         => new EE_WP_Post_Status_Field(
159
+					'post_status',
160
+					esc_html__('Event Status', 'event_espresso'),
161
+					false,
162
+					'draft',
163
+					$this->_custom_stati
164
+				),
165
+				'password' => new EE_Password_Field(
166
+					'post_password',
167
+					esc_html__('Password', 'event_espresso'),
168
+					false,
169
+					'',
170
+					array(
171
+						'EVT_desc',
172
+						'EVT_short_desc',
173
+						'EVT_display_desc',
174
+						'EVT_display_ticket_selector',
175
+						'EVT_visible_on',
176
+						'EVT_additional_limit',
177
+						'EVT_default_registration_status',
178
+						'EVT_member_only',
179
+						'EVT_phone',
180
+						'EVT_allow_overflow',
181
+						'EVT_timezone_string',
182
+						'EVT_external_URL',
183
+						'EVT_donations'
184
+					)
185
+				)
186
+			),
187
+			'Event_Meta' => array(
188
+				'EVTM_ID'                         => new EE_DB_Only_Float_Field(
189
+					'EVTM_ID',
190
+					esc_html__('Event Meta Row ID', 'event_espresso'),
191
+					false
192
+				),
193
+				'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
194
+					'EVT_ID',
195
+					esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
196
+					false
197
+				),
198
+				'VNU_ID' => new EE_Foreign_Key_Int_Field(
199
+					'VNU_ID',
200
+					__('Venue ID', 'event_espresso'),
201
+					false,
202
+					0,
203
+					'Venue'
204
+				),
205
+				'EVT_display_desc'                => new EE_Boolean_Field(
206
+					'EVT_display_desc',
207
+					esc_html__('Display Description Flag', 'event_espresso'),
208
+					false,
209
+					true
210
+				),
211
+				'EVT_display_ticket_selector'     => new EE_Boolean_Field(
212
+					'EVT_display_ticket_selector',
213
+					esc_html__('Display Ticket Selector Flag', 'event_espresso'),
214
+					false,
215
+					true
216
+				),
217
+				'EVT_visible_on'                  => new EE_Datetime_Field(
218
+					'EVT_visible_on',
219
+					esc_html__('Event Visible Date', 'event_espresso'),
220
+					true,
221
+					EE_Datetime_Field::now
222
+				),
223
+				'EVT_additional_limit'            => new EE_Integer_Field(
224
+					'EVT_additional_limit',
225
+					esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
226
+					false,
227
+					self::$_default_additional_limit
228
+				),
229
+				'EVT_default_registration_status' => new EE_Enum_Text_Field(
230
+					'EVT_default_registration_status',
231
+					esc_html__('Default Registration Status on this Event', 'event_espresso'),
232
+					false,
233
+					EEM_Event::$_default_reg_status,
234
+					EEM_Registration::reg_status_array()
235
+				),
236
+				'EVT_member_only'                 => new EE_Boolean_Field(
237
+					'EVT_member_only',
238
+					esc_html__('Member-Only Event Flag', 'event_espresso'),
239
+					false,
240
+					false
241
+				),
242
+				'EVT_phone'                       => new EE_Plain_Text_Field(
243
+					'EVT_phone',
244
+					esc_html__('Event Phone Number', 'event_espresso'),
245
+					false,
246
+					''
247
+				),
248
+				'EVT_allow_overflow'              => new EE_Boolean_Field(
249
+					'EVT_allow_overflow',
250
+					esc_html__('Allow Overflow on Event', 'event_espresso'),
251
+					false,
252
+					false
253
+				),
254
+				'EVT_timezone_string'             => new EE_Plain_Text_Field(
255
+					'EVT_timezone_string',
256
+					esc_html__('Timezone (name) for Event times', 'event_espresso'),
257
+					false,
258
+					''
259
+				),
260
+				'EVT_external_URL'                => new EE_Plain_Text_Field(
261
+					'EVT_external_URL',
262
+					esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
263
+					true
264
+				),
265
+				'EVT_donations'                   => new EE_Boolean_Field(
266
+					'EVT_donations',
267
+					esc_html__('Accept Donations?', 'event_espresso'),
268
+					false,
269
+					false
270
+				),
271
+				'FSC_UUID'                        => new EE_Foreign_Key_String_Field(
272
+					'FSC_UUID',
273
+					esc_html__('Registration Form UUID (universally unique identifier)', 'event_espresso'),
274
+					true,
275
+					null,
276
+					'Form_Section',
277
+					false
278
+				),
279
+			),
280
+		);
281
+		$this->_model_relations = array(
282
+			'Attendee'               => new EE_HABTM_Relation('Registration'),
283
+			'Datetime'               => new EE_Has_Many_Relation(),
284
+			'Event_Question_Group'   => new EE_Has_Many_Relation(),
285
+			'Form_Section'           => new EE_Belongs_To_Relation(),
286
+			'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
287
+			'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
288
+			'Registration'           => new EE_Has_Many_Relation(),
289
+			'Term_Relationship'      => new EE_Has_Many_Relation(),
290
+			'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
291
+			'Venue'                  => new EE_Belongs_To_Relation(),
292
+			'WP_User'                => new EE_Belongs_To_Relation(),
293
+		);
294
+		// this model is generally available for reading
295
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
296
+		$this->model_chain_to_password = '';
297
+		parent::__construct($timezone);
298
+	}
299
+
300
+
301
+	/**
302
+	 * @param string $default_reg_status
303
+	 * @throws EE_Error
304
+	 * @throws EE_Error
305
+	 */
306
+	public static function set_default_reg_status($default_reg_status)
307
+	{
308
+		self::$_default_reg_status = $default_reg_status;
309
+		// if EEM_Event has already been instantiated,
310
+		// then we need to reset the `EVT_default_reg_status` field to use the new default.
311
+		if (self::$_instance instanceof EEM_Event) {
312
+			$default_reg_status = new EE_Enum_Text_Field(
313
+				'EVT_default_registration_status',
314
+				esc_html__('Default Registration Status on this Event', 'event_espresso'),
315
+				false,
316
+				$default_reg_status,
317
+				EEM_Registration::reg_status_array()
318
+			);
319
+			$default_reg_status->_construct_finalize(
320
+				'Event_Meta',
321
+				'EVT_default_registration_status',
322
+				'EEM_Event'
323
+			);
324
+			self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
325
+		}
326
+	}
327
+
328
+
329
+	/**
330
+	 * Used to override the default for the additional limit field.
331
+	 * @param $additional_limit
332
+	 */
333
+	public static function set_default_additional_limit($additional_limit)
334
+	{
335
+		self::$_default_additional_limit = (int) $additional_limit;
336
+		if (self::$_instance instanceof EEM_Event) {
337
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
338
+				'EVT_additional_limit',
339
+				esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
340
+				false,
341
+				self::$_default_additional_limit
342
+			);
343
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
344
+				'Event_Meta',
345
+				'EVT_additional_limit',
346
+				'EEM_Event'
347
+			);
348
+		}
349
+	}
350
+
351
+
352
+	/**
353
+	 * Return what is currently set as the default additional limit for the event.
354
+	 * @return int
355
+	 */
356
+	public static function get_default_additional_limit()
357
+	{
358
+		return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
359
+	}
360
+
361
+
362
+	/**
363
+	 * get_question_groups
364
+	 *
365
+	 * @return array
366
+	 * @throws EE_Error
367
+	 * @throws ReflectionException
368
+	 */
369
+	public function get_all_question_groups()
370
+	{
371
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
372
+			array(
373
+				array('QSG_deleted' => false),
374
+				'order_by' => array('QSG_order' => 'ASC'),
375
+			)
376
+		);
377
+	}
378
+
379
+
380
+	/**
381
+	 * get_question_groups
382
+	 *
383
+	 * @param int $EVT_ID
384
+	 * @return array|bool
385
+	 * @throws EE_Error
386
+	 * @throws ReflectionException
387
+	 */
388
+	public function get_all_event_question_groups($EVT_ID = 0)
389
+	{
390
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
391
+			EE_Error::add_error(
392
+				esc_html__(
393
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
394
+					'event_espresso'
395
+				),
396
+				__FILE__,
397
+				__FUNCTION__,
398
+				__LINE__
399
+			);
400
+			return false;
401
+		}
402
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
403
+			array(
404
+				array('EVT_ID' => $EVT_ID),
405
+			)
406
+		);
407
+	}
408
+
409
+
410
+	/**
411
+	 * get_question_groups
412
+	 *
413
+	 * @param int $EVT_ID
414
+	 * @param boolean $for_primary_attendee
415
+	 * @return array|bool
416
+	 * @throws EE_Error
417
+	 * @throws InvalidArgumentException
418
+	 * @throws ReflectionException
419
+	 * @throws InvalidDataTypeException
420
+	 * @throws InvalidInterfaceException
421
+	 */
422
+	public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
423
+	{
424
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
425
+			EE_Error::add_error(
426
+				esc_html__(
427
+					// @codingStandardsIgnoreStart
428
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
429
+					// @codingStandardsIgnoreEnd
430
+					'event_espresso'
431
+				),
432
+				__FILE__,
433
+				__FUNCTION__,
434
+				__LINE__
435
+			);
436
+			return false;
437
+		}
438
+		$query_params = [
439
+			[
440
+				'EVT_ID' => $EVT_ID,
441
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true
442
+			]
443
+		];
444
+		if ($for_primary_attendee) {
445
+			$query_params[0]['EQG_primary'] = true;
446
+		} else {
447
+			$query_params[0]['EQG_additional'] = true;
448
+		}
449
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
450
+	}
451
+
452
+
453
+	/**
454
+	 * get_question_groups
455
+	 *
456
+	 * @param int $EVT_ID
457
+	 * @param EE_Registration $registration
458
+	 * @return array|bool
459
+	 * @throws EE_Error
460
+	 * @throws InvalidArgumentException
461
+	 * @throws InvalidDataTypeException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws ReflectionException
464
+	 */
465
+	public function get_question_groups_for_event($EVT_ID = 0, EE_Registration $registration)
466
+	{
467
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
468
+			EE_Error::add_error(
469
+				esc_html__(
470
+					'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
471
+					'event_espresso'
472
+				),
473
+				__FILE__,
474
+				__FUNCTION__,
475
+				__LINE__
476
+			);
477
+			return false;
478
+		}
479
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
480
+			[
481
+				[
482
+					'Event_Question_Group.EVT_ID'      => $EVT_ID,
483
+					'Event_Question_Group.'
484
+						. EEM_Event_Question_Group::instance()->fieldNameForContext(
485
+							$registration->is_primary_registrant()
486
+						) => true
487
+				],
488
+				'order_by' => ['QSG_order' => 'ASC'],
489
+			]
490
+		);
491
+	}
492
+
493
+
494
+	/**
495
+	 * get_question_target_db_column
496
+	 *
497
+	 * @param string $QSG_IDs csv list of $QSG IDs
498
+	 * @return array|bool
499
+	 * @throws EE_Error
500
+	 * @throws ReflectionException
501
+	 */
502
+	public function get_questions_in_groups($QSG_IDs = '')
503
+	{
504
+		if (empty($QSG_IDs)) {
505
+			EE_Error::add_error(
506
+				esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
507
+				__FILE__,
508
+				__FUNCTION__,
509
+				__LINE__
510
+			);
511
+			return false;
512
+		}
513
+		return EE_Registry::instance()->load_model('Question')->get_all(
514
+			array(
515
+				array(
516
+					'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
517
+					'QST_deleted'           => false,
518
+					'QST_admin_only'        => is_admin(),
519
+				),
520
+				'order_by' => 'QST_order',
521
+			)
522
+		);
523
+	}
524
+
525
+
526
+	/**
527
+	 * get_options_for_question
528
+	 *
529
+	 * @param string $QST_IDs csv list of $QST IDs
530
+	 * @return array|bool
531
+	 * @throws EE_Error
532
+	 * @throws ReflectionException
533
+	 */
534
+	public function get_options_for_question($QST_IDs)
535
+	{
536
+		if (empty($QST_IDs)) {
537
+			EE_Error::add_error(
538
+				esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
539
+				__FILE__,
540
+				__FUNCTION__,
541
+				__LINE__
542
+			);
543
+			return false;
544
+		}
545
+		return EE_Registry::instance()->load_model('Question_Option')->get_all(
546
+			array(
547
+				array(
548
+					'Question.QST_ID' => array('IN', $QST_IDs),
549
+					'QSO_deleted'     => false,
550
+				),
551
+				'order_by' => 'QSO_ID',
552
+			)
553
+		);
554
+	}
555
+
556
+
557
+	/**
558
+	 * Gets all events that are published
559
+	 * and have event start time earlier than now and an event end time later than now
560
+	 *
561
+	 * @param array $query_params  An array of query params to further filter on
562
+	 *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
563
+	 * @param bool  $count         whether to return the count or not (default FALSE)
564
+	 * @return EE_Event[]|int
565
+	 * @throws EE_Error
566
+	 * @throws ReflectionException
567
+	 */
568
+	public function get_active_events($query_params, $count = false)
569
+	{
570
+		if (array_key_exists(0, $query_params)) {
571
+			$where_params = $query_params[0];
572
+			unset($query_params[0]);
573
+		} else {
574
+			$where_params = array();
575
+		}
576
+		// if we have count make sure we don't include group by
577
+		if ($count && isset($query_params['group_by'])) {
578
+			unset($query_params['group_by']);
579
+		}
580
+		// let's add specific query_params for active_events
581
+		// keep in mind this will override any sent status in the query AND any date queries.
582
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
583
+		// if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
584
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
585
+			$where_params['Datetime.DTT_EVT_start******'] = array(
586
+				'<',
587
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
588
+			);
589
+		} else {
590
+			$where_params['Datetime.DTT_EVT_start'] = array(
591
+				'<',
592
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
593
+			);
594
+		}
595
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
596
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
597
+				'>',
598
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
599
+			);
600
+		} else {
601
+			$where_params['Datetime.DTT_EVT_end'] = array(
602
+				'>',
603
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
604
+			);
605
+		}
606
+		$query_params[0] = $where_params;
607
+		// don't use $query_params with count()
608
+		// because we don't want to include additional query clauses like "GROUP BY"
609
+		return $count
610
+			? $this->count(array($where_params), 'EVT_ID', true)
611
+			: $this->get_all($query_params);
612
+	}
613
+
614
+
615
+	/**
616
+	 * get all events that are published and have an event start time later than now
617
+	 *
618
+	 * @param array $query_params  An array of query params to further filter on
619
+	 *                             (Note that status and DTT_EVT_start will be overridden)
620
+	 * @param bool  $count         whether to return the count or not (default FALSE)
621
+	 * @return EE_Event[]|int
622
+	 * @throws EE_Error
623
+	 * @throws ReflectionException
624
+	 */
625
+	public function get_upcoming_events($query_params, $count = false)
626
+	{
627
+		if (array_key_exists(0, $query_params)) {
628
+			$where_params = $query_params[0];
629
+			unset($query_params[0]);
630
+		} else {
631
+			$where_params = array();
632
+		}
633
+		// if we have count make sure we don't include group by
634
+		if ($count && isset($query_params['group_by'])) {
635
+			unset($query_params['group_by']);
636
+		}
637
+		// let's add specific query_params for active_events
638
+		// keep in mind this will override any sent status in the query AND any date queries.
639
+		// we need to pull events with a status of publish and sold_out
640
+		$event_status = array('publish', EEM_Event::sold_out);
641
+		// check if the user can read private events and if so add the 'private status to the were params'
642
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
643
+			$event_status[] = 'private';
644
+		}
645
+		$where_params['status'] = array('IN', $event_status);
646
+		// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
647
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
648
+			$where_params['Datetime.DTT_EVT_start*****'] = array(
649
+				'>',
650
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
651
+			);
652
+		} else {
653
+			$where_params['Datetime.DTT_EVT_start'] = array(
654
+				'>',
655
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
656
+			);
657
+		}
658
+		$query_params[0] = $where_params;
659
+		// don't use $query_params with count()
660
+		// because we don't want to include additional query clauses like "GROUP BY"
661
+		return $count
662
+			? $this->count(array($where_params), 'EVT_ID', true)
663
+			: $this->get_all($query_params);
664
+	}
665
+
666
+
667
+	/**
668
+	 * Gets all events that are published
669
+	 * and have an event end time later than now
670
+	 *
671
+	 * @param array $query_params  An array of query params to further filter on
672
+	 *                             (note that status and DTT_EVT_end will be overridden)
673
+	 * @param bool  $count         whether to return the count or not (default FALSE)
674
+	 * @return EE_Event[]|int
675
+	 * @throws EE_Error
676
+	 * @throws ReflectionException
677
+	 */
678
+	public function get_active_and_upcoming_events($query_params, $count = false)
679
+	{
680
+		if (array_key_exists(0, $query_params)) {
681
+			$where_params = $query_params[0];
682
+			unset($query_params[0]);
683
+		} else {
684
+			$where_params = array();
685
+		}
686
+		// if we have count make sure we don't include group by
687
+		if ($count && isset($query_params['group_by'])) {
688
+			unset($query_params['group_by']);
689
+		}
690
+		// let's add specific query_params for active_events
691
+		// keep in mind this will override any sent status in the query AND any date queries.
692
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
693
+		// add where params for DTT_EVT_end
694
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
695
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
696
+				'>',
697
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
698
+			);
699
+		} else {
700
+			$where_params['Datetime.DTT_EVT_end'] = array(
701
+				'>',
702
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
703
+			);
704
+		}
705
+		$query_params[0] = $where_params;
706
+		// don't use $query_params with count()
707
+		// because we don't want to include additional query clauses like "GROUP BY"
708
+		return $count
709
+			? $this->count(array($where_params), 'EVT_ID', true)
710
+			: $this->get_all($query_params);
711
+	}
712
+
713
+
714
+	/**
715
+	 * This only returns events that are expired.
716
+	 * They may still be published but all their datetimes have expired.
717
+	 *
718
+	 * @param array $query_params  An array of query params to further filter on
719
+	 *                             (note that status and DTT_EVT_end will be overridden)
720
+	 * @param bool  $count         whether to return the count or not (default FALSE)
721
+	 * @return EE_Event[]|int
722
+	 * @throws EE_Error
723
+	 * @throws ReflectionException
724
+	 */
725
+	public function get_expired_events($query_params, $count = false)
726
+	{
727
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
728
+		// if we have count make sure we don't include group by
729
+		if ($count && isset($query_params['group_by'])) {
730
+			unset($query_params['group_by']);
731
+		}
732
+		// let's add specific query_params for active_events
733
+		// keep in mind this will override any sent status in the query AND any date queries.
734
+		if (isset($where_params['status'])) {
735
+			unset($where_params['status']);
736
+		}
737
+		$exclude_query = $query_params;
738
+		if (isset($exclude_query[0])) {
739
+			unset($exclude_query[0]);
740
+		}
741
+		$exclude_query[0] = array(
742
+			'Datetime.DTT_EVT_end' => array(
743
+				'>',
744
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
745
+			),
746
+		);
747
+		// first get all events that have datetimes where its not expired.
748
+		$event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
749
+		$event_ids = array_keys($event_ids);
750
+		// if we have any additional query_params, let's add them to the 'AND' condition
751
+		$and_condition = array(
752
+			'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
753
+			'EVT_ID'               => array('NOT IN', $event_ids),
754
+		);
755
+		if (isset($where_params['OR'])) {
756
+			$and_condition['OR'] = $where_params['OR'];
757
+			unset($where_params['OR']);
758
+		}
759
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
760
+			$and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
761
+			unset($where_params['Datetime.DTT_EVT_end']);
762
+		}
763
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
764
+			$and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
765
+			unset($where_params['Datetime.DTT_EVT_start']);
766
+		}
767
+		// merge remaining $where params with the and conditions.
768
+		$where_params['AND'] = array_merge($and_condition, $where_params);
769
+		$query_params[0] = $where_params;
770
+		// don't use $query_params with count()
771
+		// because we don't want to include additional query clauses like "GROUP BY"
772
+		return $count
773
+			? $this->count(array($where_params), 'EVT_ID', true)
774
+			: $this->get_all($query_params);
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * This basically just returns the events that do not have the publish status.
781
+	 *
782
+	 * @param  array   $query_params An array of query params to further filter on
783
+	 *                               (note that status will be overwritten)
784
+	 * @param  boolean $count        whether to return the count or not (default FALSE)
785
+	 * @return EE_Event[]|int
786
+	 * @throws EE_Error
787
+	 */
788
+	public function get_inactive_events($query_params, $count = false)
789
+	{
790
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
791
+		// let's add in specific query_params for inactive events.
792
+		if (isset($where_params['status'])) {
793
+			unset($where_params['status']);
794
+		}
795
+		// if we have count make sure we don't include group by
796
+		if ($count && isset($query_params['group_by'])) {
797
+			unset($query_params['group_by']);
798
+		}
799
+		// if we have any additional query_params, let's add them to the 'AND' condition
800
+		$where_params['AND']['status'] = array('!=', 'publish');
801
+		if (isset($where_params['OR'])) {
802
+			$where_params['AND']['OR'] = $where_params['OR'];
803
+			unset($where_params['OR']);
804
+		}
805
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
806
+			$where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
807
+			unset($where_params['Datetime.DTT_EVT_end']);
808
+		}
809
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
810
+			$where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
811
+			unset($where_params['Datetime.DTT_EVT_start']);
812
+		}
813
+		$query_params[0] = $where_params;
814
+		// don't use $query_params with count()
815
+		// because we don't want to include additional query clauses like "GROUP BY"
816
+		return $count
817
+			? $this->count(array($where_params), 'EVT_ID', true)
818
+			: $this->get_all($query_params);
819
+	}
820
+
821
+
822
+	/**
823
+	 * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
824
+	 * because we don't want to override any existing global default prices but instead insert NEW prices that get
825
+	 * attached to the event. See parent for param descriptions
826
+	 *
827
+	 * @param        $id_or_obj
828
+	 * @param        $other_model_id_or_obj
829
+	 * @param string $relationName
830
+	 * @param array  $where_query
831
+	 * @return EE_Base_Class
832
+	 * @throws EE_Error
833
+	 * @throws ReflectionException
834
+	 */
835
+	public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
836
+	{
837
+		if ($relationName === 'Price') {
838
+			// let's get the PRC object for the given ID to make sure that we aren't dealing with a default
839
+			$prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
840
+			// if EVT_ID = 0, then this is a default
841
+			if ((int) $prc_chk->get('EVT_ID') === 0) {
842
+				// let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
843
+				$prc_chk->set('PRC_ID', 0);
844
+			}
845
+			// run parent
846
+			return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
847
+		}
848
+		// otherwise carry on as normal
849
+		return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
850
+	}
851
+
852
+
853
+
854
+	/******************** DEPRECATED METHODS ********************/
855
+
856
+
857
+	/**
858
+	 * _get_question_target_db_column
859
+	 *
860
+	 * @param EE_Registration $registration    (so existing answers for registration are included)
861
+	 * @param int             $EVT_ID          so all question groups are included for event (not just answers from
862
+	 *                                         registration).
863
+	 * @return    array
864
+	 * @throws ReflectionException
865
+	 * @throws EE_Error*@deprecated as of 4.8.32.rc.001. Instead consider using
866
+	 *                                         EE_Registration_Custom_Questions_Form located in
867
+	 *                                         admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
868
+	 * @access     public
869
+	 */
870
+	public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
871
+	{
872
+		if (empty($EVT_ID)) {
873
+			throw new EE_Error(esc_html__(
874
+				'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
875
+				'event_espresso'
876
+			));
877
+		}
878
+		$questions = array();
879
+		// get all question groups for event
880
+		$qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
881
+		if (! empty($qgs)) {
882
+			foreach ($qgs as $qg) {
883
+				$qsts = $qg->questions();
884
+				$questions[ $qg->ID() ] = $qg->model_field_array();
885
+				$questions[ $qg->ID() ]['QSG_questions'] = array();
886
+				foreach ($qsts as $qst) {
887
+					if ($qst->is_system_question()) {
888
+						continue;
889
+					}
890
+					$answer = EEM_Answer::instance()->get_one(array(
891
+						array(
892
+							'QST_ID' => $qst->ID(),
893
+							'REG_ID' => $registration->ID(),
894
+						),
895
+					));
896
+					$answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
897
+					$qst_name = $qstn_id = $qst->ID();
898
+					$ans_id = $answer->ID();
899
+					$qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
900
+					$input_name = '';
901
+					$input_id = sanitize_key($qst->display_text());
902
+					$input_class = '';
903
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ] = $qst->model_field_array();
904
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name'] = 'qstn'
905
+																						   . $input_name
906
+																						   . $qst_name;
907
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id'] = $input_id . '-' . $qstn_id;
908
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
909
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'] = array();
910
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj'] = $qst;
911
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj'] = $answer;
912
+					// leave responses as-is, don't convert stuff into html entities please!
913
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
914
+					if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
915
+						$QSOs = $qst->options(true, $answer->value());
916
+						if (is_array($QSOs)) {
917
+							foreach ($QSOs as $QSO_ID => $QSO) {
918
+								$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] = $QSO->model_field_array();
919
+							}
920
+						}
921
+					}
922
+				}
923
+			}
924
+		}
925
+		return $questions;
926
+	}
927
+
928
+
929
+	/**
930
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
931
+	 *                             or an stdClass where each property is the name of a column,
932
+	 * @return EE_Base_Class
933
+	 * @throws EE_Error
934
+	 */
935
+	public function instantiate_class_from_array_or_object($cols_n_values)
936
+	{
937
+		$classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
938
+		if ($classInstance instanceof EE_Event) {
939
+			// events have their timezone defined in the DB, so use it immediately
940
+			$this->set_timezone($classInstance->get_timezone());
941
+		}
942
+		return $classInstance;
943
+	}
944
+
945
+
946
+	/**
947
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
948
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
949
+	 * as archived, not actually deleted
950
+	 *
951
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
952
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
953
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
954
+	 *                                deletes regardless of other objects which may depend on it. Its generally
955
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
956
+	 *                                DB
957
+	 * @return int                    number of rows deleted
958
+	 * @throws EE_Error
959
+	 */
960
+	public function delete_permanently($query_params, $allow_blocking = true)
961
+	{
962
+		$deleted = parent::delete_permanently($query_params, $allow_blocking);
963
+		if ($deleted) {
964
+			// get list of events with no prices
965
+			$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', []);
966
+			$where = isset($query_params[0]) ? $query_params[0] : [];
967
+			$where_event = isset($where['EVT_ID']) ? $where['EVT_ID'] : ['', ''];
968
+			$where_event_ids = isset($where_event[1]) ? $where_event[1] : '';
969
+			$event_ids = is_string($where_event_ids)
970
+				? explode(',', $where_event_ids)
971
+				: (array) $where_event_ids;
972
+			array_walk($event_ids, 'trim');
973
+			$event_ids = array_filter($event_ids);
974
+			// remove events from list of events with no prices
975
+			$espresso_no_ticket_prices = array_diff($espresso_no_ticket_prices, $event_ids);
976
+			update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
977
+		}
978
+		return $deleted;
979
+	}
980 980
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 1 patch
Indentation   +2134 added lines, -2134 removed lines patch added patch discarded remove patch
@@ -14,2142 +14,2142 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
16 16
 {
17
-    /**
18
-     * TicKet Archived:
19
-     * constant used by ticket_status() to indicate that a ticket is archived
20
-     * and no longer available for purchase
21
-     */
22
-    const archived = 'TKA';
23
-
24
-    /**
25
-     * TicKet Expired:
26
-     * constant used by ticket_status() to indicate that a ticket is expired
27
-     * and no longer available for purchase
28
-     */
29
-    const expired = 'TKE';
30
-
31
-    /**
32
-     * TicKet On sale:
33
-     * constant used by ticket_status() to indicate that a ticket is On Sale
34
-     * and IS available for purchase
35
-     */
36
-    const onsale = 'TKO';
37
-
38
-    /**
39
-     * TicKet Pending:
40
-     * constant used by ticket_status() to indicate that a ticket is pending
41
-     * and is NOT YET available for purchase
42
-     */
43
-    const pending = 'TKP';
44
-
45
-    /**
46
-     * TicKet Sold out:
47
-     * constant used by ticket_status() to indicate that a ticket is sold out
48
-     * and no longer available for purchases
49
-     */
50
-    const sold_out = 'TKS';
51
-
52
-    /**
53
-     * extra meta key for tracking ticket reservations
54
-     *
55
-     * @type string
56
-     */
57
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
-
59
-    /**
60
-     * override of parent property
61
-     *
62
-     * @var EEM_Ticket
63
-     */
64
-    protected $_model;
65
-
66
-    /**
67
-     * cached result from method of the same name
68
-     *
69
-     * @var float $_ticket_total_with_taxes
70
-     */
71
-    private $_ticket_total_with_taxes;
72
-
73
-    /**
74
-     * @var TicketPriceModifiers
75
-     */
76
-    protected $ticket_price_modifiers;
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values          incoming values
81
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
-     *                                        used.)
83
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
-     *                                        date_format and the second value is the time format
85
-     * @return EE_Ticket
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
-    {
91
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param array  $props_n_values  incoming values from the database
98
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
-     *                                the website will be used.
100
-     * @return EE_Ticket
101
-     * @throws EE_Error
102
-     * @throws ReflectionException
103
-     */
104
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
-    {
106
-        return new self($props_n_values, true, $timezone);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param array  $fieldValues
112
-     * @param false  $bydb
113
-     * @param string $timezone
114
-     * @param array  $date_formats
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
-    {
120
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
-        $this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
-    }
123
-
124
-
125
-    /**
126
-     * @return bool
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function parent()
131
-    {
132
-        return $this->get('TKT_parent');
133
-    }
134
-
135
-
136
-    /**
137
-     * return if a ticket has quantities available for purchase
138
-     *
139
-     * @param int $DTT_ID the primary key for a particular datetime
140
-     * @return boolean
141
-     * @throws EE_Error
142
-     * @throws ReflectionException
143
-     */
144
-    public function available($DTT_ID = 0)
145
-    {
146
-        // are we checking availability for a particular datetime ?
147
-        if ($DTT_ID) {
148
-            // get that datetime object
149
-            $datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
-            // if  ticket sales for this datetime have exceeded the reg limit...
151
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
-                return false;
153
-            }
154
-        }
155
-        // datetime is still open for registration, but is this ticket sold out ?
156
-        return $this->qty() < 1 || $this->qty() > $this->sold();
157
-    }
158
-
159
-
160
-    /**
161
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
-     *
163
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
-     *                               relevant status const
165
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
-     *                               further processing
167
-     * @return mixed status int if the display string isn't requested
168
-     * @throws EE_Error
169
-     * @throws ReflectionException
170
-     */
171
-    public function ticket_status($display = false, $remaining = null)
172
-    {
173
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
-        if (! $remaining) {
175
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
-        }
177
-        if ($this->get('TKT_deleted')) {
178
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
-        }
180
-        if ($this->is_expired()) {
181
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
-        }
183
-        if ($this->is_pending()) {
184
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
-        }
186
-        if ($this->is_on_sale()) {
187
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
-        }
189
-        return '';
190
-    }
191
-
192
-
193
-    /**
194
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
-     * considering ALL the factors used for figuring that out.
196
-     *
197
-     * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
-     * @return boolean         true = tickets remaining, false not.
199
-     * @throws EE_Error
200
-     * @throws ReflectionException
201
-     */
202
-    public function is_remaining($DTT_ID = 0)
203
-    {
204
-        $num_remaining = $this->remaining($DTT_ID);
205
-        if ($num_remaining === 0) {
206
-            return false;
207
-        }
208
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
-            return false;
210
-        }
211
-        return true;
212
-    }
213
-
214
-
215
-    /**
216
-     * return the total number of tickets available for purchase
217
-     *
218
-     * @param int $DTT_ID  the primary key for a particular datetime.
219
-     *                     set to 0 for all related datetimes
220
-     * @return int
221
-     * @throws EE_Error
222
-     * @throws ReflectionException
223
-     */
224
-    public function remaining($DTT_ID = 0)
225
-    {
226
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
-    }
228
-
229
-
230
-    /**
231
-     * Gets min
232
-     *
233
-     * @return int
234
-     * @throws EE_Error
235
-     * @throws ReflectionException
236
-     */
237
-    public function min()
238
-    {
239
-        return $this->get('TKT_min');
240
-    }
241
-
242
-
243
-    /**
244
-     * return if a ticket is no longer available cause its available dates have expired.
245
-     *
246
-     * @return boolean
247
-     * @throws EE_Error
248
-     * @throws ReflectionException
249
-     */
250
-    public function is_expired()
251
-    {
252
-        return ($this->get_raw('TKT_end_date') < time());
253
-    }
254
-
255
-
256
-    /**
257
-     * Return if a ticket is yet to go on sale or not
258
-     *
259
-     * @return boolean
260
-     * @throws EE_Error
261
-     * @throws ReflectionException
262
-     */
263
-    public function is_pending()
264
-    {
265
-        return ($this->get_raw('TKT_start_date') >= time());
266
-    }
267
-
268
-
269
-    /**
270
-     * Return if a ticket is on sale or not
271
-     *
272
-     * @return boolean
273
-     * @throws EE_Error
274
-     * @throws ReflectionException
275
-     */
276
-    public function is_on_sale()
277
-    {
278
-        return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
-    }
280
-
281
-
282
-    /**
283
-     * This returns the chronologically last datetime that this ticket is associated with
284
-     *
285
-     * @param string $date_format
286
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
-     *                            the end date ie: Jan 01 "to" Dec 31
288
-     * @return string
289
-     * @throws EE_Error
290
-     * @throws ReflectionException
291
-     */
292
-    public function date_range($date_format = '', $conjunction = ' - ')
293
-    {
294
-        $date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
-        $first_date  = $this->first_datetime() instanceof EE_Datetime
296
-            ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
-            : '';
298
-        $last_date   = $this->last_datetime() instanceof EE_Datetime
299
-            ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
-            : '';
301
-
302
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
-    }
304
-
305
-
306
-    /**
307
-     * This returns the chronologically first datetime that this ticket is associated with
308
-     *
309
-     * @return EE_Datetime
310
-     * @throws EE_Error
311
-     * @throws ReflectionException
312
-     */
313
-    public function first_datetime()
314
-    {
315
-        $datetimes = $this->datetimes(['limit' => 1]);
316
-        return reset($datetimes);
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets all the datetimes this ticket can be used for attending.
322
-     * Unless otherwise specified, orders datetimes by start date.
323
-     *
324
-     * @param array $query_params
325
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
-     * @return EE_Datetime[]|EE_Base_Class[]
327
-     * @throws EE_Error
328
-     * @throws ReflectionException
329
-     */
330
-    public function datetimes($query_params = [])
331
-    {
332
-        if (! isset($query_params['order_by'])) {
333
-            $query_params['order_by']['DTT_order'] = 'ASC';
334
-        }
335
-        return $this->get_many_related('Datetime', $query_params);
336
-    }
337
-
338
-
339
-    /**
340
-     * This returns the chronologically last datetime that this ticket is associated with
341
-     *
342
-     * @return EE_Datetime
343
-     * @throws EE_Error
344
-     * @throws ReflectionException
345
-     */
346
-    public function last_datetime()
347
-    {
348
-        $datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
-        return end($datetimes);
350
-    }
351
-
352
-
353
-    /**
354
-     * This returns the total tickets sold depending on the given parameters.
355
-     *
356
-     * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
360
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
-     * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
-     * @return mixed (array|int)          how many tickets have sold
364
-     * @throws EE_Error
365
-     * @throws ReflectionException
366
-     */
367
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
368
-    {
369
-        $total        = 0;
370
-        $tickets_sold = $this->_all_tickets_sold();
371
-        switch ($what) {
372
-            case 'ticket':
373
-                return $tickets_sold['ticket'];
374
-
375
-            case 'datetime':
376
-                if (empty($tickets_sold['datetime'])) {
377
-                    return $total;
378
-                }
379
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
-                    EE_Error::add_error(
381
-                        esc_html__(
382
-                            'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
-                            'event_espresso'
384
-                        ),
385
-                        __FILE__,
386
-                        __FUNCTION__,
387
-                        __LINE__
388
-                    );
389
-                    return $total;
390
-                }
391
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
-
393
-            default:
394
-                return $total;
395
-        }
396
-    }
397
-
398
-
399
-    /**
400
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
-     *
402
-     * @return EE_Ticket[]
403
-     * @throws EE_Error
404
-     * @throws ReflectionException
405
-     */
406
-    protected function _all_tickets_sold()
407
-    {
408
-        $datetimes    = $this->get_many_related('Datetime');
409
-        $tickets_sold = [];
410
-        if (! empty($datetimes)) {
411
-            foreach ($datetimes as $datetime) {
412
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
-            }
414
-        }
415
-        // Tickets sold
416
-        $tickets_sold['ticket'] = $this->sold();
417
-        return $tickets_sold;
418
-    }
419
-
420
-
421
-    /**
422
-     * This returns the base price object for the ticket.
423
-     *
424
-     * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function base_price(bool $return_array = false)
430
-    {
431
-        $base_price = $this->ticket_price_modifiers->getBasePrice();
432
-        if (! empty($base_price)) {
433
-            return $return_array ? $base_price : reset($base_price);
434
-        }
435
-        $_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
-        return $return_array
437
-            ? $this->get_many_related('Price', [$_where])
438
-            : $this->get_first_related('Price', [$_where]);
439
-    }
440
-
441
-
442
-    /**
443
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
-     *
445
-     * @return EE_Price[]
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     */
449
-    public function price_modifiers(): array
450
-    {
451
-        $price_modifiers = $this->usesGlobalTaxes()
452
-            ? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
-            : $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
-        if (! empty($price_modifiers)) {
455
-            return $price_modifiers;
456
-        }
457
-        return $this->prices(
458
-            [
459
-                [
460
-                    'Price_Type.PBT_ID' => [
461
-                        'NOT IN',
462
-                        [EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
-                    ]
464
-                ]
465
-            ]
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * This returns ONLY the TAX price modifiers for the ticket
472
-     *
473
-     * @return EE_Price[]
474
-     * @throws EE_Error
475
-     * @throws ReflectionException
476
-     */
477
-    public function tax_price_modifiers(): array
478
-    {
479
-        $tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
-        if (! empty($tax_price_modifiers)) {
481
-            return $tax_price_modifiers;
482
-        }
483
-        return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
-    }
485
-
486
-
487
-    /**
488
-     * Gets all the prices that combine to form the final price of this ticket
489
-     *
490
-     * @param array $query_params
491
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
-     * @return EE_Price[]|EE_Base_Class[]
493
-     * @throws EE_Error
494
-     * @throws ReflectionException
495
-     */
496
-    public function prices(array $query_params = []): array
497
-    {
498
-        if (! isset($query_params['order_by'])) {
499
-            $query_params['order_by']['PRC_order'] = 'ASC';
500
-        }
501
-        return $this->get_many_related('Price', $query_params);
502
-    }
503
-
504
-
505
-    /**
506
-     * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
-     *
508
-     * @param array $query_params
509
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function datetime_tickets($query_params = [])
515
-    {
516
-        return $this->get_many_related('Datetime_Ticket', $query_params);
517
-    }
518
-
519
-
520
-    /**
521
-     * Gets all the datetimes from the db ordered by DTT_order
522
-     *
523
-     * @param boolean $show_expired
524
-     * @param boolean $show_deleted
525
-     * @return EE_Datetime[]
526
-     * @throws EE_Error
527
-     * @throws ReflectionException
528
-     */
529
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
-    {
531
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
-            $this->ID(),
533
-            $show_expired,
534
-            $show_deleted
535
-        );
536
-    }
537
-
538
-
539
-    /**
540
-     * Gets ID
541
-     *
542
-     * @return int
543
-     * @throws EE_Error
544
-     * @throws ReflectionException
545
-     */
546
-    public function ID()
547
-    {
548
-        return (int) $this->get('TKT_ID');
549
-    }
550
-
551
-
552
-    /**
553
-     * get the author of the ticket.
554
-     *
555
-     * @return int
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     * @since 4.5.0
559
-     */
560
-    public function wp_user()
561
-    {
562
-        return $this->get('TKT_wp_user');
563
-    }
564
-
565
-
566
-    /**
567
-     * Gets the template for the ticket
568
-     *
569
-     * @return EE_Ticket_Template|EE_Base_Class
570
-     * @throws EE_Error
571
-     * @throws ReflectionException
572
-     */
573
-    public function template()
574
-    {
575
-        return $this->get_first_related('Ticket_Template');
576
-    }
577
-
578
-
579
-    /**
580
-     * Simply returns an array of EE_Price objects that are taxes.
581
-     *
582
-     * @return EE_Price[]
583
-     * @throws EE_Error
584
-     * @throws ReflectionException
585
-     */
586
-    public function get_ticket_taxes_for_admin(): array
587
-    {
588
-        return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
-    }
590
-
591
-
592
-    /**
593
-     * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
-     * as opposed to having tax price modifiers added directly to each ticket
595
-     *
596
-     * @return bool
597
-     * @throws EE_Error
598
-     * @throws ReflectionException
599
-     * @since   $VID:$
600
-     */
601
-    public function usesGlobalTaxes(): bool
602
-    {
603
-        return $this->taxable();
604
-    }
605
-
606
-
607
-    /**
608
-     * @return float
609
-     * @throws EE_Error
610
-     * @throws ReflectionException
611
-     */
612
-    public function ticket_price()
613
-    {
614
-        return $this->get('TKT_price');
615
-    }
616
-
617
-
618
-    /**
619
-     * @return mixed
620
-     * @throws EE_Error
621
-     * @throws ReflectionException
622
-     */
623
-    public function pretty_price()
624
-    {
625
-        return $this->get_pretty('TKT_price');
626
-    }
627
-
628
-
629
-    /**
630
-     * @return bool
631
-     * @throws EE_Error
632
-     * @throws ReflectionException
633
-     */
634
-    public function is_free()
635
-    {
636
-        return $this->get_ticket_total_with_taxes() === (float) 0;
637
-    }
638
-
639
-
640
-    /**
641
-     * get_ticket_total_with_taxes
642
-     *
643
-     * @param bool $no_cache
644
-     * @return float
645
-     * @throws EE_Error
646
-     * @throws ReflectionException
647
-     */
648
-    public function get_ticket_total_with_taxes($no_cache = false)
649
-    {
650
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
-            $this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
-                ? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
-                : $this->ticket_price();
654
-        }
655
-        return (float) $this->_ticket_total_with_taxes;
656
-    }
657
-
658
-
659
-    /**
660
-     * @throws EE_Error
661
-     * @throws ReflectionException
662
-     */
663
-    public function ensure_TKT_Price_correct()
664
-    {
665
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
-        $this->save();
667
-    }
668
-
669
-
670
-    /**
671
-     * @return float
672
-     * @throws EE_Error
673
-     * @throws ReflectionException
674
-     */
675
-    public function get_ticket_subtotal()
676
-    {
677
-        return EE_Taxes::get_subtotal_for_admin($this);
678
-    }
679
-
680
-
681
-    /**
682
-     * Returns the total taxes applied to this ticket
683
-     *
684
-     * @return float
685
-     * @throws EE_Error
686
-     * @throws ReflectionException
687
-     */
688
-    public function get_ticket_taxes_total_for_admin()
689
-    {
690
-        return EE_Taxes::get_total_taxes_for_admin($this);
691
-    }
692
-
693
-
694
-    /**
695
-     * Sets name
696
-     *
697
-     * @param string $name
698
-     * @throws EE_Error
699
-     * @throws ReflectionException
700
-     */
701
-    public function set_name($name)
702
-    {
703
-        $this->set('TKT_name', $name);
704
-    }
705
-
706
-
707
-    /**
708
-     * Gets description
709
-     *
710
-     * @return string
711
-     * @throws EE_Error
712
-     * @throws ReflectionException
713
-     */
714
-    public function description()
715
-    {
716
-        return $this->get('TKT_description');
717
-    }
718
-
719
-
720
-    /**
721
-     * Sets description
722
-     *
723
-     * @param string $description
724
-     * @throws EE_Error
725
-     * @throws ReflectionException
726
-     */
727
-    public function set_description($description)
728
-    {
729
-        $this->set('TKT_description', $description);
730
-    }
731
-
732
-
733
-    /**
734
-     * Gets start_date
735
-     *
736
-     * @param string $date_format
737
-     * @param string $time_format
738
-     * @return string
739
-     * @throws EE_Error
740
-     * @throws ReflectionException
741
-     */
742
-    public function start_date($date_format = '', $time_format = '')
743
-    {
744
-        return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
-    }
746
-
747
-
748
-    /**
749
-     * Sets start_date
750
-     *
751
-     * @param string $start_date
752
-     * @return void
753
-     * @throws EE_Error
754
-     * @throws ReflectionException
755
-     */
756
-    public function set_start_date($start_date)
757
-    {
758
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
759
-    }
760
-
761
-
762
-    /**
763
-     * Gets end_date
764
-     *
765
-     * @param string $date_format
766
-     * @param string $time_format
767
-     * @return string
768
-     * @throws EE_Error
769
-     * @throws ReflectionException
770
-     */
771
-    public function end_date($date_format = '', $time_format = '')
772
-    {
773
-        return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
-    }
775
-
776
-
777
-    /**
778
-     * Sets end_date
779
-     *
780
-     * @param string $end_date
781
-     * @return void
782
-     * @throws EE_Error
783
-     * @throws ReflectionException
784
-     */
785
-    public function set_end_date($end_date)
786
-    {
787
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
788
-    }
789
-
790
-
791
-    /**
792
-     * Sets sell until time
793
-     *
794
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
-     * @throws EE_Error
796
-     * @throws ReflectionException
797
-     * @since 4.5.0
798
-     */
799
-    public function set_end_time($time)
800
-    {
801
-        $this->_set_time_for($time, 'TKT_end_date');
802
-    }
803
-
804
-
805
-    /**
806
-     * Sets min
807
-     *
808
-     * @param int $min
809
-     * @return void
810
-     * @throws EE_Error
811
-     * @throws ReflectionException
812
-     */
813
-    public function set_min($min)
814
-    {
815
-        $this->set('TKT_min', $min);
816
-    }
817
-
818
-
819
-    /**
820
-     * Gets max
821
-     *
822
-     * @return int
823
-     * @throws EE_Error
824
-     * @throws ReflectionException
825
-     */
826
-    public function max()
827
-    {
828
-        return $this->get('TKT_max');
829
-    }
830
-
831
-
832
-    /**
833
-     * Sets max
834
-     *
835
-     * @param int $max
836
-     * @return void
837
-     * @throws EE_Error
838
-     * @throws ReflectionException
839
-     */
840
-    public function set_max($max)
841
-    {
842
-        $this->set('TKT_max', $max);
843
-    }
844
-
845
-
846
-    /**
847
-     * Sets price
848
-     *
849
-     * @param float $price
850
-     * @return void
851
-     * @throws EE_Error
852
-     * @throws ReflectionException
853
-     */
854
-    public function set_price($price)
855
-    {
856
-        $this->set('TKT_price', $price);
857
-    }
858
-
859
-
860
-    /**
861
-     * Gets sold
862
-     *
863
-     * @return int
864
-     * @throws EE_Error
865
-     * @throws ReflectionException
866
-     */
867
-    public function sold(): int
868
-    {
869
-        return (int) $this->get_raw('TKT_sold');
870
-    }
871
-
872
-
873
-    /**
874
-     * Sets sold
875
-     *
876
-     * @param int $sold
877
-     * @return void
878
-     * @throws EE_Error
879
-     * @throws ReflectionException
880
-     */
881
-    public function set_sold($sold)
882
-    {
883
-        // sold can not go below zero
884
-        $sold = max(0, $sold);
885
-        $this->set('TKT_sold', $sold);
886
-    }
887
-
888
-
889
-    /**
890
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
-     * associated datetimes.
892
-     *
893
-     * @param int $qty
894
-     * @return boolean
895
-     * @throws EE_Error
896
-     * @throws InvalidArgumentException
897
-     * @throws InvalidDataTypeException
898
-     * @throws InvalidInterfaceException
899
-     * @throws ReflectionException
900
-     * @since 4.9.80.p
901
-     */
902
-    public function increaseSold($qty = 1)
903
-    {
904
-        $qty = absint($qty);
905
-        // increment sold and decrement reserved datetime quantities simultaneously
906
-        // don't worry about failures, because they must have already had a spot reserved
907
-        $this->increaseSoldForDatetimes($qty);
908
-        // Increment and decrement ticket quantities simultaneously
909
-        $success = $this->adjustNumericFieldsInDb(
910
-            [
911
-                'TKT_reserved' => $qty * -1,
912
-                'TKT_sold'     => $qty,
913
-            ]
914
-        );
915
-        do_action(
916
-            'AHEE__EE_Ticket__increase_sold',
917
-            $this,
918
-            $qty,
919
-            $this->sold(),
920
-            $success
921
-        );
922
-        return $success;
923
-    }
924
-
925
-
926
-    /**
927
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
-     *
929
-     * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
-     *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
-     * @param EE_Datetime[] $datetimes
932
-     * @throws EE_Error
933
-     * @throws InvalidArgumentException
934
-     * @throws InvalidDataTypeException
935
-     * @throws InvalidInterfaceException
936
-     * @throws ReflectionException
937
-     * @since 4.9.80.p
938
-     */
939
-    protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
-    {
941
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
-        foreach ($datetimes as $datetime) {
943
-            $datetime->increaseSold($qty);
944
-        }
945
-    }
946
-
947
-
948
-    /**
949
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
-     * DB and then updates the model objects.
951
-     * Does not affect the reserved counts.
952
-     *
953
-     * @param int $qty
954
-     * @return boolean
955
-     * @throws EE_Error
956
-     * @throws InvalidArgumentException
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws ReflectionException
960
-     * @since 4.9.80.p
961
-     */
962
-    public function decreaseSold($qty = 1)
963
-    {
964
-        $qty = absint($qty);
965
-        $this->decreaseSoldForDatetimes($qty);
966
-        $success = $this->adjustNumericFieldsInDb(
967
-            [
968
-                'TKT_sold' => $qty * -1,
969
-            ]
970
-        );
971
-        do_action(
972
-            'AHEE__EE_Ticket__decrease_sold',
973
-            $this,
974
-            $qty,
975
-            $this->sold(),
976
-            $success
977
-        );
978
-        return $success;
979
-    }
980
-
981
-
982
-    /**
983
-     * Decreases sold on related datetimes
984
-     *
985
-     * @param int           $qty
986
-     * @param EE_Datetime[] $datetimes
987
-     * @return void
988
-     * @throws EE_Error
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidDataTypeException
991
-     * @throws InvalidInterfaceException
992
-     * @throws ReflectionException
993
-     * @since 4.9.80.p
994
-     */
995
-    protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
-    {
997
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
-        if (is_array($datetimes)) {
999
-            foreach ($datetimes as $datetime) {
1000
-                if ($datetime instanceof EE_Datetime) {
1001
-                    $datetime->decreaseSold($qty);
1002
-                }
1003
-            }
1004
-        }
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Gets qty of reserved tickets
1010
-     *
1011
-     * @return int
1012
-     * @throws EE_Error
1013
-     * @throws ReflectionException
1014
-     */
1015
-    public function reserved(): int
1016
-    {
1017
-        return (int) $this->get_raw('TKT_reserved');
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Sets reserved
1023
-     *
1024
-     * @param int $reserved
1025
-     * @return void
1026
-     * @throws EE_Error
1027
-     * @throws ReflectionException
1028
-     */
1029
-    public function set_reserved($reserved)
1030
-    {
1031
-        // reserved can not go below zero
1032
-        $reserved = max(0, (int) $reserved);
1033
-        $this->set('TKT_reserved', $reserved);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
-     *
1040
-     * @param int    $qty
1041
-     * @param string $source
1042
-     * @return bool whether we successfully reserved the ticket or not.
1043
-     * @throws EE_Error
1044
-     * @throws InvalidArgumentException
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws InvalidInterfaceException
1048
-     * @since 4.9.80.p
1049
-     */
1050
-    public function increaseReserved($qty = 1, $source = 'unknown')
1051
-    {
1052
-        $qty = absint($qty);
1053
-        do_action(
1054
-            'AHEE__EE_Ticket__increase_reserved__begin',
1055
-            $this,
1056
-            $qty,
1057
-            $source
1058
-        );
1059
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
-        $success                         = false;
1061
-        $datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
-        if ($datetimes_adjusted_successfully) {
1063
-            $success = $this->incrementFieldConditionallyInDb(
1064
-                'TKT_reserved',
1065
-                'TKT_sold',
1066
-                'TKT_qty',
1067
-                $qty
1068
-            );
1069
-            if (! $success) {
1070
-                // The datetimes were successfully bumped, but not the
1071
-                // ticket. So we need to manually rollback the datetimes.
1072
-                $this->decreaseReservedForDatetimes($qty);
1073
-            }
1074
-        }
1075
-        do_action(
1076
-            'AHEE__EE_Ticket__increase_reserved',
1077
-            $this,
1078
-            $qty,
1079
-            $this->reserved(),
1080
-            $success
1081
-        );
1082
-        return $success;
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * Increases reserved counts on related datetimes
1088
-     *
1089
-     * @param int           $qty
1090
-     * @param EE_Datetime[] $datetimes
1091
-     * @return boolean indicating success
1092
-     * @throws EE_Error
1093
-     * @throws InvalidArgumentException
1094
-     * @throws InvalidDataTypeException
1095
-     * @throws InvalidInterfaceException
1096
-     * @throws ReflectionException
1097
-     * @since 4.9.80.p
1098
-     */
1099
-    protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
-    {
1101
-        $datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
-        $datetimes_updated = [];
1103
-        $limit_exceeded    = false;
1104
-        if (is_array($datetimes)) {
1105
-            foreach ($datetimes as $datetime) {
1106
-                if ($datetime instanceof EE_Datetime) {
1107
-                    if ($datetime->increaseReserved($qty)) {
1108
-                        $datetimes_updated[] = $datetime;
1109
-                    } else {
1110
-                        $limit_exceeded = true;
1111
-                        break;
1112
-                    }
1113
-                }
1114
-            }
1115
-            // If somewhere along the way we detected a datetime whose
1116
-            // limit was exceeded, do a manual rollback.
1117
-            if ($limit_exceeded) {
1118
-                $this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
-                return false;
1120
-            }
1121
-        }
1122
-        return true;
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
-     *
1129
-     * @param int    $qty
1130
-     * @param bool   $adjust_datetimes
1131
-     * @param string $source
1132
-     * @return boolean
1133
-     * @throws EE_Error
1134
-     * @throws InvalidArgumentException
1135
-     * @throws ReflectionException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws InvalidInterfaceException
1138
-     * @since 4.9.80.p
1139
-     */
1140
-    public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
-    {
1142
-        $qty = absint($qty);
1143
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
-        if ($adjust_datetimes) {
1145
-            $this->decreaseReservedForDatetimes($qty);
1146
-        }
1147
-        $success = $this->adjustNumericFieldsInDb(
1148
-            [
1149
-                'TKT_reserved' => $qty * -1,
1150
-            ]
1151
-        );
1152
-        do_action(
1153
-            'AHEE__EE_Ticket__decrease_reserved',
1154
-            $this,
1155
-            $qty,
1156
-            $this->reserved(),
1157
-            $success
1158
-        );
1159
-        return $success;
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * Decreases the reserved count on the specified datetimes.
1165
-     *
1166
-     * @param int           $qty
1167
-     * @param EE_Datetime[] $datetimes
1168
-     * @throws EE_Error
1169
-     * @throws InvalidArgumentException
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws InvalidInterfaceException
1173
-     * @since 4.9.80.p
1174
-     */
1175
-    protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
-    {
1177
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
-        foreach ($datetimes as $datetime) {
1179
-            if ($datetime instanceof EE_Datetime) {
1180
-                $datetime->decreaseReserved($qty);
1181
-            }
1182
-        }
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets ticket quantity
1188
-     *
1189
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
-     * @return int
1196
-     * @throws EE_Error
1197
-     * @throws ReflectionException
1198
-     */
1199
-    public function qty($context = '')
1200
-    {
1201
-        switch ($context) {
1202
-            case 'reg_limit':
1203
-                return $this->real_quantity_on_ticket();
1204
-            case 'saleable':
1205
-                return $this->real_quantity_on_ticket('saleable');
1206
-            default:
1207
-                return $this->get_raw('TKT_qty');
1208
-        }
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * Gets ticket quantity
1214
-     *
1215
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
-     * @param int    $DTT_ID      the primary key for a particular datetime.
1221
-     *                            set to 0 for all related datetimes
1222
-     * @return int
1223
-     * @throws EE_Error
1224
-     * @throws ReflectionException
1225
-     */
1226
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
-    {
1228
-        $raw = $this->get_raw('TKT_qty');
1229
-        // return immediately if it's zero
1230
-        if ($raw === 0) {
1231
-            return $raw;
1232
-        }
1233
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
-        // ensure qty doesn't exceed raw value for THIS ticket
1235
-        $qty = min(EE_INF, $raw);
1236
-        // echo "\n . qty: " . $qty . '<br />';
1237
-        // calculate this ticket's total sales and reservations
1238
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
-        // echo "\n . sold: " . $this->sold() . '<br />';
1240
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1241
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
-        // first we need to calculate the maximum number of tickets available for the datetime
1243
-        // do we want data for one datetime or all of them ?
1244
-        $query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
-        $datetimes    = $this->datetimes($query_params);
1246
-        if (is_array($datetimes) && ! empty($datetimes)) {
1247
-            foreach ($datetimes as $datetime) {
1248
-                if ($datetime instanceof EE_Datetime) {
1249
-                    $datetime->refresh_from_db();
1250
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
-                    // initialize with no restrictions for each datetime
1253
-                    // but adjust datetime qty based on datetime reg limit
1254
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
-                    // and reservations for this datetime, that do NOT include sales and reservations
1259
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
-                    if ($context === 'saleable') {
1261
-                        $datetime_qty = max(
1262
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
-                            0
1264
-                        );
1265
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
-                    }
1272
-                    $qty = min($datetime_qty, $qty);
1273
-                    // echo "\n . . qty: " . $qty . '<br />';
1274
-                }
1275
-            }
1276
-        }
1277
-        // NOW that we know the  maximum number of tickets available for the datetime
1278
-        // we can finally factor in the details for this specific ticket
1279
-        if ($qty > 0 && $context === 'saleable') {
1280
-            // and subtract the sales for THIS ticket
1281
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
-            // echo "\n . qty: " . $qty . '<br />';
1283
-        }
1284
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
-        return $qty;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
-     *
1292
-     * @param int $qty
1293
-     * @return void
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function set_qty($qty)
1298
-    {
1299
-        $datetimes = $this->datetimes();
1300
-        foreach ($datetimes as $datetime) {
1301
-            if ($datetime instanceof EE_Datetime) {
1302
-                $qty = min($qty, $datetime->reg_limit());
1303
-            }
1304
-        }
1305
-        $this->set('TKT_qty', $qty);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * Gets uses
1311
-     *
1312
-     * @return int
1313
-     * @throws EE_Error
1314
-     * @throws ReflectionException
1315
-     */
1316
-    public function uses()
1317
-    {
1318
-        return $this->get('TKT_uses');
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * Sets uses
1324
-     *
1325
-     * @param int $uses
1326
-     * @return void
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     */
1330
-    public function set_uses($uses)
1331
-    {
1332
-        $this->set('TKT_uses', $uses);
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * returns whether ticket is required or not.
1338
-     *
1339
-     * @return boolean
1340
-     * @throws EE_Error
1341
-     * @throws ReflectionException
1342
-     */
1343
-    public function required()
1344
-    {
1345
-        return $this->get('TKT_required');
1346
-    }
1347
-
1348
-
1349
-    /**
1350
-     * sets the TKT_required property
1351
-     *
1352
-     * @param boolean $required
1353
-     * @return void
1354
-     * @throws EE_Error
1355
-     * @throws ReflectionException
1356
-     */
1357
-    public function set_required($required)
1358
-    {
1359
-        $this->set('TKT_required', $required);
1360
-    }
1361
-
1362
-
1363
-    /**
1364
-     * Gets taxable
1365
-     *
1366
-     * @return boolean
1367
-     * @throws EE_Error
1368
-     * @throws ReflectionException
1369
-     */
1370
-    public function taxable()
1371
-    {
1372
-        return $this->get('TKT_taxable');
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * Sets taxable
1378
-     *
1379
-     * @param boolean $taxable
1380
-     * @return void
1381
-     * @throws EE_Error
1382
-     * @throws ReflectionException
1383
-     */
1384
-    public function set_taxable($taxable)
1385
-    {
1386
-        $this->set('TKT_taxable', $taxable);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * Gets is_default
1392
-     *
1393
-     * @return boolean
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function is_default()
1398
-    {
1399
-        return $this->get('TKT_is_default');
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * Sets is_default
1405
-     *
1406
-     * @param boolean $is_default
1407
-     * @return void
1408
-     * @throws EE_Error
1409
-     * @throws ReflectionException
1410
-     */
1411
-    public function set_is_default($is_default)
1412
-    {
1413
-        $this->set('TKT_is_default', $is_default);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Gets order
1419
-     *
1420
-     * @return int
1421
-     * @throws EE_Error
1422
-     * @throws ReflectionException
1423
-     */
1424
-    public function order()
1425
-    {
1426
-        return $this->get('TKT_order');
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * Sets order
1432
-     *
1433
-     * @param int $order
1434
-     * @return void
1435
-     * @throws EE_Error
1436
-     * @throws ReflectionException
1437
-     */
1438
-    public function set_order($order)
1439
-    {
1440
-        $this->set('TKT_order', $order);
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Gets row
1446
-     *
1447
-     * @return int
1448
-     * @throws EE_Error
1449
-     * @throws ReflectionException
1450
-     */
1451
-    public function row()
1452
-    {
1453
-        return $this->get('TKT_row');
1454
-    }
1455
-
1456
-
1457
-    /**
1458
-     * Sets row
1459
-     *
1460
-     * @param int $row
1461
-     * @return void
1462
-     * @throws EE_Error
1463
-     * @throws ReflectionException
1464
-     */
1465
-    public function set_row($row)
1466
-    {
1467
-        $this->set('TKT_row', $row);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Gets deleted
1473
-     *
1474
-     * @return boolean
1475
-     * @throws EE_Error
1476
-     * @throws ReflectionException
1477
-     */
1478
-    public function deleted()
1479
-    {
1480
-        return $this->get('TKT_deleted');
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * Sets deleted
1486
-     *
1487
-     * @param boolean $deleted
1488
-     * @return void
1489
-     * @throws EE_Error
1490
-     * @throws ReflectionException
1491
-     */
1492
-    public function set_deleted($deleted)
1493
-    {
1494
-        $this->set('TKT_deleted', $deleted);
1495
-    }
1496
-
1497
-
1498
-    /**
1499
-     * Gets parent
1500
-     *
1501
-     * @return int
1502
-     * @throws EE_Error
1503
-     * @throws ReflectionException
1504
-     */
1505
-    public function parent_ID()
1506
-    {
1507
-        return $this->get('TKT_parent');
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Sets parent
1513
-     *
1514
-     * @param int $parent
1515
-     * @return void
1516
-     * @throws EE_Error
1517
-     * @throws ReflectionException
1518
-     */
1519
-    public function set_parent_ID($parent)
1520
-    {
1521
-        $this->set('TKT_parent', $parent);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * @return boolean
1527
-     * @throws EE_Error
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidDataTypeException
1530
-     * @throws InvalidInterfaceException
1531
-     * @throws ReflectionException
1532
-     */
1533
-    public function reverse_calculate()
1534
-    {
1535
-        return $this->get('TKT_reverse_calculate');
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * @param boolean $reverse_calculate
1541
-     * @throws EE_Error
1542
-     * @throws InvalidArgumentException
1543
-     * @throws InvalidDataTypeException
1544
-     * @throws InvalidInterfaceException
1545
-     * @throws ReflectionException
1546
-     */
1547
-    public function set_reverse_calculate($reverse_calculate)
1548
-    {
1549
-        $this->set('TKT_reverse_calculate', $reverse_calculate);
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
-     *
1556
-     * @return string
1557
-     * @throws EE_Error
1558
-     * @throws ReflectionException
1559
-     */
1560
-    public function name_and_info()
1561
-    {
1562
-        $times = [];
1563
-        foreach ($this->datetimes() as $datetime) {
1564
-            $times[] = $datetime->start_date_and_time();
1565
-        }
1566
-        return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1567
-    }
1568
-
1569
-
1570
-    /**
1571
-     * Gets name
1572
-     *
1573
-     * @return string
1574
-     * @throws EE_Error
1575
-     * @throws ReflectionException
1576
-     */
1577
-    public function name()
1578
-    {
1579
-        return $this->get('TKT_name');
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets price
1585
-     *
1586
-     * @return float
1587
-     * @throws EE_Error
1588
-     * @throws ReflectionException
1589
-     */
1590
-    public function price()
1591
-    {
1592
-        return $this->get('TKT_price');
1593
-    }
1594
-
1595
-
1596
-    /**
1597
-     * Gets all the registrations for this ticket
1598
-     *
1599
-     * @param array $query_params
1600
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1601
-     * @return EE_Registration[]|EE_Base_Class[]
1602
-     * @throws EE_Error
1603
-     * @throws ReflectionException
1604
-     */
1605
-    public function registrations($query_params = [])
1606
-    {
1607
-        return $this->get_many_related('Registration', $query_params);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1613
-     *
1614
-     * @return int
1615
-     * @throws EE_Error
1616
-     * @throws ReflectionException
1617
-     */
1618
-    public function update_tickets_sold()
1619
-    {
1620
-        $count_regs_for_this_ticket = $this->count_registrations(
1621
-            [
1622
-                [
1623
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1624
-                    'REG_deleted' => 0,
1625
-                ],
1626
-            ]
1627
-        );
1628
-        $this->set_sold($count_regs_for_this_ticket);
1629
-        $this->save();
1630
-        return $count_regs_for_this_ticket;
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Counts the registrations for this ticket
1636
-     *
1637
-     * @param array $query_params
1638
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1639
-     * @return int
1640
-     * @throws EE_Error
1641
-     * @throws ReflectionException
1642
-     */
1643
-    public function count_registrations($query_params = [])
1644
-    {
1645
-        return $this->count_related('Registration', $query_params);
1646
-    }
1647
-
1648
-
1649
-    /**
1650
-     * Implementation for EEI_Has_Icon interface method.
1651
-     *
1652
-     * @return string
1653
-     * @see EEI_Visual_Representation for comments
1654
-     */
1655
-    public function get_icon()
1656
-    {
1657
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1658
-    }
1659
-
1660
-
1661
-    /**
1662
-     * Implementation of the EEI_Event_Relation interface method
1663
-     *
1664
-     * @return EE_Event
1665
-     * @throws EE_Error
1666
-     * @throws UnexpectedEntityException
1667
-     * @throws ReflectionException
1668
-     * @see EEI_Event_Relation for comments
1669
-     */
1670
-    public function get_related_event()
1671
-    {
1672
-        // get one datetime to use for getting the event
1673
-        $datetime = $this->first_datetime();
1674
-        if (! $datetime instanceof EE_Datetime) {
1675
-            throw new UnexpectedEntityException(
1676
-                $datetime,
1677
-                'EE_Datetime',
1678
-                sprintf(
1679
-                    esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1680
-                    $this->name()
1681
-                )
1682
-            );
1683
-        }
1684
-        $event = $datetime->event();
1685
-        if (! $event instanceof EE_Event) {
1686
-            throw new UnexpectedEntityException(
1687
-                $event,
1688
-                'EE_Event',
1689
-                sprintf(
1690
-                    esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1691
-                    $this->name()
1692
-                )
1693
-            );
1694
-        }
1695
-        return $event;
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * Implementation of the EEI_Event_Relation interface method
1701
-     *
1702
-     * @return string
1703
-     * @throws UnexpectedEntityException
1704
-     * @throws EE_Error
1705
-     * @throws ReflectionException
1706
-     * @see EEI_Event_Relation for comments
1707
-     */
1708
-    public function get_event_name()
1709
-    {
1710
-        $event = $this->get_related_event();
1711
-        return $event instanceof EE_Event ? $event->name() : '';
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * Implementation of the EEI_Event_Relation interface method
1717
-     *
1718
-     * @return int
1719
-     * @throws UnexpectedEntityException
1720
-     * @throws EE_Error
1721
-     * @throws ReflectionException
1722
-     * @see EEI_Event_Relation for comments
1723
-     */
1724
-    public function get_event_ID()
1725
-    {
1726
-        $event = $this->get_related_event();
1727
-        return $event instanceof EE_Event ? $event->ID() : 0;
1728
-    }
1729
-
1730
-
1731
-    /**
1732
-     * This simply returns whether a ticket can be permanently deleted or not.
1733
-     * The criteria for determining this is whether the ticket has any related registrations.
1734
-     * If there are none then it can be permanently deleted.
1735
-     *
1736
-     * @return bool
1737
-     * @throws EE_Error
1738
-     * @throws ReflectionException
1739
-     */
1740
-    public function is_permanently_deleteable()
1741
-    {
1742
-        return $this->count_registrations() === 0;
1743
-    }
1744
-
1745
-
1746
-    /**
1747
-     * @return int
1748
-     * @throws EE_Error
1749
-     * @throws ReflectionException
1750
-     * @since   $VID:$
1751
-     */
1752
-    public function visibility(): int
1753
-    {
1754
-        return $this->get('TKT_visibility');
1755
-    }
1756
-
1757
-
1758
-    /**
1759
-     * @return int
1760
-     * @throws EE_Error
1761
-     * @throws ReflectionException
1762
-     * @since   $VID:$
1763
-     */
1764
-    public function isHidden(): int
1765
-    {
1766
-        return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1767
-    }
1768
-
1769
-
1770
-    /**
1771
-     * @return int
1772
-     * @throws EE_Error
1773
-     * @throws ReflectionException
1774
-     * @since   $VID:$
1775
-     */
1776
-    public function isNotHidden(): int
1777
-    {
1778
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1779
-    }
1780
-
1781
-
1782
-    /**
1783
-     * @return int
1784
-     * @throws EE_Error
1785
-     * @throws ReflectionException
1786
-     * @since   $VID:$
1787
-     */
1788
-    public function isPublicOnly(): int
1789
-    {
1790
-        return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     * @return int
1796
-     * @throws EE_Error
1797
-     * @throws ReflectionException
1798
-     * @since   $VID:$
1799
-     */
1800
-    public function isMembersOnly(): int
1801
-    {
1802
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1803
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1804
-    }
1805
-
1806
-
1807
-    /**
1808
-     * @return int
1809
-     * @throws EE_Error
1810
-     * @throws ReflectionException
1811
-     * @since   $VID:$
1812
-     */
1813
-    public function isAdminsOnly(): int
1814
-    {
1815
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1816
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1817
-    }
1818
-
1819
-
1820
-    /**
1821
-     * @return int
1822
-     * @throws EE_Error
1823
-     * @throws ReflectionException
1824
-     * @since   $VID:$
1825
-     */
1826
-    public function isAdminUiOnly(): int
1827
-    {
1828
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1829
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1830
-    }
1831
-
1832
-
1833
-    /**
1834
-     * @param int $visibility
1835
-     * @throws EE_Error
1836
-     * @throws ReflectionException
1837
-     * @since   $VID:$
1838
-     */
1839
-    public function set_visibility(int $visibility)
1840
-    {
1841
-
1842
-        $ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1843
-        $ticket_visibility         = -1;
1844
-        foreach ($ticket_visibility_options as $ticket_visibility_option) {
1845
-            if ($visibility === $ticket_visibility_option) {
1846
-                $ticket_visibility = $visibility;
1847
-            }
1848
-        }
1849
-        if ($ticket_visibility === -1) {
1850
-            throw new DomainException(
1851
-                sprintf(
1852
-                    esc_html__(
1853
-                        'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1854
-                        'event_espresso'
1855
-                    ),
1856
-                    $visibility,
1857
-                    '<br />',
1858
-                    var_export($ticket_visibility_options, true)
1859
-                )
1860
-            );
1861
-        }
1862
-        $this->set('TKT_visibility', $ticket_visibility);
1863
-    }
1864
-
1865
-
1866
-    /**
1867
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1868
-     * @param string                   $relationName
1869
-     * @param array                    $extra_join_model_fields_n_values
1870
-     * @param string|null              $cache_id
1871
-     * @return EE_Base_Class
1872
-     * @throws EE_Error
1873
-     * @throws ReflectionException
1874
-     * @since   $VID:$
1875
-     */
1876
-    public function _add_relation_to(
1877
-        $otherObjectModelObjectOrID,
1878
-        $relationName,
1879
-        $extra_join_model_fields_n_values = [],
1880
-        $cache_id = null
1881
-    ) {
1882
-        if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1883
-            /** @var EE_Datetime $datetime */
1884
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1885
-            $datetime->increaseSold($this->sold(), false);
1886
-            $datetime->increaseReserved($this->reserved());
1887
-            $datetime->save();
1888
-            $otherObjectModelObjectOrID = $datetime;
1889
-        }
1890
-        return parent::_add_relation_to(
1891
-            $otherObjectModelObjectOrID,
1892
-            $relationName,
1893
-            $extra_join_model_fields_n_values,
1894
-            $cache_id
1895
-        );
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1901
-     * @param string                   $relationName
1902
-     * @param array                    $where_query
1903
-     * @return bool|EE_Base_Class|null
1904
-     * @throws EE_Error
1905
-     * @throws ReflectionException
1906
-     * @since   $VID:$
1907
-     */
1908
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1909
-    {
1910
-        // if we're adding a new relation to a datetime
1911
-        if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1912
-            /** @var EE_Datetime $datetime */
1913
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1914
-            $datetime->decreaseSold($this->sold());
1915
-            $datetime->decreaseReserved($this->reserved());
1916
-            $datetime->save();
1917
-            $otherObjectModelObjectOrID = $datetime;
1918
-        }
1919
-        return parent::_remove_relation_to(
1920
-            $otherObjectModelObjectOrID,
1921
-            $relationName,
1922
-            $where_query
1923
-        );
1924
-    }
1925
-
1926
-
1927
-    /**
1928
-     * Removes ALL the related things for the $relationName.
1929
-     *
1930
-     * @param string $relationName
1931
-     * @param array  $where_query_params
1932
-     * @return EE_Base_Class
1933
-     * @throws ReflectionException
1934
-     * @throws InvalidArgumentException
1935
-     * @throws InvalidInterfaceException
1936
-     * @throws InvalidDataTypeException
1937
-     * @throws EE_Error
1938
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1939
-     */
1940
-    public function _remove_relations($relationName, $where_query_params = [])
1941
-    {
1942
-        if ($relationName === 'Datetime') {
1943
-            $datetimes = $this->datetimes();
1944
-            foreach ($datetimes as $datetime) {
1945
-                $datetime->decreaseSold($this->sold());
1946
-                $datetime->decreaseReserved($this->reserved());
1947
-                $datetime->save();
1948
-            }
1949
-        }
1950
-        return parent::_remove_relations($relationName, $where_query_params);
1951
-    }
1952
-
1953
-
1954
-    /*******************************************************************
17
+	/**
18
+	 * TicKet Archived:
19
+	 * constant used by ticket_status() to indicate that a ticket is archived
20
+	 * and no longer available for purchase
21
+	 */
22
+	const archived = 'TKA';
23
+
24
+	/**
25
+	 * TicKet Expired:
26
+	 * constant used by ticket_status() to indicate that a ticket is expired
27
+	 * and no longer available for purchase
28
+	 */
29
+	const expired = 'TKE';
30
+
31
+	/**
32
+	 * TicKet On sale:
33
+	 * constant used by ticket_status() to indicate that a ticket is On Sale
34
+	 * and IS available for purchase
35
+	 */
36
+	const onsale = 'TKO';
37
+
38
+	/**
39
+	 * TicKet Pending:
40
+	 * constant used by ticket_status() to indicate that a ticket is pending
41
+	 * and is NOT YET available for purchase
42
+	 */
43
+	const pending = 'TKP';
44
+
45
+	/**
46
+	 * TicKet Sold out:
47
+	 * constant used by ticket_status() to indicate that a ticket is sold out
48
+	 * and no longer available for purchases
49
+	 */
50
+	const sold_out = 'TKS';
51
+
52
+	/**
53
+	 * extra meta key for tracking ticket reservations
54
+	 *
55
+	 * @type string
56
+	 */
57
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
+
59
+	/**
60
+	 * override of parent property
61
+	 *
62
+	 * @var EEM_Ticket
63
+	 */
64
+	protected $_model;
65
+
66
+	/**
67
+	 * cached result from method of the same name
68
+	 *
69
+	 * @var float $_ticket_total_with_taxes
70
+	 */
71
+	private $_ticket_total_with_taxes;
72
+
73
+	/**
74
+	 * @var TicketPriceModifiers
75
+	 */
76
+	protected $ticket_price_modifiers;
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values          incoming values
81
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
+	 *                                        used.)
83
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
+	 *                                        date_format and the second value is the time format
85
+	 * @return EE_Ticket
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
+	{
91
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param array  $props_n_values  incoming values from the database
98
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
+	 *                                the website will be used.
100
+	 * @return EE_Ticket
101
+	 * @throws EE_Error
102
+	 * @throws ReflectionException
103
+	 */
104
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
+	{
106
+		return new self($props_n_values, true, $timezone);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param array  $fieldValues
112
+	 * @param false  $bydb
113
+	 * @param string $timezone
114
+	 * @param array  $date_formats
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
+	{
120
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
+		$this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @return bool
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function parent()
131
+	{
132
+		return $this->get('TKT_parent');
133
+	}
134
+
135
+
136
+	/**
137
+	 * return if a ticket has quantities available for purchase
138
+	 *
139
+	 * @param int $DTT_ID the primary key for a particular datetime
140
+	 * @return boolean
141
+	 * @throws EE_Error
142
+	 * @throws ReflectionException
143
+	 */
144
+	public function available($DTT_ID = 0)
145
+	{
146
+		// are we checking availability for a particular datetime ?
147
+		if ($DTT_ID) {
148
+			// get that datetime object
149
+			$datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
+			// if  ticket sales for this datetime have exceeded the reg limit...
151
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
+				return false;
153
+			}
154
+		}
155
+		// datetime is still open for registration, but is this ticket sold out ?
156
+		return $this->qty() < 1 || $this->qty() > $this->sold();
157
+	}
158
+
159
+
160
+	/**
161
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
+	 *
163
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
+	 *                               relevant status const
165
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
+	 *                               further processing
167
+	 * @return mixed status int if the display string isn't requested
168
+	 * @throws EE_Error
169
+	 * @throws ReflectionException
170
+	 */
171
+	public function ticket_status($display = false, $remaining = null)
172
+	{
173
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
+		if (! $remaining) {
175
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
+		}
177
+		if ($this->get('TKT_deleted')) {
178
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
+		}
180
+		if ($this->is_expired()) {
181
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
+		}
183
+		if ($this->is_pending()) {
184
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
+		}
186
+		if ($this->is_on_sale()) {
187
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
+		}
189
+		return '';
190
+	}
191
+
192
+
193
+	/**
194
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
+	 * considering ALL the factors used for figuring that out.
196
+	 *
197
+	 * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
+	 * @return boolean         true = tickets remaining, false not.
199
+	 * @throws EE_Error
200
+	 * @throws ReflectionException
201
+	 */
202
+	public function is_remaining($DTT_ID = 0)
203
+	{
204
+		$num_remaining = $this->remaining($DTT_ID);
205
+		if ($num_remaining === 0) {
206
+			return false;
207
+		}
208
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
+			return false;
210
+		}
211
+		return true;
212
+	}
213
+
214
+
215
+	/**
216
+	 * return the total number of tickets available for purchase
217
+	 *
218
+	 * @param int $DTT_ID  the primary key for a particular datetime.
219
+	 *                     set to 0 for all related datetimes
220
+	 * @return int
221
+	 * @throws EE_Error
222
+	 * @throws ReflectionException
223
+	 */
224
+	public function remaining($DTT_ID = 0)
225
+	{
226
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
+	}
228
+
229
+
230
+	/**
231
+	 * Gets min
232
+	 *
233
+	 * @return int
234
+	 * @throws EE_Error
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function min()
238
+	{
239
+		return $this->get('TKT_min');
240
+	}
241
+
242
+
243
+	/**
244
+	 * return if a ticket is no longer available cause its available dates have expired.
245
+	 *
246
+	 * @return boolean
247
+	 * @throws EE_Error
248
+	 * @throws ReflectionException
249
+	 */
250
+	public function is_expired()
251
+	{
252
+		return ($this->get_raw('TKT_end_date') < time());
253
+	}
254
+
255
+
256
+	/**
257
+	 * Return if a ticket is yet to go on sale or not
258
+	 *
259
+	 * @return boolean
260
+	 * @throws EE_Error
261
+	 * @throws ReflectionException
262
+	 */
263
+	public function is_pending()
264
+	{
265
+		return ($this->get_raw('TKT_start_date') >= time());
266
+	}
267
+
268
+
269
+	/**
270
+	 * Return if a ticket is on sale or not
271
+	 *
272
+	 * @return boolean
273
+	 * @throws EE_Error
274
+	 * @throws ReflectionException
275
+	 */
276
+	public function is_on_sale()
277
+	{
278
+		return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
+	}
280
+
281
+
282
+	/**
283
+	 * This returns the chronologically last datetime that this ticket is associated with
284
+	 *
285
+	 * @param string $date_format
286
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
+	 *                            the end date ie: Jan 01 "to" Dec 31
288
+	 * @return string
289
+	 * @throws EE_Error
290
+	 * @throws ReflectionException
291
+	 */
292
+	public function date_range($date_format = '', $conjunction = ' - ')
293
+	{
294
+		$date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
+		$first_date  = $this->first_datetime() instanceof EE_Datetime
296
+			? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
+			: '';
298
+		$last_date   = $this->last_datetime() instanceof EE_Datetime
299
+			? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
+			: '';
301
+
302
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
+	}
304
+
305
+
306
+	/**
307
+	 * This returns the chronologically first datetime that this ticket is associated with
308
+	 *
309
+	 * @return EE_Datetime
310
+	 * @throws EE_Error
311
+	 * @throws ReflectionException
312
+	 */
313
+	public function first_datetime()
314
+	{
315
+		$datetimes = $this->datetimes(['limit' => 1]);
316
+		return reset($datetimes);
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets all the datetimes this ticket can be used for attending.
322
+	 * Unless otherwise specified, orders datetimes by start date.
323
+	 *
324
+	 * @param array $query_params
325
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
+	 * @return EE_Datetime[]|EE_Base_Class[]
327
+	 * @throws EE_Error
328
+	 * @throws ReflectionException
329
+	 */
330
+	public function datetimes($query_params = [])
331
+	{
332
+		if (! isset($query_params['order_by'])) {
333
+			$query_params['order_by']['DTT_order'] = 'ASC';
334
+		}
335
+		return $this->get_many_related('Datetime', $query_params);
336
+	}
337
+
338
+
339
+	/**
340
+	 * This returns the chronologically last datetime that this ticket is associated with
341
+	 *
342
+	 * @return EE_Datetime
343
+	 * @throws EE_Error
344
+	 * @throws ReflectionException
345
+	 */
346
+	public function last_datetime()
347
+	{
348
+		$datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
+		return end($datetimes);
350
+	}
351
+
352
+
353
+	/**
354
+	 * This returns the total tickets sold depending on the given parameters.
355
+	 *
356
+	 * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
360
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
+	 * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
+	 * @return mixed (array|int)          how many tickets have sold
364
+	 * @throws EE_Error
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
368
+	{
369
+		$total        = 0;
370
+		$tickets_sold = $this->_all_tickets_sold();
371
+		switch ($what) {
372
+			case 'ticket':
373
+				return $tickets_sold['ticket'];
374
+
375
+			case 'datetime':
376
+				if (empty($tickets_sold['datetime'])) {
377
+					return $total;
378
+				}
379
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
+					EE_Error::add_error(
381
+						esc_html__(
382
+							'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
+							'event_espresso'
384
+						),
385
+						__FILE__,
386
+						__FUNCTION__,
387
+						__LINE__
388
+					);
389
+					return $total;
390
+				}
391
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
+
393
+			default:
394
+				return $total;
395
+		}
396
+	}
397
+
398
+
399
+	/**
400
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
+	 *
402
+	 * @return EE_Ticket[]
403
+	 * @throws EE_Error
404
+	 * @throws ReflectionException
405
+	 */
406
+	protected function _all_tickets_sold()
407
+	{
408
+		$datetimes    = $this->get_many_related('Datetime');
409
+		$tickets_sold = [];
410
+		if (! empty($datetimes)) {
411
+			foreach ($datetimes as $datetime) {
412
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
+			}
414
+		}
415
+		// Tickets sold
416
+		$tickets_sold['ticket'] = $this->sold();
417
+		return $tickets_sold;
418
+	}
419
+
420
+
421
+	/**
422
+	 * This returns the base price object for the ticket.
423
+	 *
424
+	 * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function base_price(bool $return_array = false)
430
+	{
431
+		$base_price = $this->ticket_price_modifiers->getBasePrice();
432
+		if (! empty($base_price)) {
433
+			return $return_array ? $base_price : reset($base_price);
434
+		}
435
+		$_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
+		return $return_array
437
+			? $this->get_many_related('Price', [$_where])
438
+			: $this->get_first_related('Price', [$_where]);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
+	 *
445
+	 * @return EE_Price[]
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 */
449
+	public function price_modifiers(): array
450
+	{
451
+		$price_modifiers = $this->usesGlobalTaxes()
452
+			? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
+			: $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
+		if (! empty($price_modifiers)) {
455
+			return $price_modifiers;
456
+		}
457
+		return $this->prices(
458
+			[
459
+				[
460
+					'Price_Type.PBT_ID' => [
461
+						'NOT IN',
462
+						[EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
+					]
464
+				]
465
+			]
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * This returns ONLY the TAX price modifiers for the ticket
472
+	 *
473
+	 * @return EE_Price[]
474
+	 * @throws EE_Error
475
+	 * @throws ReflectionException
476
+	 */
477
+	public function tax_price_modifiers(): array
478
+	{
479
+		$tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
+		if (! empty($tax_price_modifiers)) {
481
+			return $tax_price_modifiers;
482
+		}
483
+		return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
+	}
485
+
486
+
487
+	/**
488
+	 * Gets all the prices that combine to form the final price of this ticket
489
+	 *
490
+	 * @param array $query_params
491
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
+	 * @return EE_Price[]|EE_Base_Class[]
493
+	 * @throws EE_Error
494
+	 * @throws ReflectionException
495
+	 */
496
+	public function prices(array $query_params = []): array
497
+	{
498
+		if (! isset($query_params['order_by'])) {
499
+			$query_params['order_by']['PRC_order'] = 'ASC';
500
+		}
501
+		return $this->get_many_related('Price', $query_params);
502
+	}
503
+
504
+
505
+	/**
506
+	 * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
+	 *
508
+	 * @param array $query_params
509
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function datetime_tickets($query_params = [])
515
+	{
516
+		return $this->get_many_related('Datetime_Ticket', $query_params);
517
+	}
518
+
519
+
520
+	/**
521
+	 * Gets all the datetimes from the db ordered by DTT_order
522
+	 *
523
+	 * @param boolean $show_expired
524
+	 * @param boolean $show_deleted
525
+	 * @return EE_Datetime[]
526
+	 * @throws EE_Error
527
+	 * @throws ReflectionException
528
+	 */
529
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
+	{
531
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
+			$this->ID(),
533
+			$show_expired,
534
+			$show_deleted
535
+		);
536
+	}
537
+
538
+
539
+	/**
540
+	 * Gets ID
541
+	 *
542
+	 * @return int
543
+	 * @throws EE_Error
544
+	 * @throws ReflectionException
545
+	 */
546
+	public function ID()
547
+	{
548
+		return (int) $this->get('TKT_ID');
549
+	}
550
+
551
+
552
+	/**
553
+	 * get the author of the ticket.
554
+	 *
555
+	 * @return int
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 * @since 4.5.0
559
+	 */
560
+	public function wp_user()
561
+	{
562
+		return $this->get('TKT_wp_user');
563
+	}
564
+
565
+
566
+	/**
567
+	 * Gets the template for the ticket
568
+	 *
569
+	 * @return EE_Ticket_Template|EE_Base_Class
570
+	 * @throws EE_Error
571
+	 * @throws ReflectionException
572
+	 */
573
+	public function template()
574
+	{
575
+		return $this->get_first_related('Ticket_Template');
576
+	}
577
+
578
+
579
+	/**
580
+	 * Simply returns an array of EE_Price objects that are taxes.
581
+	 *
582
+	 * @return EE_Price[]
583
+	 * @throws EE_Error
584
+	 * @throws ReflectionException
585
+	 */
586
+	public function get_ticket_taxes_for_admin(): array
587
+	{
588
+		return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
+	}
590
+
591
+
592
+	/**
593
+	 * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
+	 * as opposed to having tax price modifiers added directly to each ticket
595
+	 *
596
+	 * @return bool
597
+	 * @throws EE_Error
598
+	 * @throws ReflectionException
599
+	 * @since   $VID:$
600
+	 */
601
+	public function usesGlobalTaxes(): bool
602
+	{
603
+		return $this->taxable();
604
+	}
605
+
606
+
607
+	/**
608
+	 * @return float
609
+	 * @throws EE_Error
610
+	 * @throws ReflectionException
611
+	 */
612
+	public function ticket_price()
613
+	{
614
+		return $this->get('TKT_price');
615
+	}
616
+
617
+
618
+	/**
619
+	 * @return mixed
620
+	 * @throws EE_Error
621
+	 * @throws ReflectionException
622
+	 */
623
+	public function pretty_price()
624
+	{
625
+		return $this->get_pretty('TKT_price');
626
+	}
627
+
628
+
629
+	/**
630
+	 * @return bool
631
+	 * @throws EE_Error
632
+	 * @throws ReflectionException
633
+	 */
634
+	public function is_free()
635
+	{
636
+		return $this->get_ticket_total_with_taxes() === (float) 0;
637
+	}
638
+
639
+
640
+	/**
641
+	 * get_ticket_total_with_taxes
642
+	 *
643
+	 * @param bool $no_cache
644
+	 * @return float
645
+	 * @throws EE_Error
646
+	 * @throws ReflectionException
647
+	 */
648
+	public function get_ticket_total_with_taxes($no_cache = false)
649
+	{
650
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
+			$this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
+				? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
+				: $this->ticket_price();
654
+		}
655
+		return (float) $this->_ticket_total_with_taxes;
656
+	}
657
+
658
+
659
+	/**
660
+	 * @throws EE_Error
661
+	 * @throws ReflectionException
662
+	 */
663
+	public function ensure_TKT_Price_correct()
664
+	{
665
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
+		$this->save();
667
+	}
668
+
669
+
670
+	/**
671
+	 * @return float
672
+	 * @throws EE_Error
673
+	 * @throws ReflectionException
674
+	 */
675
+	public function get_ticket_subtotal()
676
+	{
677
+		return EE_Taxes::get_subtotal_for_admin($this);
678
+	}
679
+
680
+
681
+	/**
682
+	 * Returns the total taxes applied to this ticket
683
+	 *
684
+	 * @return float
685
+	 * @throws EE_Error
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function get_ticket_taxes_total_for_admin()
689
+	{
690
+		return EE_Taxes::get_total_taxes_for_admin($this);
691
+	}
692
+
693
+
694
+	/**
695
+	 * Sets name
696
+	 *
697
+	 * @param string $name
698
+	 * @throws EE_Error
699
+	 * @throws ReflectionException
700
+	 */
701
+	public function set_name($name)
702
+	{
703
+		$this->set('TKT_name', $name);
704
+	}
705
+
706
+
707
+	/**
708
+	 * Gets description
709
+	 *
710
+	 * @return string
711
+	 * @throws EE_Error
712
+	 * @throws ReflectionException
713
+	 */
714
+	public function description()
715
+	{
716
+		return $this->get('TKT_description');
717
+	}
718
+
719
+
720
+	/**
721
+	 * Sets description
722
+	 *
723
+	 * @param string $description
724
+	 * @throws EE_Error
725
+	 * @throws ReflectionException
726
+	 */
727
+	public function set_description($description)
728
+	{
729
+		$this->set('TKT_description', $description);
730
+	}
731
+
732
+
733
+	/**
734
+	 * Gets start_date
735
+	 *
736
+	 * @param string $date_format
737
+	 * @param string $time_format
738
+	 * @return string
739
+	 * @throws EE_Error
740
+	 * @throws ReflectionException
741
+	 */
742
+	public function start_date($date_format = '', $time_format = '')
743
+	{
744
+		return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
+	}
746
+
747
+
748
+	/**
749
+	 * Sets start_date
750
+	 *
751
+	 * @param string $start_date
752
+	 * @return void
753
+	 * @throws EE_Error
754
+	 * @throws ReflectionException
755
+	 */
756
+	public function set_start_date($start_date)
757
+	{
758
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
759
+	}
760
+
761
+
762
+	/**
763
+	 * Gets end_date
764
+	 *
765
+	 * @param string $date_format
766
+	 * @param string $time_format
767
+	 * @return string
768
+	 * @throws EE_Error
769
+	 * @throws ReflectionException
770
+	 */
771
+	public function end_date($date_format = '', $time_format = '')
772
+	{
773
+		return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
+	}
775
+
776
+
777
+	/**
778
+	 * Sets end_date
779
+	 *
780
+	 * @param string $end_date
781
+	 * @return void
782
+	 * @throws EE_Error
783
+	 * @throws ReflectionException
784
+	 */
785
+	public function set_end_date($end_date)
786
+	{
787
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
788
+	}
789
+
790
+
791
+	/**
792
+	 * Sets sell until time
793
+	 *
794
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
+	 * @throws EE_Error
796
+	 * @throws ReflectionException
797
+	 * @since 4.5.0
798
+	 */
799
+	public function set_end_time($time)
800
+	{
801
+		$this->_set_time_for($time, 'TKT_end_date');
802
+	}
803
+
804
+
805
+	/**
806
+	 * Sets min
807
+	 *
808
+	 * @param int $min
809
+	 * @return void
810
+	 * @throws EE_Error
811
+	 * @throws ReflectionException
812
+	 */
813
+	public function set_min($min)
814
+	{
815
+		$this->set('TKT_min', $min);
816
+	}
817
+
818
+
819
+	/**
820
+	 * Gets max
821
+	 *
822
+	 * @return int
823
+	 * @throws EE_Error
824
+	 * @throws ReflectionException
825
+	 */
826
+	public function max()
827
+	{
828
+		return $this->get('TKT_max');
829
+	}
830
+
831
+
832
+	/**
833
+	 * Sets max
834
+	 *
835
+	 * @param int $max
836
+	 * @return void
837
+	 * @throws EE_Error
838
+	 * @throws ReflectionException
839
+	 */
840
+	public function set_max($max)
841
+	{
842
+		$this->set('TKT_max', $max);
843
+	}
844
+
845
+
846
+	/**
847
+	 * Sets price
848
+	 *
849
+	 * @param float $price
850
+	 * @return void
851
+	 * @throws EE_Error
852
+	 * @throws ReflectionException
853
+	 */
854
+	public function set_price($price)
855
+	{
856
+		$this->set('TKT_price', $price);
857
+	}
858
+
859
+
860
+	/**
861
+	 * Gets sold
862
+	 *
863
+	 * @return int
864
+	 * @throws EE_Error
865
+	 * @throws ReflectionException
866
+	 */
867
+	public function sold(): int
868
+	{
869
+		return (int) $this->get_raw('TKT_sold');
870
+	}
871
+
872
+
873
+	/**
874
+	 * Sets sold
875
+	 *
876
+	 * @param int $sold
877
+	 * @return void
878
+	 * @throws EE_Error
879
+	 * @throws ReflectionException
880
+	 */
881
+	public function set_sold($sold)
882
+	{
883
+		// sold can not go below zero
884
+		$sold = max(0, $sold);
885
+		$this->set('TKT_sold', $sold);
886
+	}
887
+
888
+
889
+	/**
890
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
+	 * associated datetimes.
892
+	 *
893
+	 * @param int $qty
894
+	 * @return boolean
895
+	 * @throws EE_Error
896
+	 * @throws InvalidArgumentException
897
+	 * @throws InvalidDataTypeException
898
+	 * @throws InvalidInterfaceException
899
+	 * @throws ReflectionException
900
+	 * @since 4.9.80.p
901
+	 */
902
+	public function increaseSold($qty = 1)
903
+	{
904
+		$qty = absint($qty);
905
+		// increment sold and decrement reserved datetime quantities simultaneously
906
+		// don't worry about failures, because they must have already had a spot reserved
907
+		$this->increaseSoldForDatetimes($qty);
908
+		// Increment and decrement ticket quantities simultaneously
909
+		$success = $this->adjustNumericFieldsInDb(
910
+			[
911
+				'TKT_reserved' => $qty * -1,
912
+				'TKT_sold'     => $qty,
913
+			]
914
+		);
915
+		do_action(
916
+			'AHEE__EE_Ticket__increase_sold',
917
+			$this,
918
+			$qty,
919
+			$this->sold(),
920
+			$success
921
+		);
922
+		return $success;
923
+	}
924
+
925
+
926
+	/**
927
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
+	 *
929
+	 * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
+	 *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
+	 * @param EE_Datetime[] $datetimes
932
+	 * @throws EE_Error
933
+	 * @throws InvalidArgumentException
934
+	 * @throws InvalidDataTypeException
935
+	 * @throws InvalidInterfaceException
936
+	 * @throws ReflectionException
937
+	 * @since 4.9.80.p
938
+	 */
939
+	protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
+	{
941
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
+		foreach ($datetimes as $datetime) {
943
+			$datetime->increaseSold($qty);
944
+		}
945
+	}
946
+
947
+
948
+	/**
949
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
+	 * DB and then updates the model objects.
951
+	 * Does not affect the reserved counts.
952
+	 *
953
+	 * @param int $qty
954
+	 * @return boolean
955
+	 * @throws EE_Error
956
+	 * @throws InvalidArgumentException
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws ReflectionException
960
+	 * @since 4.9.80.p
961
+	 */
962
+	public function decreaseSold($qty = 1)
963
+	{
964
+		$qty = absint($qty);
965
+		$this->decreaseSoldForDatetimes($qty);
966
+		$success = $this->adjustNumericFieldsInDb(
967
+			[
968
+				'TKT_sold' => $qty * -1,
969
+			]
970
+		);
971
+		do_action(
972
+			'AHEE__EE_Ticket__decrease_sold',
973
+			$this,
974
+			$qty,
975
+			$this->sold(),
976
+			$success
977
+		);
978
+		return $success;
979
+	}
980
+
981
+
982
+	/**
983
+	 * Decreases sold on related datetimes
984
+	 *
985
+	 * @param int           $qty
986
+	 * @param EE_Datetime[] $datetimes
987
+	 * @return void
988
+	 * @throws EE_Error
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidDataTypeException
991
+	 * @throws InvalidInterfaceException
992
+	 * @throws ReflectionException
993
+	 * @since 4.9.80.p
994
+	 */
995
+	protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
+	{
997
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
+		if (is_array($datetimes)) {
999
+			foreach ($datetimes as $datetime) {
1000
+				if ($datetime instanceof EE_Datetime) {
1001
+					$datetime->decreaseSold($qty);
1002
+				}
1003
+			}
1004
+		}
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Gets qty of reserved tickets
1010
+	 *
1011
+	 * @return int
1012
+	 * @throws EE_Error
1013
+	 * @throws ReflectionException
1014
+	 */
1015
+	public function reserved(): int
1016
+	{
1017
+		return (int) $this->get_raw('TKT_reserved');
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Sets reserved
1023
+	 *
1024
+	 * @param int $reserved
1025
+	 * @return void
1026
+	 * @throws EE_Error
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	public function set_reserved($reserved)
1030
+	{
1031
+		// reserved can not go below zero
1032
+		$reserved = max(0, (int) $reserved);
1033
+		$this->set('TKT_reserved', $reserved);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
+	 *
1040
+	 * @param int    $qty
1041
+	 * @param string $source
1042
+	 * @return bool whether we successfully reserved the ticket or not.
1043
+	 * @throws EE_Error
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @since 4.9.80.p
1049
+	 */
1050
+	public function increaseReserved($qty = 1, $source = 'unknown')
1051
+	{
1052
+		$qty = absint($qty);
1053
+		do_action(
1054
+			'AHEE__EE_Ticket__increase_reserved__begin',
1055
+			$this,
1056
+			$qty,
1057
+			$source
1058
+		);
1059
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
+		$success                         = false;
1061
+		$datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
+		if ($datetimes_adjusted_successfully) {
1063
+			$success = $this->incrementFieldConditionallyInDb(
1064
+				'TKT_reserved',
1065
+				'TKT_sold',
1066
+				'TKT_qty',
1067
+				$qty
1068
+			);
1069
+			if (! $success) {
1070
+				// The datetimes were successfully bumped, but not the
1071
+				// ticket. So we need to manually rollback the datetimes.
1072
+				$this->decreaseReservedForDatetimes($qty);
1073
+			}
1074
+		}
1075
+		do_action(
1076
+			'AHEE__EE_Ticket__increase_reserved',
1077
+			$this,
1078
+			$qty,
1079
+			$this->reserved(),
1080
+			$success
1081
+		);
1082
+		return $success;
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * Increases reserved counts on related datetimes
1088
+	 *
1089
+	 * @param int           $qty
1090
+	 * @param EE_Datetime[] $datetimes
1091
+	 * @return boolean indicating success
1092
+	 * @throws EE_Error
1093
+	 * @throws InvalidArgumentException
1094
+	 * @throws InvalidDataTypeException
1095
+	 * @throws InvalidInterfaceException
1096
+	 * @throws ReflectionException
1097
+	 * @since 4.9.80.p
1098
+	 */
1099
+	protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
+	{
1101
+		$datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
+		$datetimes_updated = [];
1103
+		$limit_exceeded    = false;
1104
+		if (is_array($datetimes)) {
1105
+			foreach ($datetimes as $datetime) {
1106
+				if ($datetime instanceof EE_Datetime) {
1107
+					if ($datetime->increaseReserved($qty)) {
1108
+						$datetimes_updated[] = $datetime;
1109
+					} else {
1110
+						$limit_exceeded = true;
1111
+						break;
1112
+					}
1113
+				}
1114
+			}
1115
+			// If somewhere along the way we detected a datetime whose
1116
+			// limit was exceeded, do a manual rollback.
1117
+			if ($limit_exceeded) {
1118
+				$this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
+				return false;
1120
+			}
1121
+		}
1122
+		return true;
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
+	 *
1129
+	 * @param int    $qty
1130
+	 * @param bool   $adjust_datetimes
1131
+	 * @param string $source
1132
+	 * @return boolean
1133
+	 * @throws EE_Error
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws ReflectionException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws InvalidInterfaceException
1138
+	 * @since 4.9.80.p
1139
+	 */
1140
+	public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
+	{
1142
+		$qty = absint($qty);
1143
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
+		if ($adjust_datetimes) {
1145
+			$this->decreaseReservedForDatetimes($qty);
1146
+		}
1147
+		$success = $this->adjustNumericFieldsInDb(
1148
+			[
1149
+				'TKT_reserved' => $qty * -1,
1150
+			]
1151
+		);
1152
+		do_action(
1153
+			'AHEE__EE_Ticket__decrease_reserved',
1154
+			$this,
1155
+			$qty,
1156
+			$this->reserved(),
1157
+			$success
1158
+		);
1159
+		return $success;
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * Decreases the reserved count on the specified datetimes.
1165
+	 *
1166
+	 * @param int           $qty
1167
+	 * @param EE_Datetime[] $datetimes
1168
+	 * @throws EE_Error
1169
+	 * @throws InvalidArgumentException
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @since 4.9.80.p
1174
+	 */
1175
+	protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
+	{
1177
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
+		foreach ($datetimes as $datetime) {
1179
+			if ($datetime instanceof EE_Datetime) {
1180
+				$datetime->decreaseReserved($qty);
1181
+			}
1182
+		}
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets ticket quantity
1188
+	 *
1189
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
+	 * @return int
1196
+	 * @throws EE_Error
1197
+	 * @throws ReflectionException
1198
+	 */
1199
+	public function qty($context = '')
1200
+	{
1201
+		switch ($context) {
1202
+			case 'reg_limit':
1203
+				return $this->real_quantity_on_ticket();
1204
+			case 'saleable':
1205
+				return $this->real_quantity_on_ticket('saleable');
1206
+			default:
1207
+				return $this->get_raw('TKT_qty');
1208
+		}
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * Gets ticket quantity
1214
+	 *
1215
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
+	 * @param int    $DTT_ID      the primary key for a particular datetime.
1221
+	 *                            set to 0 for all related datetimes
1222
+	 * @return int
1223
+	 * @throws EE_Error
1224
+	 * @throws ReflectionException
1225
+	 */
1226
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
+	{
1228
+		$raw = $this->get_raw('TKT_qty');
1229
+		// return immediately if it's zero
1230
+		if ($raw === 0) {
1231
+			return $raw;
1232
+		}
1233
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
+		// ensure qty doesn't exceed raw value for THIS ticket
1235
+		$qty = min(EE_INF, $raw);
1236
+		// echo "\n . qty: " . $qty . '<br />';
1237
+		// calculate this ticket's total sales and reservations
1238
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
+		// echo "\n . sold: " . $this->sold() . '<br />';
1240
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1241
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
+		// first we need to calculate the maximum number of tickets available for the datetime
1243
+		// do we want data for one datetime or all of them ?
1244
+		$query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
+		$datetimes    = $this->datetimes($query_params);
1246
+		if (is_array($datetimes) && ! empty($datetimes)) {
1247
+			foreach ($datetimes as $datetime) {
1248
+				if ($datetime instanceof EE_Datetime) {
1249
+					$datetime->refresh_from_db();
1250
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
+					// initialize with no restrictions for each datetime
1253
+					// but adjust datetime qty based on datetime reg limit
1254
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
+					// and reservations for this datetime, that do NOT include sales and reservations
1259
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
+					if ($context === 'saleable') {
1261
+						$datetime_qty = max(
1262
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
+							0
1264
+						);
1265
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
+					}
1272
+					$qty = min($datetime_qty, $qty);
1273
+					// echo "\n . . qty: " . $qty . '<br />';
1274
+				}
1275
+			}
1276
+		}
1277
+		// NOW that we know the  maximum number of tickets available for the datetime
1278
+		// we can finally factor in the details for this specific ticket
1279
+		if ($qty > 0 && $context === 'saleable') {
1280
+			// and subtract the sales for THIS ticket
1281
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
+			// echo "\n . qty: " . $qty . '<br />';
1283
+		}
1284
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
+		return $qty;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
+	 *
1292
+	 * @param int $qty
1293
+	 * @return void
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function set_qty($qty)
1298
+	{
1299
+		$datetimes = $this->datetimes();
1300
+		foreach ($datetimes as $datetime) {
1301
+			if ($datetime instanceof EE_Datetime) {
1302
+				$qty = min($qty, $datetime->reg_limit());
1303
+			}
1304
+		}
1305
+		$this->set('TKT_qty', $qty);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * Gets uses
1311
+	 *
1312
+	 * @return int
1313
+	 * @throws EE_Error
1314
+	 * @throws ReflectionException
1315
+	 */
1316
+	public function uses()
1317
+	{
1318
+		return $this->get('TKT_uses');
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * Sets uses
1324
+	 *
1325
+	 * @param int $uses
1326
+	 * @return void
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 */
1330
+	public function set_uses($uses)
1331
+	{
1332
+		$this->set('TKT_uses', $uses);
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * returns whether ticket is required or not.
1338
+	 *
1339
+	 * @return boolean
1340
+	 * @throws EE_Error
1341
+	 * @throws ReflectionException
1342
+	 */
1343
+	public function required()
1344
+	{
1345
+		return $this->get('TKT_required');
1346
+	}
1347
+
1348
+
1349
+	/**
1350
+	 * sets the TKT_required property
1351
+	 *
1352
+	 * @param boolean $required
1353
+	 * @return void
1354
+	 * @throws EE_Error
1355
+	 * @throws ReflectionException
1356
+	 */
1357
+	public function set_required($required)
1358
+	{
1359
+		$this->set('TKT_required', $required);
1360
+	}
1361
+
1362
+
1363
+	/**
1364
+	 * Gets taxable
1365
+	 *
1366
+	 * @return boolean
1367
+	 * @throws EE_Error
1368
+	 * @throws ReflectionException
1369
+	 */
1370
+	public function taxable()
1371
+	{
1372
+		return $this->get('TKT_taxable');
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * Sets taxable
1378
+	 *
1379
+	 * @param boolean $taxable
1380
+	 * @return void
1381
+	 * @throws EE_Error
1382
+	 * @throws ReflectionException
1383
+	 */
1384
+	public function set_taxable($taxable)
1385
+	{
1386
+		$this->set('TKT_taxable', $taxable);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * Gets is_default
1392
+	 *
1393
+	 * @return boolean
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function is_default()
1398
+	{
1399
+		return $this->get('TKT_is_default');
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * Sets is_default
1405
+	 *
1406
+	 * @param boolean $is_default
1407
+	 * @return void
1408
+	 * @throws EE_Error
1409
+	 * @throws ReflectionException
1410
+	 */
1411
+	public function set_is_default($is_default)
1412
+	{
1413
+		$this->set('TKT_is_default', $is_default);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Gets order
1419
+	 *
1420
+	 * @return int
1421
+	 * @throws EE_Error
1422
+	 * @throws ReflectionException
1423
+	 */
1424
+	public function order()
1425
+	{
1426
+		return $this->get('TKT_order');
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * Sets order
1432
+	 *
1433
+	 * @param int $order
1434
+	 * @return void
1435
+	 * @throws EE_Error
1436
+	 * @throws ReflectionException
1437
+	 */
1438
+	public function set_order($order)
1439
+	{
1440
+		$this->set('TKT_order', $order);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Gets row
1446
+	 *
1447
+	 * @return int
1448
+	 * @throws EE_Error
1449
+	 * @throws ReflectionException
1450
+	 */
1451
+	public function row()
1452
+	{
1453
+		return $this->get('TKT_row');
1454
+	}
1455
+
1456
+
1457
+	/**
1458
+	 * Sets row
1459
+	 *
1460
+	 * @param int $row
1461
+	 * @return void
1462
+	 * @throws EE_Error
1463
+	 * @throws ReflectionException
1464
+	 */
1465
+	public function set_row($row)
1466
+	{
1467
+		$this->set('TKT_row', $row);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Gets deleted
1473
+	 *
1474
+	 * @return boolean
1475
+	 * @throws EE_Error
1476
+	 * @throws ReflectionException
1477
+	 */
1478
+	public function deleted()
1479
+	{
1480
+		return $this->get('TKT_deleted');
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * Sets deleted
1486
+	 *
1487
+	 * @param boolean $deleted
1488
+	 * @return void
1489
+	 * @throws EE_Error
1490
+	 * @throws ReflectionException
1491
+	 */
1492
+	public function set_deleted($deleted)
1493
+	{
1494
+		$this->set('TKT_deleted', $deleted);
1495
+	}
1496
+
1497
+
1498
+	/**
1499
+	 * Gets parent
1500
+	 *
1501
+	 * @return int
1502
+	 * @throws EE_Error
1503
+	 * @throws ReflectionException
1504
+	 */
1505
+	public function parent_ID()
1506
+	{
1507
+		return $this->get('TKT_parent');
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Sets parent
1513
+	 *
1514
+	 * @param int $parent
1515
+	 * @return void
1516
+	 * @throws EE_Error
1517
+	 * @throws ReflectionException
1518
+	 */
1519
+	public function set_parent_ID($parent)
1520
+	{
1521
+		$this->set('TKT_parent', $parent);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * @return boolean
1527
+	 * @throws EE_Error
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidDataTypeException
1530
+	 * @throws InvalidInterfaceException
1531
+	 * @throws ReflectionException
1532
+	 */
1533
+	public function reverse_calculate()
1534
+	{
1535
+		return $this->get('TKT_reverse_calculate');
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * @param boolean $reverse_calculate
1541
+	 * @throws EE_Error
1542
+	 * @throws InvalidArgumentException
1543
+	 * @throws InvalidDataTypeException
1544
+	 * @throws InvalidInterfaceException
1545
+	 * @throws ReflectionException
1546
+	 */
1547
+	public function set_reverse_calculate($reverse_calculate)
1548
+	{
1549
+		$this->set('TKT_reverse_calculate', $reverse_calculate);
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
+	 *
1556
+	 * @return string
1557
+	 * @throws EE_Error
1558
+	 * @throws ReflectionException
1559
+	 */
1560
+	public function name_and_info()
1561
+	{
1562
+		$times = [];
1563
+		foreach ($this->datetimes() as $datetime) {
1564
+			$times[] = $datetime->start_date_and_time();
1565
+		}
1566
+		return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1567
+	}
1568
+
1569
+
1570
+	/**
1571
+	 * Gets name
1572
+	 *
1573
+	 * @return string
1574
+	 * @throws EE_Error
1575
+	 * @throws ReflectionException
1576
+	 */
1577
+	public function name()
1578
+	{
1579
+		return $this->get('TKT_name');
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets price
1585
+	 *
1586
+	 * @return float
1587
+	 * @throws EE_Error
1588
+	 * @throws ReflectionException
1589
+	 */
1590
+	public function price()
1591
+	{
1592
+		return $this->get('TKT_price');
1593
+	}
1594
+
1595
+
1596
+	/**
1597
+	 * Gets all the registrations for this ticket
1598
+	 *
1599
+	 * @param array $query_params
1600
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1601
+	 * @return EE_Registration[]|EE_Base_Class[]
1602
+	 * @throws EE_Error
1603
+	 * @throws ReflectionException
1604
+	 */
1605
+	public function registrations($query_params = [])
1606
+	{
1607
+		return $this->get_many_related('Registration', $query_params);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1613
+	 *
1614
+	 * @return int
1615
+	 * @throws EE_Error
1616
+	 * @throws ReflectionException
1617
+	 */
1618
+	public function update_tickets_sold()
1619
+	{
1620
+		$count_regs_for_this_ticket = $this->count_registrations(
1621
+			[
1622
+				[
1623
+					'STS_ID'      => EEM_Registration::status_id_approved,
1624
+					'REG_deleted' => 0,
1625
+				],
1626
+			]
1627
+		);
1628
+		$this->set_sold($count_regs_for_this_ticket);
1629
+		$this->save();
1630
+		return $count_regs_for_this_ticket;
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Counts the registrations for this ticket
1636
+	 *
1637
+	 * @param array $query_params
1638
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1639
+	 * @return int
1640
+	 * @throws EE_Error
1641
+	 * @throws ReflectionException
1642
+	 */
1643
+	public function count_registrations($query_params = [])
1644
+	{
1645
+		return $this->count_related('Registration', $query_params);
1646
+	}
1647
+
1648
+
1649
+	/**
1650
+	 * Implementation for EEI_Has_Icon interface method.
1651
+	 *
1652
+	 * @return string
1653
+	 * @see EEI_Visual_Representation for comments
1654
+	 */
1655
+	public function get_icon()
1656
+	{
1657
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1658
+	}
1659
+
1660
+
1661
+	/**
1662
+	 * Implementation of the EEI_Event_Relation interface method
1663
+	 *
1664
+	 * @return EE_Event
1665
+	 * @throws EE_Error
1666
+	 * @throws UnexpectedEntityException
1667
+	 * @throws ReflectionException
1668
+	 * @see EEI_Event_Relation for comments
1669
+	 */
1670
+	public function get_related_event()
1671
+	{
1672
+		// get one datetime to use for getting the event
1673
+		$datetime = $this->first_datetime();
1674
+		if (! $datetime instanceof EE_Datetime) {
1675
+			throw new UnexpectedEntityException(
1676
+				$datetime,
1677
+				'EE_Datetime',
1678
+				sprintf(
1679
+					esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1680
+					$this->name()
1681
+				)
1682
+			);
1683
+		}
1684
+		$event = $datetime->event();
1685
+		if (! $event instanceof EE_Event) {
1686
+			throw new UnexpectedEntityException(
1687
+				$event,
1688
+				'EE_Event',
1689
+				sprintf(
1690
+					esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1691
+					$this->name()
1692
+				)
1693
+			);
1694
+		}
1695
+		return $event;
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * Implementation of the EEI_Event_Relation interface method
1701
+	 *
1702
+	 * @return string
1703
+	 * @throws UnexpectedEntityException
1704
+	 * @throws EE_Error
1705
+	 * @throws ReflectionException
1706
+	 * @see EEI_Event_Relation for comments
1707
+	 */
1708
+	public function get_event_name()
1709
+	{
1710
+		$event = $this->get_related_event();
1711
+		return $event instanceof EE_Event ? $event->name() : '';
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * Implementation of the EEI_Event_Relation interface method
1717
+	 *
1718
+	 * @return int
1719
+	 * @throws UnexpectedEntityException
1720
+	 * @throws EE_Error
1721
+	 * @throws ReflectionException
1722
+	 * @see EEI_Event_Relation for comments
1723
+	 */
1724
+	public function get_event_ID()
1725
+	{
1726
+		$event = $this->get_related_event();
1727
+		return $event instanceof EE_Event ? $event->ID() : 0;
1728
+	}
1729
+
1730
+
1731
+	/**
1732
+	 * This simply returns whether a ticket can be permanently deleted or not.
1733
+	 * The criteria for determining this is whether the ticket has any related registrations.
1734
+	 * If there are none then it can be permanently deleted.
1735
+	 *
1736
+	 * @return bool
1737
+	 * @throws EE_Error
1738
+	 * @throws ReflectionException
1739
+	 */
1740
+	public function is_permanently_deleteable()
1741
+	{
1742
+		return $this->count_registrations() === 0;
1743
+	}
1744
+
1745
+
1746
+	/**
1747
+	 * @return int
1748
+	 * @throws EE_Error
1749
+	 * @throws ReflectionException
1750
+	 * @since   $VID:$
1751
+	 */
1752
+	public function visibility(): int
1753
+	{
1754
+		return $this->get('TKT_visibility');
1755
+	}
1756
+
1757
+
1758
+	/**
1759
+	 * @return int
1760
+	 * @throws EE_Error
1761
+	 * @throws ReflectionException
1762
+	 * @since   $VID:$
1763
+	 */
1764
+	public function isHidden(): int
1765
+	{
1766
+		return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1767
+	}
1768
+
1769
+
1770
+	/**
1771
+	 * @return int
1772
+	 * @throws EE_Error
1773
+	 * @throws ReflectionException
1774
+	 * @since   $VID:$
1775
+	 */
1776
+	public function isNotHidden(): int
1777
+	{
1778
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1779
+	}
1780
+
1781
+
1782
+	/**
1783
+	 * @return int
1784
+	 * @throws EE_Error
1785
+	 * @throws ReflectionException
1786
+	 * @since   $VID:$
1787
+	 */
1788
+	public function isPublicOnly(): int
1789
+	{
1790
+		return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 * @return int
1796
+	 * @throws EE_Error
1797
+	 * @throws ReflectionException
1798
+	 * @since   $VID:$
1799
+	 */
1800
+	public function isMembersOnly(): int
1801
+	{
1802
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1803
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1804
+	}
1805
+
1806
+
1807
+	/**
1808
+	 * @return int
1809
+	 * @throws EE_Error
1810
+	 * @throws ReflectionException
1811
+	 * @since   $VID:$
1812
+	 */
1813
+	public function isAdminsOnly(): int
1814
+	{
1815
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1816
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1817
+	}
1818
+
1819
+
1820
+	/**
1821
+	 * @return int
1822
+	 * @throws EE_Error
1823
+	 * @throws ReflectionException
1824
+	 * @since   $VID:$
1825
+	 */
1826
+	public function isAdminUiOnly(): int
1827
+	{
1828
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1829
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1830
+	}
1831
+
1832
+
1833
+	/**
1834
+	 * @param int $visibility
1835
+	 * @throws EE_Error
1836
+	 * @throws ReflectionException
1837
+	 * @since   $VID:$
1838
+	 */
1839
+	public function set_visibility(int $visibility)
1840
+	{
1841
+
1842
+		$ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1843
+		$ticket_visibility         = -1;
1844
+		foreach ($ticket_visibility_options as $ticket_visibility_option) {
1845
+			if ($visibility === $ticket_visibility_option) {
1846
+				$ticket_visibility = $visibility;
1847
+			}
1848
+		}
1849
+		if ($ticket_visibility === -1) {
1850
+			throw new DomainException(
1851
+				sprintf(
1852
+					esc_html__(
1853
+						'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1854
+						'event_espresso'
1855
+					),
1856
+					$visibility,
1857
+					'<br />',
1858
+					var_export($ticket_visibility_options, true)
1859
+				)
1860
+			);
1861
+		}
1862
+		$this->set('TKT_visibility', $ticket_visibility);
1863
+	}
1864
+
1865
+
1866
+	/**
1867
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1868
+	 * @param string                   $relationName
1869
+	 * @param array                    $extra_join_model_fields_n_values
1870
+	 * @param string|null              $cache_id
1871
+	 * @return EE_Base_Class
1872
+	 * @throws EE_Error
1873
+	 * @throws ReflectionException
1874
+	 * @since   $VID:$
1875
+	 */
1876
+	public function _add_relation_to(
1877
+		$otherObjectModelObjectOrID,
1878
+		$relationName,
1879
+		$extra_join_model_fields_n_values = [],
1880
+		$cache_id = null
1881
+	) {
1882
+		if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1883
+			/** @var EE_Datetime $datetime */
1884
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1885
+			$datetime->increaseSold($this->sold(), false);
1886
+			$datetime->increaseReserved($this->reserved());
1887
+			$datetime->save();
1888
+			$otherObjectModelObjectOrID = $datetime;
1889
+		}
1890
+		return parent::_add_relation_to(
1891
+			$otherObjectModelObjectOrID,
1892
+			$relationName,
1893
+			$extra_join_model_fields_n_values,
1894
+			$cache_id
1895
+		);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1901
+	 * @param string                   $relationName
1902
+	 * @param array                    $where_query
1903
+	 * @return bool|EE_Base_Class|null
1904
+	 * @throws EE_Error
1905
+	 * @throws ReflectionException
1906
+	 * @since   $VID:$
1907
+	 */
1908
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1909
+	{
1910
+		// if we're adding a new relation to a datetime
1911
+		if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1912
+			/** @var EE_Datetime $datetime */
1913
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1914
+			$datetime->decreaseSold($this->sold());
1915
+			$datetime->decreaseReserved($this->reserved());
1916
+			$datetime->save();
1917
+			$otherObjectModelObjectOrID = $datetime;
1918
+		}
1919
+		return parent::_remove_relation_to(
1920
+			$otherObjectModelObjectOrID,
1921
+			$relationName,
1922
+			$where_query
1923
+		);
1924
+	}
1925
+
1926
+
1927
+	/**
1928
+	 * Removes ALL the related things for the $relationName.
1929
+	 *
1930
+	 * @param string $relationName
1931
+	 * @param array  $where_query_params
1932
+	 * @return EE_Base_Class
1933
+	 * @throws ReflectionException
1934
+	 * @throws InvalidArgumentException
1935
+	 * @throws InvalidInterfaceException
1936
+	 * @throws InvalidDataTypeException
1937
+	 * @throws EE_Error
1938
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1939
+	 */
1940
+	public function _remove_relations($relationName, $where_query_params = [])
1941
+	{
1942
+		if ($relationName === 'Datetime') {
1943
+			$datetimes = $this->datetimes();
1944
+			foreach ($datetimes as $datetime) {
1945
+				$datetime->decreaseSold($this->sold());
1946
+				$datetime->decreaseReserved($this->reserved());
1947
+				$datetime->save();
1948
+			}
1949
+		}
1950
+		return parent::_remove_relations($relationName, $where_query_params);
1951
+	}
1952
+
1953
+
1954
+	/*******************************************************************
1955 1955
      ***********************  DEPRECATED METHODS  **********************
1956 1956
      *******************************************************************/
1957 1957
 
1958 1958
 
1959
-    /**
1960
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1961
-     * associated datetimes.
1962
-     *
1963
-     * @param int $qty
1964
-     * @return void
1965
-     * @throws EE_Error
1966
-     * @throws InvalidArgumentException
1967
-     * @throws InvalidDataTypeException
1968
-     * @throws InvalidInterfaceException
1969
-     * @throws ReflectionException
1970
-     * @deprecated 4.9.80.p
1971
-     */
1972
-    public function increase_sold($qty = 1)
1973
-    {
1974
-        EE_Error::doing_it_wrong(
1975
-            __FUNCTION__,
1976
-            esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1977
-            '4.9.80.p',
1978
-            '5.0.0.p'
1979
-        );
1980
-        $this->increaseSold($qty);
1981
-    }
1982
-
1983
-
1984
-    /**
1985
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1986
-     *
1987
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1988
-     *                 Negative means to decreases old counts (and increase reserved counts).
1989
-     * @throws EE_Error
1990
-     * @throws InvalidArgumentException
1991
-     * @throws InvalidDataTypeException
1992
-     * @throws InvalidInterfaceException
1993
-     * @throws ReflectionException
1994
-     * @deprecated 4.9.80.p
1995
-     */
1996
-    protected function _increase_sold_for_datetimes($qty)
1997
-    {
1998
-        EE_Error::doing_it_wrong(
1999
-            __FUNCTION__,
2000
-            esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2001
-            '4.9.80.p',
2002
-            '5.0.0.p'
2003
-        );
2004
-        $this->increaseSoldForDatetimes($qty);
2005
-    }
2006
-
2007
-
2008
-    /**
2009
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2010
-     * DB and then updates the model objects.
2011
-     * Does not affect the reserved counts.
2012
-     *
2013
-     * @param int $qty
2014
-     * @return void
2015
-     * @throws EE_Error
2016
-     * @throws InvalidArgumentException
2017
-     * @throws InvalidDataTypeException
2018
-     * @throws InvalidInterfaceException
2019
-     * @throws ReflectionException
2020
-     * @deprecated 4.9.80.p
2021
-     */
2022
-    public function decrease_sold($qty = 1)
2023
-    {
2024
-        EE_Error::doing_it_wrong(
2025
-            __FUNCTION__,
2026
-            esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2027
-            '4.9.80.p',
2028
-            '5.0.0.p'
2029
-        );
2030
-        $this->decreaseSold($qty);
2031
-    }
2032
-
2033
-
2034
-    /**
2035
-     * Decreases sold on related datetimes
2036
-     *
2037
-     * @param int $qty
2038
-     * @return void
2039
-     * @throws EE_Error
2040
-     * @throws InvalidArgumentException
2041
-     * @throws InvalidDataTypeException
2042
-     * @throws InvalidInterfaceException
2043
-     * @throws ReflectionException
2044
-     * @deprecated 4.9.80.p
2045
-     */
2046
-    protected function _decrease_sold_for_datetimes($qty = 1)
2047
-    {
2048
-        EE_Error::doing_it_wrong(
2049
-            __FUNCTION__,
2050
-            esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2051
-            '4.9.80.p',
2052
-            '5.0.0.p'
2053
-        );
2054
-        $this->decreaseSoldForDatetimes($qty);
2055
-    }
2056
-
2057
-
2058
-    /**
2059
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2060
-     *
2061
-     * @param int    $qty
2062
-     * @param string $source
2063
-     * @return bool whether we successfully reserved the ticket or not.
2064
-     * @throws EE_Error
2065
-     * @throws InvalidArgumentException
2066
-     * @throws ReflectionException
2067
-     * @throws InvalidDataTypeException
2068
-     * @throws InvalidInterfaceException
2069
-     * @deprecated 4.9.80.p
2070
-     */
2071
-    public function increase_reserved($qty = 1, $source = 'unknown')
2072
-    {
2073
-        EE_Error::doing_it_wrong(
2074
-            __FUNCTION__,
2075
-            esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2076
-            '4.9.80.p',
2077
-            '5.0.0.p'
2078
-        );
2079
-        return $this->increaseReserved($qty);
2080
-    }
2081
-
2082
-
2083
-    /**
2084
-     * Increases sold on related datetimes
2085
-     *
2086
-     * @param int $qty
2087
-     * @return boolean indicating success
2088
-     * @throws EE_Error
2089
-     * @throws InvalidArgumentException
2090
-     * @throws InvalidDataTypeException
2091
-     * @throws InvalidInterfaceException
2092
-     * @throws ReflectionException
2093
-     * @deprecated 4.9.80.p
2094
-     */
2095
-    protected function _increase_reserved_for_datetimes($qty = 1)
2096
-    {
2097
-        EE_Error::doing_it_wrong(
2098
-            __FUNCTION__,
2099
-            esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2100
-            '4.9.80.p',
2101
-            '5.0.0.p'
2102
-        );
2103
-        return $this->increaseReservedForDatetimes($qty);
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2109
-     *
2110
-     * @param int    $qty
2111
-     * @param bool   $adjust_datetimes
2112
-     * @param string $source
2113
-     * @return void
2114
-     * @throws EE_Error
2115
-     * @throws InvalidArgumentException
2116
-     * @throws ReflectionException
2117
-     * @throws InvalidDataTypeException
2118
-     * @throws InvalidInterfaceException
2119
-     * @deprecated 4.9.80.p
2120
-     */
2121
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2122
-    {
2123
-        EE_Error::doing_it_wrong(
2124
-            __FUNCTION__,
2125
-            esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2126
-            '4.9.80.p',
2127
-            '5.0.0.p'
2128
-        );
2129
-        $this->decreaseReserved($qty);
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Decreases reserved on related datetimes
2135
-     *
2136
-     * @param int $qty
2137
-     * @return void
2138
-     * @throws EE_Error
2139
-     * @throws InvalidArgumentException
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidDataTypeException
2142
-     * @throws InvalidInterfaceException
2143
-     * @deprecated 4.9.80.p
2144
-     */
2145
-    protected function _decrease_reserved_for_datetimes($qty = 1)
2146
-    {
2147
-        EE_Error::doing_it_wrong(
2148
-            __FUNCTION__,
2149
-            esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2150
-            '4.9.80.p',
2151
-            '5.0.0.p'
2152
-        );
2153
-        $this->decreaseReservedForDatetimes($qty);
2154
-    }
1959
+	/**
1960
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1961
+	 * associated datetimes.
1962
+	 *
1963
+	 * @param int $qty
1964
+	 * @return void
1965
+	 * @throws EE_Error
1966
+	 * @throws InvalidArgumentException
1967
+	 * @throws InvalidDataTypeException
1968
+	 * @throws InvalidInterfaceException
1969
+	 * @throws ReflectionException
1970
+	 * @deprecated 4.9.80.p
1971
+	 */
1972
+	public function increase_sold($qty = 1)
1973
+	{
1974
+		EE_Error::doing_it_wrong(
1975
+			__FUNCTION__,
1976
+			esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1977
+			'4.9.80.p',
1978
+			'5.0.0.p'
1979
+		);
1980
+		$this->increaseSold($qty);
1981
+	}
1982
+
1983
+
1984
+	/**
1985
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1986
+	 *
1987
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1988
+	 *                 Negative means to decreases old counts (and increase reserved counts).
1989
+	 * @throws EE_Error
1990
+	 * @throws InvalidArgumentException
1991
+	 * @throws InvalidDataTypeException
1992
+	 * @throws InvalidInterfaceException
1993
+	 * @throws ReflectionException
1994
+	 * @deprecated 4.9.80.p
1995
+	 */
1996
+	protected function _increase_sold_for_datetimes($qty)
1997
+	{
1998
+		EE_Error::doing_it_wrong(
1999
+			__FUNCTION__,
2000
+			esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2001
+			'4.9.80.p',
2002
+			'5.0.0.p'
2003
+		);
2004
+		$this->increaseSoldForDatetimes($qty);
2005
+	}
2006
+
2007
+
2008
+	/**
2009
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2010
+	 * DB and then updates the model objects.
2011
+	 * Does not affect the reserved counts.
2012
+	 *
2013
+	 * @param int $qty
2014
+	 * @return void
2015
+	 * @throws EE_Error
2016
+	 * @throws InvalidArgumentException
2017
+	 * @throws InvalidDataTypeException
2018
+	 * @throws InvalidInterfaceException
2019
+	 * @throws ReflectionException
2020
+	 * @deprecated 4.9.80.p
2021
+	 */
2022
+	public function decrease_sold($qty = 1)
2023
+	{
2024
+		EE_Error::doing_it_wrong(
2025
+			__FUNCTION__,
2026
+			esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2027
+			'4.9.80.p',
2028
+			'5.0.0.p'
2029
+		);
2030
+		$this->decreaseSold($qty);
2031
+	}
2032
+
2033
+
2034
+	/**
2035
+	 * Decreases sold on related datetimes
2036
+	 *
2037
+	 * @param int $qty
2038
+	 * @return void
2039
+	 * @throws EE_Error
2040
+	 * @throws InvalidArgumentException
2041
+	 * @throws InvalidDataTypeException
2042
+	 * @throws InvalidInterfaceException
2043
+	 * @throws ReflectionException
2044
+	 * @deprecated 4.9.80.p
2045
+	 */
2046
+	protected function _decrease_sold_for_datetimes($qty = 1)
2047
+	{
2048
+		EE_Error::doing_it_wrong(
2049
+			__FUNCTION__,
2050
+			esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2051
+			'4.9.80.p',
2052
+			'5.0.0.p'
2053
+		);
2054
+		$this->decreaseSoldForDatetimes($qty);
2055
+	}
2056
+
2057
+
2058
+	/**
2059
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2060
+	 *
2061
+	 * @param int    $qty
2062
+	 * @param string $source
2063
+	 * @return bool whether we successfully reserved the ticket or not.
2064
+	 * @throws EE_Error
2065
+	 * @throws InvalidArgumentException
2066
+	 * @throws ReflectionException
2067
+	 * @throws InvalidDataTypeException
2068
+	 * @throws InvalidInterfaceException
2069
+	 * @deprecated 4.9.80.p
2070
+	 */
2071
+	public function increase_reserved($qty = 1, $source = 'unknown')
2072
+	{
2073
+		EE_Error::doing_it_wrong(
2074
+			__FUNCTION__,
2075
+			esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2076
+			'4.9.80.p',
2077
+			'5.0.0.p'
2078
+		);
2079
+		return $this->increaseReserved($qty);
2080
+	}
2081
+
2082
+
2083
+	/**
2084
+	 * Increases sold on related datetimes
2085
+	 *
2086
+	 * @param int $qty
2087
+	 * @return boolean indicating success
2088
+	 * @throws EE_Error
2089
+	 * @throws InvalidArgumentException
2090
+	 * @throws InvalidDataTypeException
2091
+	 * @throws InvalidInterfaceException
2092
+	 * @throws ReflectionException
2093
+	 * @deprecated 4.9.80.p
2094
+	 */
2095
+	protected function _increase_reserved_for_datetimes($qty = 1)
2096
+	{
2097
+		EE_Error::doing_it_wrong(
2098
+			__FUNCTION__,
2099
+			esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2100
+			'4.9.80.p',
2101
+			'5.0.0.p'
2102
+		);
2103
+		return $this->increaseReservedForDatetimes($qty);
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2109
+	 *
2110
+	 * @param int    $qty
2111
+	 * @param bool   $adjust_datetimes
2112
+	 * @param string $source
2113
+	 * @return void
2114
+	 * @throws EE_Error
2115
+	 * @throws InvalidArgumentException
2116
+	 * @throws ReflectionException
2117
+	 * @throws InvalidDataTypeException
2118
+	 * @throws InvalidInterfaceException
2119
+	 * @deprecated 4.9.80.p
2120
+	 */
2121
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2122
+	{
2123
+		EE_Error::doing_it_wrong(
2124
+			__FUNCTION__,
2125
+			esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2126
+			'4.9.80.p',
2127
+			'5.0.0.p'
2128
+		);
2129
+		$this->decreaseReserved($qty);
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Decreases reserved on related datetimes
2135
+	 *
2136
+	 * @param int $qty
2137
+	 * @return void
2138
+	 * @throws EE_Error
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidDataTypeException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @deprecated 4.9.80.p
2144
+	 */
2145
+	protected function _decrease_reserved_for_datetimes($qty = 1)
2146
+	{
2147
+		EE_Error::doing_it_wrong(
2148
+			__FUNCTION__,
2149
+			esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2150
+			'4.9.80.p',
2151
+			'5.0.0.p'
2152
+		);
2153
+		$this->decreaseReservedForDatetimes($qty);
2154
+	}
2155 2155
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 2 patches
Indentation   +1593 added lines, -1593 removed lines patch added patch discarded remove patch
@@ -16,1600 +16,1600 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
18 18
 {
19
-    /**
20
-     * cached value for the the logical active status for the event
21
-     *
22
-     * @see get_active_status()
23
-     * @var string
24
-     */
25
-    protected $_active_status = '';
26
-
27
-    /**
28
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
-     *
30
-     * @var EE_Datetime
31
-     */
32
-    protected $_Primary_Datetime;
33
-
34
-    /**
35
-     * @var EventSpacesCalculator $available_spaces_calculator
36
-     */
37
-    protected $available_spaces_calculator;
38
-
39
-
40
-    /**
41
-     * @param array  $props_n_values          incoming values
42
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
-     *                                        used.)
44
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
-     *                                        date_format and the second value is the time format
46
-     * @return EE_Event
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = []): EE_Event
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
-    }
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values  incoming values from the database
59
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
-     *                                the website will be used.
61
-     * @return EE_Event
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public static function new_instance_from_db($props_n_values = [], $timezone = null): EE_Event
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-    /**
72
-     * @return EventSpacesCalculator
73
-     * @throws EE_Error
74
-     * @throws ReflectionException
75
-     */
76
-    public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
-    {
78
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-    /**
86
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
-     *
88
-     * @param string $field_name
89
-     * @param mixed  $field_value
90
-     * @param bool   $use_default
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status':
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default:
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @param string $status
113
-     * @param bool   $use_default
114
-     * @return void
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function set_status($status = '', $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($status) && ! $use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $status) {
128
-            // TO sold_out
129
-            if ($status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
-                // OR FROM  sold_out
134
-            } elseif ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
-            }
138
-            // clear out the active status so that it gets reset the next time it is requested
139
-            $this->_active_status = null;
140
-            // update status
141
-            parent::set('status', $status, $use_default);
142
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
143
-            return;
144
-        }
145
-        // even though the old value matches the new value, it's still good to
146
-        // allow the parent set method to have a say
147
-        parent::set('status', $status, $use_default);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets all the datetimes for this event
153
-     *
154
-     * @param array|null $query_params
155
-     * @return EE_Base_Class[]|EE_Datetime[]
156
-     * @throws EE_Error
157
-     * @throws ReflectionException
158
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
-     */
160
-    public function datetimes(?array $query_params = []): array
161
-    {
162
-        return $this->get_many_related('Datetime', $query_params);
163
-    }
164
-
165
-
166
-    /**
167
-     * Gets all the datetimes for this event that are currently ACTIVE,
168
-     * meaning the datetime has started and has not yet ended.
169
-     *
170
-     * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
-     * @param array|null $query_params will recursively replace default values
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
-     */
176
-    public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
-    {
178
-        // if start date is null, then use current time
179
-        $start_date = $start_date ?? time();
180
-        $where      = [];
181
-        if ($start_date) {
182
-            $where['DTT_EVT_start'] = ['<', $start_date];
183
-            $where['DTT_EVT_end']   = ['>', time()];
184
-        }
185
-        $query_params = array_replace_recursive(
186
-            [
187
-                $where,
188
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
189
-            ],
190
-            $query_params
191
-        );
192
-        return $this->get_many_related('Datetime', $query_params);
193
-    }
194
-
195
-
196
-    /**
197
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
-     *
199
-     * @return EE_Base_Class[]|EE_Datetime[]
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function datetimes_in_chronological_order(): array
204
-    {
205
-        return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
-    }
207
-
208
-
209
-    /**
210
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
-     * after running our query, so that this timezone isn't set for EVERY query
213
-     * on EEM_Datetime for the rest of the request, no?
214
-     *
215
-     * @param bool     $show_expired whether or not to include expired events
216
-     * @param bool     $show_deleted whether or not to include deleted events
217
-     * @param int|null $limit
218
-     * @return EE_Datetime[]
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
-    {
224
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
-            $this->ID(),
226
-            $show_expired,
227
-            $show_deleted,
228
-            $limit
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * Returns one related datetime. Mostly only used by some legacy code.
235
-     *
236
-     * @return EE_Base_Class|EE_Datetime
237
-     * @throws EE_Error
238
-     * @throws ReflectionException
239
-     */
240
-    public function first_datetime(): EE_Datetime
241
-    {
242
-        return $this->get_first_related('Datetime');
243
-    }
244
-
245
-
246
-    /**
247
-     * Returns the 'primary' datetime for the event
248
-     *
249
-     * @param bool $try_to_exclude_expired
250
-     * @param bool $try_to_exclude_deleted
251
-     * @return EE_Datetime|null
252
-     * @throws EE_Error
253
-     * @throws ReflectionException
254
-     */
255
-    public function primary_datetime(
256
-        bool $try_to_exclude_expired = true,
257
-        bool $try_to_exclude_deleted = true
258
-    ): ?EE_Datetime {
259
-        if (! empty($this->_Primary_Datetime)) {
260
-            return $this->_Primary_Datetime;
261
-        }
262
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
-            $this->ID(),
264
-            $try_to_exclude_expired,
265
-            $try_to_exclude_deleted
266
-        );
267
-        return $this->_Primary_Datetime;
268
-    }
269
-
270
-
271
-    /**
272
-     * Gets all the tickets available for purchase of this event
273
-     *
274
-     * @param array|null $query_params
275
-     * @return EE_Base_Class[]|EE_Ticket[]
276
-     * @throws EE_Error
277
-     * @throws ReflectionException
278
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
-     */
280
-    public function tickets(?array $query_params = []): array
281
-    {
282
-        // first get all datetimes
283
-        $datetimes = $this->datetimes_ordered();
284
-        if (! $datetimes) {
285
-            return [];
286
-        }
287
-        $datetime_ids = [];
288
-        foreach ($datetimes as $datetime) {
289
-            $datetime_ids[] = $datetime->ID();
290
-        }
291
-        $where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
-        // if incoming $query_params has where conditions let's merge but not override existing.
293
-        if (is_array($query_params) && isset($query_params[0])) {
294
-            $where_params = array_merge($query_params[0], $where_params);
295
-            unset($query_params[0]);
296
-        }
297
-        // now add $where_params to $query_params
298
-        $query_params[0] = $where_params;
299
-        return EEM_Ticket::instance()->get_all($query_params);
300
-    }
301
-
302
-
303
-    /**
304
-     * get all unexpired not-trashed tickets
305
-     *
306
-     * @return EE_Ticket[]
307
-     * @throws EE_Error
308
-     * @throws ReflectionException
309
-     */
310
-    public function active_tickets(): array
311
-    {
312
-        return $this->tickets(
313
-            [
314
-                [
315
-                    'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
-                    'TKT_deleted'  => false,
317
-                ],
318
-            ]
319
-        );
320
-    }
321
-
322
-
323
-    /**
324
-     * @return int
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public function additional_limit(): int
329
-    {
330
-        return $this->get('EVT_additional_limit');
331
-    }
332
-
333
-
334
-    /**
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @throws ReflectionException
338
-     */
339
-    public function allow_overflow(): bool
340
-    {
341
-        return $this->get('EVT_allow_overflow');
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function created(): string
351
-    {
352
-        return $this->get('EVT_created');
353
-    }
354
-
355
-
356
-    /**
357
-     * @return string
358
-     * @throws EE_Error
359
-     * @throws ReflectionException
360
-     */
361
-    public function description(): string
362
-    {
363
-        return $this->get('EVT_desc');
364
-    }
365
-
366
-
367
-    /**
368
-     * Runs do_shortcode and wpautop on the description
369
-     *
370
-     * @return string of html
371
-     * @throws EE_Error
372
-     * @throws ReflectionException
373
-     */
374
-    public function description_filtered(): string
375
-    {
376
-        return $this->get_pretty('EVT_desc');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     * @throws ReflectionException
384
-     */
385
-    public function display_description(): bool
386
-    {
387
-        return $this->get('EVT_display_desc');
388
-    }
389
-
390
-
391
-    /**
392
-     * @return bool
393
-     * @throws EE_Error
394
-     * @throws ReflectionException
395
-     */
396
-    public function display_ticket_selector(): bool
397
-    {
398
-        return (bool) $this->get('EVT_display_ticket_selector');
399
-    }
400
-
401
-
402
-    /**
403
-     * @return string
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    public function external_url(): string
408
-    {
409
-        return $this->get('EVT_external_URL');
410
-    }
411
-
412
-
413
-    /**
414
-     * @return bool
415
-     * @throws EE_Error
416
-     * @throws ReflectionException
417
-     */
418
-    public function member_only(): bool
419
-    {
420
-        return $this->get('EVT_member_only');
421
-    }
422
-
423
-
424
-    /**
425
-     * @return string
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function phone(): string
430
-    {
431
-        return $this->get('EVT_phone');
432
-    }
433
-
434
-
435
-    /**
436
-     * @return string
437
-     * @throws EE_Error
438
-     * @throws ReflectionException
439
-     */
440
-    public function modified(): string
441
-    {
442
-        return $this->get('EVT_modified');
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function name(): string
452
-    {
453
-        return $this->get('EVT_name');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return int
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function order(): int
463
-    {
464
-        return $this->get('EVT_order');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function default_registration_status(): string
474
-    {
475
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
476
-        return ! empty($event_default_registration_status)
477
-            ? $event_default_registration_status
478
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
479
-    }
480
-
481
-
482
-    /**
483
-     * @param int|null    $num_words
484
-     * @param string|null $more
485
-     * @param bool        $not_full_desc
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
-    {
492
-        $short_desc = $this->get('EVT_short_desc');
493
-        if (! empty($short_desc) || $not_full_desc) {
494
-            return $short_desc;
495
-        }
496
-        $full_desc = $this->get('EVT_desc');
497
-        return wp_trim_words($full_desc, $num_words, $more);
498
-    }
499
-
500
-
501
-    /**
502
-     * @return string
503
-     * @throws EE_Error
504
-     * @throws ReflectionException
505
-     */
506
-    public function slug(): string
507
-    {
508
-        return $this->get('EVT_slug');
509
-    }
510
-
511
-
512
-    /**
513
-     * @return string
514
-     * @throws EE_Error
515
-     * @throws ReflectionException
516
-     */
517
-    public function timezone_string(): string
518
-    {
519
-        return $this->get('EVT_timezone_string');
520
-    }
521
-
522
-
523
-    /**
524
-     * @return string
525
-     * @throws EE_Error
526
-     * @throws ReflectionException
527
-     */
528
-    public function visible_on(): string
529
-    {
530
-        return $this->get('EVT_visible_on');
531
-    }
532
-
533
-
534
-    /**
535
-     * @return int
536
-     * @throws EE_Error
537
-     * @throws ReflectionException
538
-     */
539
-    public function wp_user(): int
540
-    {
541
-        return $this->get('EVT_wp_user');
542
-    }
543
-
544
-
545
-    /**
546
-     * @return bool
547
-     * @throws EE_Error
548
-     * @throws ReflectionException
549
-     */
550
-    public function donations(): bool
551
-    {
552
-        return $this->get('EVT_donations');
553
-    }
554
-
555
-
556
-    /**
557
-     * @param int $limit
558
-     * @throws EE_Error
559
-     * @throws ReflectionException
560
-     */
561
-    public function set_additional_limit(int $limit)
562
-    {
563
-        $this->set('EVT_additional_limit', $limit);
564
-    }
565
-
566
-
567
-    /**
568
-     * @param $created
569
-     * @throws EE_Error
570
-     * @throws ReflectionException
571
-     */
572
-    public function set_created($created)
573
-    {
574
-        $this->set('EVT_created', $created);
575
-    }
576
-
577
-
578
-    /**
579
-     * @param $desc
580
-     * @throws EE_Error
581
-     * @throws ReflectionException
582
-     */
583
-    public function set_description($desc)
584
-    {
585
-        $this->set('EVT_desc', $desc);
586
-    }
587
-
588
-
589
-    /**
590
-     * @param $display_desc
591
-     * @throws EE_Error
592
-     * @throws ReflectionException
593
-     */
594
-    public function set_display_description($display_desc)
595
-    {
596
-        $this->set('EVT_display_desc', $display_desc);
597
-    }
598
-
599
-
600
-    /**
601
-     * @param $display_ticket_selector
602
-     * @throws EE_Error
603
-     * @throws ReflectionException
604
-     */
605
-    public function set_display_ticket_selector($display_ticket_selector)
606
-    {
607
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $external_url
613
-     * @throws EE_Error
614
-     * @throws ReflectionException
615
-     */
616
-    public function set_external_url($external_url)
617
-    {
618
-        $this->set('EVT_external_URL', $external_url);
619
-    }
620
-
621
-
622
-    /**
623
-     * @param $member_only
624
-     * @throws EE_Error
625
-     * @throws ReflectionException
626
-     */
627
-    public function set_member_only($member_only)
628
-    {
629
-        $this->set('EVT_member_only', $member_only);
630
-    }
631
-
632
-
633
-    /**
634
-     * @param $event_phone
635
-     * @throws EE_Error
636
-     * @throws ReflectionException
637
-     */
638
-    public function set_event_phone($event_phone)
639
-    {
640
-        $this->set('EVT_phone', $event_phone);
641
-    }
642
-
643
-
644
-    /**
645
-     * @param $modified
646
-     * @throws EE_Error
647
-     * @throws ReflectionException
648
-     */
649
-    public function set_modified($modified)
650
-    {
651
-        $this->set('EVT_modified', $modified);
652
-    }
653
-
654
-
655
-    /**
656
-     * @param $name
657
-     * @throws EE_Error
658
-     * @throws ReflectionException
659
-     */
660
-    public function set_name($name)
661
-    {
662
-        $this->set('EVT_name', $name);
663
-    }
664
-
665
-
666
-    /**
667
-     * @param $order
668
-     * @throws EE_Error
669
-     * @throws ReflectionException
670
-     */
671
-    public function set_order($order)
672
-    {
673
-        $this->set('EVT_order', $order);
674
-    }
675
-
676
-
677
-    /**
678
-     * @param $short_desc
679
-     * @throws EE_Error
680
-     * @throws ReflectionException
681
-     */
682
-    public function set_short_description($short_desc)
683
-    {
684
-        $this->set('EVT_short_desc', $short_desc);
685
-    }
686
-
687
-
688
-    /**
689
-     * @param $slug
690
-     * @throws EE_Error
691
-     * @throws ReflectionException
692
-     */
693
-    public function set_slug($slug)
694
-    {
695
-        $this->set('EVT_slug', $slug);
696
-    }
697
-
698
-
699
-    /**
700
-     * @param $timezone_string
701
-     * @throws EE_Error
702
-     * @throws ReflectionException
703
-     */
704
-    public function set_timezone_string($timezone_string)
705
-    {
706
-        $this->set('EVT_timezone_string', $timezone_string);
707
-    }
708
-
709
-
710
-    /**
711
-     * @param $visible_on
712
-     * @throws EE_Error
713
-     * @throws ReflectionException
714
-     */
715
-    public function set_visible_on($visible_on)
716
-    {
717
-        $this->set('EVT_visible_on', $visible_on);
718
-    }
719
-
720
-
721
-    /**
722
-     * @param $wp_user
723
-     * @throws EE_Error
724
-     * @throws ReflectionException
725
-     */
726
-    public function set_wp_user($wp_user)
727
-    {
728
-        $this->set('EVT_wp_user', $wp_user);
729
-    }
730
-
731
-
732
-    /**
733
-     * @param $default_registration_status
734
-     * @throws EE_Error
735
-     * @throws ReflectionException
736
-     */
737
-    public function set_default_registration_status($default_registration_status)
738
-    {
739
-        $this->set('EVT_default_registration_status', $default_registration_status);
740
-    }
741
-
742
-
743
-    /**
744
-     * @param $donations
745
-     * @throws EE_Error
746
-     * @throws ReflectionException
747
-     */
748
-    public function set_donations($donations)
749
-    {
750
-        $this->set('EVT_donations', $donations);
751
-    }
752
-
753
-
754
-    /**
755
-     * Adds a venue to this event
756
-     *
757
-     * @param int|EE_Venue /int $venue_id_or_obj
758
-     * @return EE_Base_Class|EE_Venue
759
-     * @throws EE_Error
760
-     * @throws ReflectionException
761
-     */
762
-    public function add_venue($venue_id_or_obj): EE_Venue
763
-    {
764
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
765
-    }
766
-
767
-
768
-    /**
769
-     * Removes a venue from the event
770
-     *
771
-     * @param EE_Venue /int $venue_id_or_obj
772
-     * @return EE_Base_Class|EE_Venue
773
-     * @throws EE_Error
774
-     * @throws ReflectionException
775
-     */
776
-    public function remove_venue($venue_id_or_obj): EE_Venue
777
-    {
778
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
779
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
780
-    }
781
-
782
-
783
-    /**
784
-     * Gets the venue related to the event. May provide additional $query_params if desired
785
-     *
786
-     * @param array $query_params
787
-     * @return int
788
-     * @throws EE_Error
789
-     * @throws ReflectionException
790
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
791
-     */
792
-    public function venue_ID(array $query_params = []): int
793
-    {
794
-        $venue = $this->get_first_related('Venue', $query_params);
795
-        return $venue instanceof EE_Venue ? $venue->ID() : 0;
796
-    }
797
-
798
-
799
-    /**
800
-     * Gets the venue related to the event. May provide additional $query_params if desired
801
-     *
802
-     * @param array $query_params
803
-     * @return EE_Base_Class|EE_Venue
804
-     * @throws EE_Error
805
-     * @throws ReflectionException
806
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
807
-     */
808
-    public function venue(array $query_params = []): EE_Venue
809
-    {
810
-        return $this->get_first_related('Venue', $query_params);
811
-    }
812
-
813
-
814
-    /**
815
-     * @param array $query_params
816
-     * @return EE_Base_Class[]|EE_Venue[]
817
-     * @throws EE_Error
818
-     * @throws ReflectionException
819
-     * @deprecated $VID:$
820
-     */
821
-    public function venues(array $query_params = []): array
822
-    {
823
-        return [$this->venue($query_params)];
824
-    }
825
-
826
-
827
-    /**
828
-     * check if event id is present and if event is published
829
-     *
830
-     * @return boolean true yes, false no
831
-     * @throws EE_Error
832
-     * @throws ReflectionException
833
-     */
834
-    private function _has_ID_and_is_published(): bool
835
-    {
836
-        // first check if event id is present and not NULL,
837
-        // then check if this event is published (or any of the equivalent "published" statuses)
838
-        return
839
-            $this->ID() && $this->ID() !== null
840
-            && (
841
-                $this->status() === 'publish'
842
-                || $this->status() === EEM_Event::sold_out
843
-                || $this->status() === EEM_Event::postponed
844
-                || $this->status() === EEM_Event::cancelled
845
-            );
846
-    }
847
-
848
-
849
-    /**
850
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
851
-     *
852
-     * @return boolean true yes, false no
853
-     * @throws EE_Error
854
-     * @throws ReflectionException
855
-     */
856
-    public function is_upcoming(): bool
857
-    {
858
-        // check if event id is present and if this event is published
859
-        if ($this->is_inactive()) {
860
-            return false;
861
-        }
862
-        // set initial value
863
-        $upcoming = false;
864
-        // next let's get all datetimes and loop through them
865
-        $datetimes = $this->datetimes_in_chronological_order();
866
-        foreach ($datetimes as $datetime) {
867
-            if ($datetime instanceof EE_Datetime) {
868
-                // if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
869
-                if ($datetime->is_expired()) {
870
-                    continue;
871
-                }
872
-                // if this dtt is active then we return false.
873
-                if ($datetime->is_active()) {
874
-                    return false;
875
-                }
876
-                // otherwise let's check upcoming status
877
-                $upcoming = $datetime->is_upcoming();
878
-            }
879
-        }
880
-        return $upcoming;
881
-    }
882
-
883
-
884
-    /**
885
-     * @return bool
886
-     * @throws EE_Error
887
-     * @throws ReflectionException
888
-     */
889
-    public function is_active(): bool
890
-    {
891
-        // check if event id is present and if this event is published
892
-        if ($this->is_inactive()) {
893
-            return false;
894
-        }
895
-        // set initial value
896
-        $active = false;
897
-        // next let's get all datetimes and loop through them
898
-        $datetimes = $this->datetimes_in_chronological_order();
899
-        foreach ($datetimes as $datetime) {
900
-            if ($datetime instanceof EE_Datetime) {
901
-                // if this dtt is expired then we continue cause one of the other datetimes might be active.
902
-                if ($datetime->is_expired()) {
903
-                    continue;
904
-                }
905
-                // if this dtt is upcoming then we return false.
906
-                if ($datetime->is_upcoming()) {
907
-                    return false;
908
-                }
909
-                // otherwise let's check active status
910
-                $active = $datetime->is_active();
911
-            }
912
-        }
913
-        return $active;
914
-    }
915
-
916
-
917
-    /**
918
-     * @return bool
919
-     * @throws EE_Error
920
-     * @throws ReflectionException
921
-     */
922
-    public function is_expired(): bool
923
-    {
924
-        // check if event id is present and if this event is published
925
-        if ($this->is_inactive()) {
926
-            return false;
927
-        }
928
-        // set initial value
929
-        $expired = false;
930
-        // first let's get all datetimes and loop through them
931
-        $datetimes = $this->datetimes_in_chronological_order();
932
-        foreach ($datetimes as $datetime) {
933
-            if ($datetime instanceof EE_Datetime) {
934
-                // if this dtt is upcoming or active then we return false.
935
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
936
-                    return false;
937
-                }
938
-                // otherwise let's check active status
939
-                $expired = $datetime->is_expired();
940
-            }
941
-        }
942
-        return $expired;
943
-    }
944
-
945
-
946
-    /**
947
-     * @return bool
948
-     * @throws EE_Error
949
-     * @throws ReflectionException
950
-     */
951
-    public function is_inactive(): bool
952
-    {
953
-        // check if event id is present and if this event is published
954
-        if ($this->_has_ID_and_is_published()) {
955
-            return false;
956
-        }
957
-        return true;
958
-    }
959
-
960
-
961
-    /**
962
-     * calculate spaces remaining based on "saleable" tickets
963
-     *
964
-     * @param array|null $tickets
965
-     * @param bool       $filtered
966
-     * @return int|float
967
-     * @throws EE_Error
968
-     * @throws DomainException
969
-     * @throws UnexpectedEntityException
970
-     * @throws ReflectionException
971
-     */
972
-    public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
973
-    {
974
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
975
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
976
-        return $filtered
977
-            ? apply_filters(
978
-                'FHEE_EE_Event__spaces_remaining',
979
-                $spaces_remaining,
980
-                $this,
981
-                $tickets
982
-            )
983
-            : $spaces_remaining;
984
-    }
985
-
986
-
987
-    /**
988
-     *    perform_sold_out_status_check
989
-     *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
990
-     *    available... if NOT, then the event status will get toggled to 'sold_out'
991
-     *
992
-     * @return bool    return the ACTUAL sold out state.
993
-     * @throws EE_Error
994
-     * @throws DomainException
995
-     * @throws UnexpectedEntityException
996
-     * @throws ReflectionException
997
-     */
998
-    public function perform_sold_out_status_check(): bool
999
-    {
1000
-        // get all tickets
1001
-        $tickets     = $this->tickets(
1002
-            [
1003
-                'default_where_conditions' => 'none',
1004
-                'order_by'                 => ['TKT_qty' => 'ASC'],
1005
-            ]
1006
-        );
1007
-        $all_expired = true;
1008
-        foreach ($tickets as $ticket) {
1009
-            if (! $ticket->is_expired()) {
1010
-                $all_expired = false;
1011
-                break;
1012
-            }
1013
-        }
1014
-        // if all the tickets are just expired, then don't update the event status to sold out
1015
-        if ($all_expired) {
1016
-            return true;
1017
-        }
1018
-        $spaces_remaining = $this->spaces_remaining($tickets);
1019
-        if ($spaces_remaining < 1) {
1020
-            if ($this->status() !== EEM_CPT_Base::post_status_private) {
1021
-                $this->set_status(EEM_Event::sold_out);
1022
-                $this->save();
1023
-            }
1024
-            $sold_out = true;
1025
-        } else {
1026
-            $sold_out = false;
1027
-            // was event previously marked as sold out ?
1028
-            if ($this->status() === EEM_Event::sold_out) {
1029
-                // revert status to previous value, if it was set
1030
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
1031
-                if ($previous_event_status) {
1032
-                    $this->set_status($previous_event_status);
1033
-                    $this->save();
1034
-                }
1035
-            }
1036
-        }
1037
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1038
-        return $sold_out;
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * This returns the total remaining spaces for sale on this event.
1044
-     *
1045
-     * @return int|float
1046
-     * @throws EE_Error
1047
-     * @throws DomainException
1048
-     * @throws UnexpectedEntityException
1049
-     * @throws ReflectionException
1050
-     * @uses EE_Event::total_available_spaces()
1051
-     */
1052
-    public function spaces_remaining_for_sale()
1053
-    {
1054
-        return $this->total_available_spaces(true);
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * This returns the total spaces available for an event
1060
-     * while considering all the quantities on the tickets and the reg limits
1061
-     * on the datetimes attached to this event.
1062
-     *
1063
-     * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1064
-     *                              If this is false, then we return the most tickets that could ever be sold
1065
-     *                              for this event with the datetime and tickets setup on the event under optimal
1066
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
1067
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
1068
-     *                              may appear to equal remaining tickets.  However, the more tickets are
1069
-     *                              sold out, the more accurate the "live" total is.
1070
-     * @return int|float
1071
-     * @throws EE_Error
1072
-     * @throws DomainException
1073
-     * @throws UnexpectedEntityException
1074
-     * @throws ReflectionException
1075
-     */
1076
-    public function total_available_spaces(bool $consider_sold = false)
1077
-    {
1078
-        $spaces_available = $consider_sold
1079
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
1080
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1081
-        return apply_filters(
1082
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
1083
-            $spaces_available,
1084
-            $this,
1085
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
1086
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
1087
-        );
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Checks if the event is set to sold out
1093
-     *
1094
-     * @param bool $actual  whether or not to perform calculations to not only figure the
1095
-     *                      actual status but also to flip the status if necessary to sold
1096
-     *                      out If false, we just check the existing status of the event
1097
-     * @return boolean
1098
-     * @throws EE_Error
1099
-     * @throws ReflectionException
1100
-     */
1101
-    public function is_sold_out(bool $actual = false): bool
1102
-    {
1103
-        if (! $actual) {
1104
-            return $this->status() === EEM_Event::sold_out;
1105
-        }
1106
-        return $this->perform_sold_out_status_check();
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * Checks if the event is marked as postponed
1112
-     *
1113
-     * @return boolean
1114
-     */
1115
-    public function is_postponed(): bool
1116
-    {
1117
-        return $this->status() === EEM_Event::postponed;
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * Checks if the event is marked as cancelled
1123
-     *
1124
-     * @return boolean
1125
-     */
1126
-    public function is_cancelled(): bool
1127
-    {
1128
-        return $this->status() === EEM_Event::cancelled;
1129
-    }
1130
-
1131
-
1132
-    /**
1133
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1134
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1135
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1136
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1137
-     * the event is considered expired.
1138
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1139
-     * status set on the EVENT when it is not published and thus is done
1140
-     *
1141
-     * @param bool $reset
1142
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1143
-     * @throws EE_Error
1144
-     * @throws ReflectionException
1145
-     */
1146
-    public function get_active_status(bool $reset = false)
1147
-    {
1148
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1149
-        if (! empty($this->_active_status) && ! $reset) {
1150
-            return $this->_active_status;
1151
-        }
1152
-        // first check if event id is present on this object
1153
-        if (! $this->ID()) {
1154
-            return false;
1155
-        }
1156
-        $where_params_for_event = [['EVT_ID' => $this->ID()]];
1157
-        // if event is published:
1158
-        if (
1159
-            $this->status() === EEM_CPT_Base::post_status_publish
1160
-            || $this->status() === EEM_CPT_Base::post_status_private
1161
-        ) {
1162
-            // active?
1163
-            if (
1164
-                EEM_Datetime::instance()->get_datetime_count_for_status(
1165
-                    EE_Datetime::active,
1166
-                    $where_params_for_event
1167
-                ) > 0
1168
-            ) {
1169
-                $this->_active_status = EE_Datetime::active;
1170
-            } else {
1171
-                // upcoming?
1172
-                if (
1173
-                    EEM_Datetime::instance()->get_datetime_count_for_status(
1174
-                        EE_Datetime::upcoming,
1175
-                        $where_params_for_event
1176
-                    ) > 0
1177
-                ) {
1178
-                    $this->_active_status = EE_Datetime::upcoming;
1179
-                } else {
1180
-                    // expired?
1181
-                    if (
1182
-                        EEM_Datetime::instance()->get_datetime_count_for_status(
1183
-                            EE_Datetime::expired,
1184
-                            $where_params_for_event
1185
-                        ) > 0
1186
-                    ) {
1187
-                        $this->_active_status = EE_Datetime::expired;
1188
-                    } else {
1189
-                        // it would be odd if things make it this far
1190
-                        // because it basically means there are no datetimes attached to the event.
1191
-                        // So in this case it will just be considered inactive.
1192
-                        $this->_active_status = EE_Datetime::inactive;
1193
-                    }
1194
-                }
1195
-            }
1196
-        } else {
1197
-            // the event is not published, so let's just set it's active status according to its' post status
1198
-            switch ($this->status()) {
1199
-                case EEM_Event::sold_out:
1200
-                    $this->_active_status = EE_Datetime::sold_out;
1201
-                    break;
1202
-                case EEM_Event::cancelled:
1203
-                    $this->_active_status = EE_Datetime::cancelled;
1204
-                    break;
1205
-                case EEM_Event::postponed:
1206
-                    $this->_active_status = EE_Datetime::postponed;
1207
-                    break;
1208
-                default:
1209
-                    $this->_active_status = EE_Datetime::inactive;
1210
-            }
1211
-        }
1212
-        return $this->_active_status;
1213
-    }
1214
-
1215
-
1216
-    /**
1217
-     *    pretty_active_status
1218
-     *
1219
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1220
-     * @return string
1221
-     * @throws EE_Error
1222
-     * @throws ReflectionException
1223
-     */
1224
-    public function pretty_active_status(bool $echo = true): string
1225
-    {
1226
-        $active_status = $this->get_active_status();
1227
-        $status        = "
19
+	/**
20
+	 * cached value for the the logical active status for the event
21
+	 *
22
+	 * @see get_active_status()
23
+	 * @var string
24
+	 */
25
+	protected $_active_status = '';
26
+
27
+	/**
28
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
+	 *
30
+	 * @var EE_Datetime
31
+	 */
32
+	protected $_Primary_Datetime;
33
+
34
+	/**
35
+	 * @var EventSpacesCalculator $available_spaces_calculator
36
+	 */
37
+	protected $available_spaces_calculator;
38
+
39
+
40
+	/**
41
+	 * @param array  $props_n_values          incoming values
42
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
+	 *                                        used.)
44
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
+	 *                                        date_format and the second value is the time format
46
+	 * @return EE_Event
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = []): EE_Event
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
+	}
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values  incoming values from the database
59
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
+	 *                                the website will be used.
61
+	 * @return EE_Event
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = [], $timezone = null): EE_Event
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return EventSpacesCalculator
73
+	 * @throws EE_Error
74
+	 * @throws ReflectionException
75
+	 */
76
+	public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
+	{
78
+		if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+	/**
86
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
+	 *
88
+	 * @param string $field_name
89
+	 * @param mixed  $field_value
90
+	 * @param bool   $use_default
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status':
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default:
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @param string $status
113
+	 * @param bool   $use_default
114
+	 * @return void
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function set_status($status = '', $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($status) && ! $use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $status) {
128
+			// TO sold_out
129
+			if ($status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
+				// OR FROM  sold_out
134
+			} elseif ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
+			}
138
+			// clear out the active status so that it gets reset the next time it is requested
139
+			$this->_active_status = null;
140
+			// update status
141
+			parent::set('status', $status, $use_default);
142
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
143
+			return;
144
+		}
145
+		// even though the old value matches the new value, it's still good to
146
+		// allow the parent set method to have a say
147
+		parent::set('status', $status, $use_default);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets all the datetimes for this event
153
+	 *
154
+	 * @param array|null $query_params
155
+	 * @return EE_Base_Class[]|EE_Datetime[]
156
+	 * @throws EE_Error
157
+	 * @throws ReflectionException
158
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
+	 */
160
+	public function datetimes(?array $query_params = []): array
161
+	{
162
+		return $this->get_many_related('Datetime', $query_params);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Gets all the datetimes for this event that are currently ACTIVE,
168
+	 * meaning the datetime has started and has not yet ended.
169
+	 *
170
+	 * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
+	 * @param array|null $query_params will recursively replace default values
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
+	 */
176
+	public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
+	{
178
+		// if start date is null, then use current time
179
+		$start_date = $start_date ?? time();
180
+		$where      = [];
181
+		if ($start_date) {
182
+			$where['DTT_EVT_start'] = ['<', $start_date];
183
+			$where['DTT_EVT_end']   = ['>', time()];
184
+		}
185
+		$query_params = array_replace_recursive(
186
+			[
187
+				$where,
188
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
189
+			],
190
+			$query_params
191
+		);
192
+		return $this->get_many_related('Datetime', $query_params);
193
+	}
194
+
195
+
196
+	/**
197
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
+	 *
199
+	 * @return EE_Base_Class[]|EE_Datetime[]
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function datetimes_in_chronological_order(): array
204
+	{
205
+		return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
+	 * after running our query, so that this timezone isn't set for EVERY query
213
+	 * on EEM_Datetime for the rest of the request, no?
214
+	 *
215
+	 * @param bool     $show_expired whether or not to include expired events
216
+	 * @param bool     $show_deleted whether or not to include deleted events
217
+	 * @param int|null $limit
218
+	 * @return EE_Datetime[]
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
+	{
224
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
+			$this->ID(),
226
+			$show_expired,
227
+			$show_deleted,
228
+			$limit
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * Returns one related datetime. Mostly only used by some legacy code.
235
+	 *
236
+	 * @return EE_Base_Class|EE_Datetime
237
+	 * @throws EE_Error
238
+	 * @throws ReflectionException
239
+	 */
240
+	public function first_datetime(): EE_Datetime
241
+	{
242
+		return $this->get_first_related('Datetime');
243
+	}
244
+
245
+
246
+	/**
247
+	 * Returns the 'primary' datetime for the event
248
+	 *
249
+	 * @param bool $try_to_exclude_expired
250
+	 * @param bool $try_to_exclude_deleted
251
+	 * @return EE_Datetime|null
252
+	 * @throws EE_Error
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function primary_datetime(
256
+		bool $try_to_exclude_expired = true,
257
+		bool $try_to_exclude_deleted = true
258
+	): ?EE_Datetime {
259
+		if (! empty($this->_Primary_Datetime)) {
260
+			return $this->_Primary_Datetime;
261
+		}
262
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
+			$this->ID(),
264
+			$try_to_exclude_expired,
265
+			$try_to_exclude_deleted
266
+		);
267
+		return $this->_Primary_Datetime;
268
+	}
269
+
270
+
271
+	/**
272
+	 * Gets all the tickets available for purchase of this event
273
+	 *
274
+	 * @param array|null $query_params
275
+	 * @return EE_Base_Class[]|EE_Ticket[]
276
+	 * @throws EE_Error
277
+	 * @throws ReflectionException
278
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
+	 */
280
+	public function tickets(?array $query_params = []): array
281
+	{
282
+		// first get all datetimes
283
+		$datetimes = $this->datetimes_ordered();
284
+		if (! $datetimes) {
285
+			return [];
286
+		}
287
+		$datetime_ids = [];
288
+		foreach ($datetimes as $datetime) {
289
+			$datetime_ids[] = $datetime->ID();
290
+		}
291
+		$where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
+		// if incoming $query_params has where conditions let's merge but not override existing.
293
+		if (is_array($query_params) && isset($query_params[0])) {
294
+			$where_params = array_merge($query_params[0], $where_params);
295
+			unset($query_params[0]);
296
+		}
297
+		// now add $where_params to $query_params
298
+		$query_params[0] = $where_params;
299
+		return EEM_Ticket::instance()->get_all($query_params);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get all unexpired not-trashed tickets
305
+	 *
306
+	 * @return EE_Ticket[]
307
+	 * @throws EE_Error
308
+	 * @throws ReflectionException
309
+	 */
310
+	public function active_tickets(): array
311
+	{
312
+		return $this->tickets(
313
+			[
314
+				[
315
+					'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
+					'TKT_deleted'  => false,
317
+				],
318
+			]
319
+		);
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return int
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public function additional_limit(): int
329
+	{
330
+		return $this->get('EVT_additional_limit');
331
+	}
332
+
333
+
334
+	/**
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @throws ReflectionException
338
+	 */
339
+	public function allow_overflow(): bool
340
+	{
341
+		return $this->get('EVT_allow_overflow');
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function created(): string
351
+	{
352
+		return $this->get('EVT_created');
353
+	}
354
+
355
+
356
+	/**
357
+	 * @return string
358
+	 * @throws EE_Error
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function description(): string
362
+	{
363
+		return $this->get('EVT_desc');
364
+	}
365
+
366
+
367
+	/**
368
+	 * Runs do_shortcode and wpautop on the description
369
+	 *
370
+	 * @return string of html
371
+	 * @throws EE_Error
372
+	 * @throws ReflectionException
373
+	 */
374
+	public function description_filtered(): string
375
+	{
376
+		return $this->get_pretty('EVT_desc');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function display_description(): bool
386
+	{
387
+		return $this->get('EVT_display_desc');
388
+	}
389
+
390
+
391
+	/**
392
+	 * @return bool
393
+	 * @throws EE_Error
394
+	 * @throws ReflectionException
395
+	 */
396
+	public function display_ticket_selector(): bool
397
+	{
398
+		return (bool) $this->get('EVT_display_ticket_selector');
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return string
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	public function external_url(): string
408
+	{
409
+		return $this->get('EVT_external_URL');
410
+	}
411
+
412
+
413
+	/**
414
+	 * @return bool
415
+	 * @throws EE_Error
416
+	 * @throws ReflectionException
417
+	 */
418
+	public function member_only(): bool
419
+	{
420
+		return $this->get('EVT_member_only');
421
+	}
422
+
423
+
424
+	/**
425
+	 * @return string
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function phone(): string
430
+	{
431
+		return $this->get('EVT_phone');
432
+	}
433
+
434
+
435
+	/**
436
+	 * @return string
437
+	 * @throws EE_Error
438
+	 * @throws ReflectionException
439
+	 */
440
+	public function modified(): string
441
+	{
442
+		return $this->get('EVT_modified');
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function name(): string
452
+	{
453
+		return $this->get('EVT_name');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return int
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function order(): int
463
+	{
464
+		return $this->get('EVT_order');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function default_registration_status(): string
474
+	{
475
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
476
+		return ! empty($event_default_registration_status)
477
+			? $event_default_registration_status
478
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
479
+	}
480
+
481
+
482
+	/**
483
+	 * @param int|null    $num_words
484
+	 * @param string|null $more
485
+	 * @param bool        $not_full_desc
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
+	{
492
+		$short_desc = $this->get('EVT_short_desc');
493
+		if (! empty($short_desc) || $not_full_desc) {
494
+			return $short_desc;
495
+		}
496
+		$full_desc = $this->get('EVT_desc');
497
+		return wp_trim_words($full_desc, $num_words, $more);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @return string
503
+	 * @throws EE_Error
504
+	 * @throws ReflectionException
505
+	 */
506
+	public function slug(): string
507
+	{
508
+		return $this->get('EVT_slug');
509
+	}
510
+
511
+
512
+	/**
513
+	 * @return string
514
+	 * @throws EE_Error
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function timezone_string(): string
518
+	{
519
+		return $this->get('EVT_timezone_string');
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return string
525
+	 * @throws EE_Error
526
+	 * @throws ReflectionException
527
+	 */
528
+	public function visible_on(): string
529
+	{
530
+		return $this->get('EVT_visible_on');
531
+	}
532
+
533
+
534
+	/**
535
+	 * @return int
536
+	 * @throws EE_Error
537
+	 * @throws ReflectionException
538
+	 */
539
+	public function wp_user(): int
540
+	{
541
+		return $this->get('EVT_wp_user');
542
+	}
543
+
544
+
545
+	/**
546
+	 * @return bool
547
+	 * @throws EE_Error
548
+	 * @throws ReflectionException
549
+	 */
550
+	public function donations(): bool
551
+	{
552
+		return $this->get('EVT_donations');
553
+	}
554
+
555
+
556
+	/**
557
+	 * @param int $limit
558
+	 * @throws EE_Error
559
+	 * @throws ReflectionException
560
+	 */
561
+	public function set_additional_limit(int $limit)
562
+	{
563
+		$this->set('EVT_additional_limit', $limit);
564
+	}
565
+
566
+
567
+	/**
568
+	 * @param $created
569
+	 * @throws EE_Error
570
+	 * @throws ReflectionException
571
+	 */
572
+	public function set_created($created)
573
+	{
574
+		$this->set('EVT_created', $created);
575
+	}
576
+
577
+
578
+	/**
579
+	 * @param $desc
580
+	 * @throws EE_Error
581
+	 * @throws ReflectionException
582
+	 */
583
+	public function set_description($desc)
584
+	{
585
+		$this->set('EVT_desc', $desc);
586
+	}
587
+
588
+
589
+	/**
590
+	 * @param $display_desc
591
+	 * @throws EE_Error
592
+	 * @throws ReflectionException
593
+	 */
594
+	public function set_display_description($display_desc)
595
+	{
596
+		$this->set('EVT_display_desc', $display_desc);
597
+	}
598
+
599
+
600
+	/**
601
+	 * @param $display_ticket_selector
602
+	 * @throws EE_Error
603
+	 * @throws ReflectionException
604
+	 */
605
+	public function set_display_ticket_selector($display_ticket_selector)
606
+	{
607
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $external_url
613
+	 * @throws EE_Error
614
+	 * @throws ReflectionException
615
+	 */
616
+	public function set_external_url($external_url)
617
+	{
618
+		$this->set('EVT_external_URL', $external_url);
619
+	}
620
+
621
+
622
+	/**
623
+	 * @param $member_only
624
+	 * @throws EE_Error
625
+	 * @throws ReflectionException
626
+	 */
627
+	public function set_member_only($member_only)
628
+	{
629
+		$this->set('EVT_member_only', $member_only);
630
+	}
631
+
632
+
633
+	/**
634
+	 * @param $event_phone
635
+	 * @throws EE_Error
636
+	 * @throws ReflectionException
637
+	 */
638
+	public function set_event_phone($event_phone)
639
+	{
640
+		$this->set('EVT_phone', $event_phone);
641
+	}
642
+
643
+
644
+	/**
645
+	 * @param $modified
646
+	 * @throws EE_Error
647
+	 * @throws ReflectionException
648
+	 */
649
+	public function set_modified($modified)
650
+	{
651
+		$this->set('EVT_modified', $modified);
652
+	}
653
+
654
+
655
+	/**
656
+	 * @param $name
657
+	 * @throws EE_Error
658
+	 * @throws ReflectionException
659
+	 */
660
+	public function set_name($name)
661
+	{
662
+		$this->set('EVT_name', $name);
663
+	}
664
+
665
+
666
+	/**
667
+	 * @param $order
668
+	 * @throws EE_Error
669
+	 * @throws ReflectionException
670
+	 */
671
+	public function set_order($order)
672
+	{
673
+		$this->set('EVT_order', $order);
674
+	}
675
+
676
+
677
+	/**
678
+	 * @param $short_desc
679
+	 * @throws EE_Error
680
+	 * @throws ReflectionException
681
+	 */
682
+	public function set_short_description($short_desc)
683
+	{
684
+		$this->set('EVT_short_desc', $short_desc);
685
+	}
686
+
687
+
688
+	/**
689
+	 * @param $slug
690
+	 * @throws EE_Error
691
+	 * @throws ReflectionException
692
+	 */
693
+	public function set_slug($slug)
694
+	{
695
+		$this->set('EVT_slug', $slug);
696
+	}
697
+
698
+
699
+	/**
700
+	 * @param $timezone_string
701
+	 * @throws EE_Error
702
+	 * @throws ReflectionException
703
+	 */
704
+	public function set_timezone_string($timezone_string)
705
+	{
706
+		$this->set('EVT_timezone_string', $timezone_string);
707
+	}
708
+
709
+
710
+	/**
711
+	 * @param $visible_on
712
+	 * @throws EE_Error
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function set_visible_on($visible_on)
716
+	{
717
+		$this->set('EVT_visible_on', $visible_on);
718
+	}
719
+
720
+
721
+	/**
722
+	 * @param $wp_user
723
+	 * @throws EE_Error
724
+	 * @throws ReflectionException
725
+	 */
726
+	public function set_wp_user($wp_user)
727
+	{
728
+		$this->set('EVT_wp_user', $wp_user);
729
+	}
730
+
731
+
732
+	/**
733
+	 * @param $default_registration_status
734
+	 * @throws EE_Error
735
+	 * @throws ReflectionException
736
+	 */
737
+	public function set_default_registration_status($default_registration_status)
738
+	{
739
+		$this->set('EVT_default_registration_status', $default_registration_status);
740
+	}
741
+
742
+
743
+	/**
744
+	 * @param $donations
745
+	 * @throws EE_Error
746
+	 * @throws ReflectionException
747
+	 */
748
+	public function set_donations($donations)
749
+	{
750
+		$this->set('EVT_donations', $donations);
751
+	}
752
+
753
+
754
+	/**
755
+	 * Adds a venue to this event
756
+	 *
757
+	 * @param int|EE_Venue /int $venue_id_or_obj
758
+	 * @return EE_Base_Class|EE_Venue
759
+	 * @throws EE_Error
760
+	 * @throws ReflectionException
761
+	 */
762
+	public function add_venue($venue_id_or_obj): EE_Venue
763
+	{
764
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
765
+	}
766
+
767
+
768
+	/**
769
+	 * Removes a venue from the event
770
+	 *
771
+	 * @param EE_Venue /int $venue_id_or_obj
772
+	 * @return EE_Base_Class|EE_Venue
773
+	 * @throws EE_Error
774
+	 * @throws ReflectionException
775
+	 */
776
+	public function remove_venue($venue_id_or_obj): EE_Venue
777
+	{
778
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
779
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
780
+	}
781
+
782
+
783
+	/**
784
+	 * Gets the venue related to the event. May provide additional $query_params if desired
785
+	 *
786
+	 * @param array $query_params
787
+	 * @return int
788
+	 * @throws EE_Error
789
+	 * @throws ReflectionException
790
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
791
+	 */
792
+	public function venue_ID(array $query_params = []): int
793
+	{
794
+		$venue = $this->get_first_related('Venue', $query_params);
795
+		return $venue instanceof EE_Venue ? $venue->ID() : 0;
796
+	}
797
+
798
+
799
+	/**
800
+	 * Gets the venue related to the event. May provide additional $query_params if desired
801
+	 *
802
+	 * @param array $query_params
803
+	 * @return EE_Base_Class|EE_Venue
804
+	 * @throws EE_Error
805
+	 * @throws ReflectionException
806
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
807
+	 */
808
+	public function venue(array $query_params = []): EE_Venue
809
+	{
810
+		return $this->get_first_related('Venue', $query_params);
811
+	}
812
+
813
+
814
+	/**
815
+	 * @param array $query_params
816
+	 * @return EE_Base_Class[]|EE_Venue[]
817
+	 * @throws EE_Error
818
+	 * @throws ReflectionException
819
+	 * @deprecated $VID:$
820
+	 */
821
+	public function venues(array $query_params = []): array
822
+	{
823
+		return [$this->venue($query_params)];
824
+	}
825
+
826
+
827
+	/**
828
+	 * check if event id is present and if event is published
829
+	 *
830
+	 * @return boolean true yes, false no
831
+	 * @throws EE_Error
832
+	 * @throws ReflectionException
833
+	 */
834
+	private function _has_ID_and_is_published(): bool
835
+	{
836
+		// first check if event id is present and not NULL,
837
+		// then check if this event is published (or any of the equivalent "published" statuses)
838
+		return
839
+			$this->ID() && $this->ID() !== null
840
+			&& (
841
+				$this->status() === 'publish'
842
+				|| $this->status() === EEM_Event::sold_out
843
+				|| $this->status() === EEM_Event::postponed
844
+				|| $this->status() === EEM_Event::cancelled
845
+			);
846
+	}
847
+
848
+
849
+	/**
850
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
851
+	 *
852
+	 * @return boolean true yes, false no
853
+	 * @throws EE_Error
854
+	 * @throws ReflectionException
855
+	 */
856
+	public function is_upcoming(): bool
857
+	{
858
+		// check if event id is present and if this event is published
859
+		if ($this->is_inactive()) {
860
+			return false;
861
+		}
862
+		// set initial value
863
+		$upcoming = false;
864
+		// next let's get all datetimes and loop through them
865
+		$datetimes = $this->datetimes_in_chronological_order();
866
+		foreach ($datetimes as $datetime) {
867
+			if ($datetime instanceof EE_Datetime) {
868
+				// if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
869
+				if ($datetime->is_expired()) {
870
+					continue;
871
+				}
872
+				// if this dtt is active then we return false.
873
+				if ($datetime->is_active()) {
874
+					return false;
875
+				}
876
+				// otherwise let's check upcoming status
877
+				$upcoming = $datetime->is_upcoming();
878
+			}
879
+		}
880
+		return $upcoming;
881
+	}
882
+
883
+
884
+	/**
885
+	 * @return bool
886
+	 * @throws EE_Error
887
+	 * @throws ReflectionException
888
+	 */
889
+	public function is_active(): bool
890
+	{
891
+		// check if event id is present and if this event is published
892
+		if ($this->is_inactive()) {
893
+			return false;
894
+		}
895
+		// set initial value
896
+		$active = false;
897
+		// next let's get all datetimes and loop through them
898
+		$datetimes = $this->datetimes_in_chronological_order();
899
+		foreach ($datetimes as $datetime) {
900
+			if ($datetime instanceof EE_Datetime) {
901
+				// if this dtt is expired then we continue cause one of the other datetimes might be active.
902
+				if ($datetime->is_expired()) {
903
+					continue;
904
+				}
905
+				// if this dtt is upcoming then we return false.
906
+				if ($datetime->is_upcoming()) {
907
+					return false;
908
+				}
909
+				// otherwise let's check active status
910
+				$active = $datetime->is_active();
911
+			}
912
+		}
913
+		return $active;
914
+	}
915
+
916
+
917
+	/**
918
+	 * @return bool
919
+	 * @throws EE_Error
920
+	 * @throws ReflectionException
921
+	 */
922
+	public function is_expired(): bool
923
+	{
924
+		// check if event id is present and if this event is published
925
+		if ($this->is_inactive()) {
926
+			return false;
927
+		}
928
+		// set initial value
929
+		$expired = false;
930
+		// first let's get all datetimes and loop through them
931
+		$datetimes = $this->datetimes_in_chronological_order();
932
+		foreach ($datetimes as $datetime) {
933
+			if ($datetime instanceof EE_Datetime) {
934
+				// if this dtt is upcoming or active then we return false.
935
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
936
+					return false;
937
+				}
938
+				// otherwise let's check active status
939
+				$expired = $datetime->is_expired();
940
+			}
941
+		}
942
+		return $expired;
943
+	}
944
+
945
+
946
+	/**
947
+	 * @return bool
948
+	 * @throws EE_Error
949
+	 * @throws ReflectionException
950
+	 */
951
+	public function is_inactive(): bool
952
+	{
953
+		// check if event id is present and if this event is published
954
+		if ($this->_has_ID_and_is_published()) {
955
+			return false;
956
+		}
957
+		return true;
958
+	}
959
+
960
+
961
+	/**
962
+	 * calculate spaces remaining based on "saleable" tickets
963
+	 *
964
+	 * @param array|null $tickets
965
+	 * @param bool       $filtered
966
+	 * @return int|float
967
+	 * @throws EE_Error
968
+	 * @throws DomainException
969
+	 * @throws UnexpectedEntityException
970
+	 * @throws ReflectionException
971
+	 */
972
+	public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
973
+	{
974
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
975
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
976
+		return $filtered
977
+			? apply_filters(
978
+				'FHEE_EE_Event__spaces_remaining',
979
+				$spaces_remaining,
980
+				$this,
981
+				$tickets
982
+			)
983
+			: $spaces_remaining;
984
+	}
985
+
986
+
987
+	/**
988
+	 *    perform_sold_out_status_check
989
+	 *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
990
+	 *    available... if NOT, then the event status will get toggled to 'sold_out'
991
+	 *
992
+	 * @return bool    return the ACTUAL sold out state.
993
+	 * @throws EE_Error
994
+	 * @throws DomainException
995
+	 * @throws UnexpectedEntityException
996
+	 * @throws ReflectionException
997
+	 */
998
+	public function perform_sold_out_status_check(): bool
999
+	{
1000
+		// get all tickets
1001
+		$tickets     = $this->tickets(
1002
+			[
1003
+				'default_where_conditions' => 'none',
1004
+				'order_by'                 => ['TKT_qty' => 'ASC'],
1005
+			]
1006
+		);
1007
+		$all_expired = true;
1008
+		foreach ($tickets as $ticket) {
1009
+			if (! $ticket->is_expired()) {
1010
+				$all_expired = false;
1011
+				break;
1012
+			}
1013
+		}
1014
+		// if all the tickets are just expired, then don't update the event status to sold out
1015
+		if ($all_expired) {
1016
+			return true;
1017
+		}
1018
+		$spaces_remaining = $this->spaces_remaining($tickets);
1019
+		if ($spaces_remaining < 1) {
1020
+			if ($this->status() !== EEM_CPT_Base::post_status_private) {
1021
+				$this->set_status(EEM_Event::sold_out);
1022
+				$this->save();
1023
+			}
1024
+			$sold_out = true;
1025
+		} else {
1026
+			$sold_out = false;
1027
+			// was event previously marked as sold out ?
1028
+			if ($this->status() === EEM_Event::sold_out) {
1029
+				// revert status to previous value, if it was set
1030
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
1031
+				if ($previous_event_status) {
1032
+					$this->set_status($previous_event_status);
1033
+					$this->save();
1034
+				}
1035
+			}
1036
+		}
1037
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1038
+		return $sold_out;
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * This returns the total remaining spaces for sale on this event.
1044
+	 *
1045
+	 * @return int|float
1046
+	 * @throws EE_Error
1047
+	 * @throws DomainException
1048
+	 * @throws UnexpectedEntityException
1049
+	 * @throws ReflectionException
1050
+	 * @uses EE_Event::total_available_spaces()
1051
+	 */
1052
+	public function spaces_remaining_for_sale()
1053
+	{
1054
+		return $this->total_available_spaces(true);
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * This returns the total spaces available for an event
1060
+	 * while considering all the quantities on the tickets and the reg limits
1061
+	 * on the datetimes attached to this event.
1062
+	 *
1063
+	 * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1064
+	 *                              If this is false, then we return the most tickets that could ever be sold
1065
+	 *                              for this event with the datetime and tickets setup on the event under optimal
1066
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
1067
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
1068
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
1069
+	 *                              sold out, the more accurate the "live" total is.
1070
+	 * @return int|float
1071
+	 * @throws EE_Error
1072
+	 * @throws DomainException
1073
+	 * @throws UnexpectedEntityException
1074
+	 * @throws ReflectionException
1075
+	 */
1076
+	public function total_available_spaces(bool $consider_sold = false)
1077
+	{
1078
+		$spaces_available = $consider_sold
1079
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
1080
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1081
+		return apply_filters(
1082
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
1083
+			$spaces_available,
1084
+			$this,
1085
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
1086
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
1087
+		);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Checks if the event is set to sold out
1093
+	 *
1094
+	 * @param bool $actual  whether or not to perform calculations to not only figure the
1095
+	 *                      actual status but also to flip the status if necessary to sold
1096
+	 *                      out If false, we just check the existing status of the event
1097
+	 * @return boolean
1098
+	 * @throws EE_Error
1099
+	 * @throws ReflectionException
1100
+	 */
1101
+	public function is_sold_out(bool $actual = false): bool
1102
+	{
1103
+		if (! $actual) {
1104
+			return $this->status() === EEM_Event::sold_out;
1105
+		}
1106
+		return $this->perform_sold_out_status_check();
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * Checks if the event is marked as postponed
1112
+	 *
1113
+	 * @return boolean
1114
+	 */
1115
+	public function is_postponed(): bool
1116
+	{
1117
+		return $this->status() === EEM_Event::postponed;
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * Checks if the event is marked as cancelled
1123
+	 *
1124
+	 * @return boolean
1125
+	 */
1126
+	public function is_cancelled(): bool
1127
+	{
1128
+		return $this->status() === EEM_Event::cancelled;
1129
+	}
1130
+
1131
+
1132
+	/**
1133
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1134
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1135
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1136
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1137
+	 * the event is considered expired.
1138
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1139
+	 * status set on the EVENT when it is not published and thus is done
1140
+	 *
1141
+	 * @param bool $reset
1142
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1143
+	 * @throws EE_Error
1144
+	 * @throws ReflectionException
1145
+	 */
1146
+	public function get_active_status(bool $reset = false)
1147
+	{
1148
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1149
+		if (! empty($this->_active_status) && ! $reset) {
1150
+			return $this->_active_status;
1151
+		}
1152
+		// first check if event id is present on this object
1153
+		if (! $this->ID()) {
1154
+			return false;
1155
+		}
1156
+		$where_params_for_event = [['EVT_ID' => $this->ID()]];
1157
+		// if event is published:
1158
+		if (
1159
+			$this->status() === EEM_CPT_Base::post_status_publish
1160
+			|| $this->status() === EEM_CPT_Base::post_status_private
1161
+		) {
1162
+			// active?
1163
+			if (
1164
+				EEM_Datetime::instance()->get_datetime_count_for_status(
1165
+					EE_Datetime::active,
1166
+					$where_params_for_event
1167
+				) > 0
1168
+			) {
1169
+				$this->_active_status = EE_Datetime::active;
1170
+			} else {
1171
+				// upcoming?
1172
+				if (
1173
+					EEM_Datetime::instance()->get_datetime_count_for_status(
1174
+						EE_Datetime::upcoming,
1175
+						$where_params_for_event
1176
+					) > 0
1177
+				) {
1178
+					$this->_active_status = EE_Datetime::upcoming;
1179
+				} else {
1180
+					// expired?
1181
+					if (
1182
+						EEM_Datetime::instance()->get_datetime_count_for_status(
1183
+							EE_Datetime::expired,
1184
+							$where_params_for_event
1185
+						) > 0
1186
+					) {
1187
+						$this->_active_status = EE_Datetime::expired;
1188
+					} else {
1189
+						// it would be odd if things make it this far
1190
+						// because it basically means there are no datetimes attached to the event.
1191
+						// So in this case it will just be considered inactive.
1192
+						$this->_active_status = EE_Datetime::inactive;
1193
+					}
1194
+				}
1195
+			}
1196
+		} else {
1197
+			// the event is not published, so let's just set it's active status according to its' post status
1198
+			switch ($this->status()) {
1199
+				case EEM_Event::sold_out:
1200
+					$this->_active_status = EE_Datetime::sold_out;
1201
+					break;
1202
+				case EEM_Event::cancelled:
1203
+					$this->_active_status = EE_Datetime::cancelled;
1204
+					break;
1205
+				case EEM_Event::postponed:
1206
+					$this->_active_status = EE_Datetime::postponed;
1207
+					break;
1208
+				default:
1209
+					$this->_active_status = EE_Datetime::inactive;
1210
+			}
1211
+		}
1212
+		return $this->_active_status;
1213
+	}
1214
+
1215
+
1216
+	/**
1217
+	 *    pretty_active_status
1218
+	 *
1219
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1220
+	 * @return string
1221
+	 * @throws EE_Error
1222
+	 * @throws ReflectionException
1223
+	 */
1224
+	public function pretty_active_status(bool $echo = true): string
1225
+	{
1226
+		$active_status = $this->get_active_status();
1227
+		$status        = "
1228 1228
         <span class='ee-status ee-status-bg--$active_status event-active-status-$active_status'>
1229 1229
             " . EEH_Template::pretty_status($active_status, false, 'sentence') . "
1230 1230
         </span >";
1231
-        if ($echo) {
1232
-            echo wp_kses($status, AllowedTags::getAllowedTags());
1233
-            return '';
1234
-        }
1235
-        return $status;
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     * @return bool|int
1241
-     * @throws EE_Error
1242
-     * @throws ReflectionException
1243
-     */
1244
-    public function get_number_of_tickets_sold()
1245
-    {
1246
-        $tkt_sold = 0;
1247
-        if (! $this->ID()) {
1248
-            return 0;
1249
-        }
1250
-        $datetimes = $this->datetimes();
1251
-        foreach ($datetimes as $datetime) {
1252
-            if ($datetime instanceof EE_Datetime) {
1253
-                $tkt_sold += $datetime->sold();
1254
-            }
1255
-        }
1256
-        return $tkt_sold;
1257
-    }
1258
-
1259
-
1260
-    /**
1261
-     * This just returns a count of all the registrations for this event
1262
-     *
1263
-     * @return int
1264
-     * @throws EE_Error
1265
-     * @throws ReflectionException
1266
-     */
1267
-    public function get_count_of_all_registrations(): int
1268
-    {
1269
-        return EEM_Event::instance()->count_related($this, 'Registration');
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * This returns the ticket with the earliest start time that is
1275
-     * available for this event (across all datetimes attached to the event)
1276
-     *
1277
-     * @return EE_Base_Class|EE_Ticket|null
1278
-     * @throws EE_Error
1279
-     * @throws ReflectionException
1280
-     */
1281
-    public function get_ticket_with_earliest_start_time()
1282
-    {
1283
-        $where['Datetime.EVT_ID'] = $this->ID();
1284
-        $query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1285
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * This returns the ticket with the latest end time that is available
1291
-     * for this event (across all datetimes attached to the event)
1292
-     *
1293
-     * @return EE_Base_Class|EE_Ticket|null
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function get_ticket_with_latest_end_time()
1298
-    {
1299
-        $where['Datetime.EVT_ID'] = $this->ID();
1300
-        $query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1301
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1302
-    }
1303
-
1304
-
1305
-    /**
1306
-     * This returns the number of different ticket types currently on sale for this event.
1307
-     *
1308
-     * @return int
1309
-     * @throws EE_Error
1310
-     * @throws ReflectionException
1311
-     */
1312
-    public function countTicketsOnSale(): int
1313
-    {
1314
-        $where = [
1315
-            'Datetime.EVT_ID' => $this->ID(),
1316
-            'TKT_start_date'  => ['<', time()],
1317
-            'TKT_end_date'    => ['>', time()],
1318
-        ];
1319
-        return EEM_Ticket::instance()->count([$where]);
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * This returns whether there are any tickets on sale for this event.
1325
-     *
1326
-     * @return bool true = YES tickets on sale.
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     */
1330
-    public function tickets_on_sale(): bool
1331
-    {
1332
-        return $this->countTicketsOnSale() > 0;
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1338
-     * to check for an external URL first
1339
-     *
1340
-     * @return string
1341
-     * @throws EE_Error
1342
-     * @throws ReflectionException
1343
-     */
1344
-    public function get_permalink(): string
1345
-    {
1346
-        if ($this->external_url()) {
1347
-            return $this->external_url();
1348
-        }
1349
-        return parent::get_permalink();
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * Gets the first term for 'espresso_event_categories' we can find
1355
-     *
1356
-     * @param array $query_params
1357
-     * @return EE_Base_Class|EE_Term|null
1358
-     * @throws EE_Error
1359
-     * @throws ReflectionException
1360
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1361
-     */
1362
-    public function first_event_category(array $query_params = []): ?EE_Term
1363
-    {
1364
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1365
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1366
-        return EEM_Term::instance()->get_one($query_params);
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * Gets all terms for 'espresso_event_categories' we can find
1372
-     *
1373
-     * @param array $query_params
1374
-     * @return EE_Base_Class[]|EE_Term[]
1375
-     * @throws EE_Error
1376
-     * @throws ReflectionException
1377
-     */
1378
-    public function get_all_event_categories(array $query_params = []): array
1379
-    {
1380
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1381
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1382
-        return EEM_Term::instance()->get_all($query_params);
1383
-    }
1384
-
1385
-
1386
-    /**
1387
-     * Adds a question group to this event
1388
-     *
1389
-     * @param EE_Question_Group|int $question_group_id_or_obj
1390
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1391
-     *                                           registrant, if false will be added for others. default: false
1392
-     * @return EE_Base_Class|EE_Question_Group
1393
-     * @throws EE_Error
1394
-     * @throws InvalidArgumentException
1395
-     * @throws InvalidDataTypeException
1396
-     * @throws InvalidInterfaceException
1397
-     * @throws ReflectionException
1398
-     */
1399
-    public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1400
-    {
1401
-        // If the row already exists, it will be updated. If it doesn't, it will be inserted.
1402
-        // That's in EE_HABTM_Relation::add_relation_to().
1403
-        return $this->_add_relation_to(
1404
-            $question_group_id_or_obj,
1405
-            'Question_Group',
1406
-            [
1407
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1408
-            ]
1409
-        );
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * Removes a question group from the event
1415
-     *
1416
-     * @param EE_Question_Group|int $question_group_id_or_obj
1417
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1418
-     *                                           registrant, if false will be removed from others. default: false
1419
-     * @return EE_Base_Class|EE_Question_Group|int
1420
-     * @throws EE_Error
1421
-     * @throws InvalidArgumentException
1422
-     * @throws ReflectionException
1423
-     * @throws InvalidDataTypeException
1424
-     * @throws InvalidInterfaceException
1425
-     */
1426
-    public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1427
-    {
1428
-        // If the question group is used for the other type (primary or additional)
1429
-        // then just update it. If not, delete it outright.
1430
-        $existing_relation = $this->get_first_related(
1431
-            'Event_Question_Group',
1432
-            [
1433
-                [
1434
-                    'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1435
-                ],
1436
-            ]
1437
-        );
1438
-        $field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1439
-        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1440
-        if ($existing_relation->get($other_field) === false) {
1441
-            // Delete it. It's now no longer for primary or additional question groups.
1442
-            return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1443
-        }
1444
-        // Just update it. They'll still use this question group for the other category
1445
-        $existing_relation->save(
1446
-            [
1447
-                $field_to_update => false,
1448
-            ]
1449
-        );
1450
-        return $question_group_id_or_obj;
1451
-    }
1452
-
1453
-
1454
-    /**
1455
-     * Gets all the question groups, ordering them by QSG_order ascending
1456
-     *
1457
-     * @param array $query_params
1458
-     * @return EE_Base_Class[]|EE_Question_Group[]
1459
-     * @throws EE_Error
1460
-     * @throws ReflectionException
1461
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1462
-     */
1463
-    public function question_groups(array $query_params = []): array
1464
-    {
1465
-        $query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1466
-        return $this->get_many_related('Question_Group', $query_params);
1467
-    }
1468
-
1469
-
1470
-    /**
1471
-     * Implementation for EEI_Has_Icon interface method.
1472
-     *
1473
-     * @return string
1474
-     * @see EEI_Visual_Representation for comments
1475
-     */
1476
-    public function get_icon(): string
1477
-    {
1478
-        return '<span class="dashicons dashicons-flag"></span>';
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * Implementation for EEI_Admin_Links interface method.
1484
-     *
1485
-     * @return string
1486
-     * @throws EE_Error
1487
-     * @throws ReflectionException
1488
-     * @see EEI_Admin_Links for comments
1489
-     */
1490
-    public function get_admin_details_link(): string
1491
-    {
1492
-        return $this->get_admin_edit_link();
1493
-    }
1494
-
1495
-
1496
-    /**
1497
-     * Implementation for EEI_Admin_Links interface method.
1498
-     *
1499
-     * @return string
1500
-     * @throws EE_Error
1501
-     * @throws ReflectionException
1502
-     * @see EEI_Admin_Links for comments
1503
-     */
1504
-    public function get_admin_edit_link(): string
1505
-    {
1506
-        return EEH_URL::add_query_args_and_nonce(
1507
-            [
1508
-                'page'   => 'espresso_events',
1509
-                'action' => 'edit',
1510
-                'post'   => $this->ID(),
1511
-            ],
1512
-            admin_url('admin.php')
1513
-        );
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * Implementation for EEI_Admin_Links interface method.
1519
-     *
1520
-     * @return string
1521
-     * @see EEI_Admin_Links for comments
1522
-     */
1523
-    public function get_admin_settings_link(): string
1524
-    {
1525
-        return EEH_URL::add_query_args_and_nonce(
1526
-            [
1527
-                'page'   => 'espresso_events',
1528
-                'action' => 'default_event_settings',
1529
-            ],
1530
-            admin_url('admin.php')
1531
-        );
1532
-    }
1533
-
1534
-
1535
-    /**
1536
-     * Implementation for EEI_Admin_Links interface method.
1537
-     *
1538
-     * @return string
1539
-     * @see EEI_Admin_Links for comments
1540
-     */
1541
-    public function get_admin_overview_link(): string
1542
-    {
1543
-        return EEH_URL::add_query_args_and_nonce(
1544
-            [
1545
-                'page'   => 'espresso_events',
1546
-                'action' => 'default',
1547
-            ],
1548
-            admin_url('admin.php')
1549
-        );
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * @return string|null
1555
-     * @throws EE_Error
1556
-     * @throws ReflectionException
1557
-     */
1558
-    public function registrationFormUuid(): ?string
1559
-    {
1560
-        return $this->get('FSC_UUID');
1561
-    }
1562
-
1563
-
1564
-    /**
1565
-     * Gets all the form sections for this event
1566
-     *
1567
-     * @return EE_Base_Class[]|EE_Form_Section[]
1568
-     * @throws EE_Error
1569
-     * @throws ReflectionException
1570
-     */
1571
-    public function registrationForm(): array
1572
-    {
1573
-        $FSC_UUID = $this->registrationFormUuid();
1574
-
1575
-        if (empty($FSC_UUID)) {
1576
-            return [];
1577
-        }
1578
-
1579
-        return EEM_Form_Section::instance()->get_all(
1580
-            [
1581
-                [
1582
-                    'OR' => [
1583
-                        'FSC_UUID'      => $FSC_UUID, // top level form
1584
-                        'FSC_belongsTo' => $FSC_UUID, // child form sections
1585
-                    ],
1586
-                ],
1587
-                'order_by' => ['FSC_order' => 'ASC'],
1588
-            ]
1589
-        );
1590
-    }
1591
-
1592
-
1593
-    /**
1594
-     * @param string $UUID
1595
-     * @throws EE_Error
1596
-     * @throws ReflectionException
1597
-     */
1598
-    public function setRegistrationFormUuid(string $UUID): void
1599
-    {
1600
-        if (! Cuid::isCuid($UUID)) {
1601
-            throw new InvalidArgumentException(
1602
-                sprintf(
1603
-                /* translators: 1: UUID value, 2: UUID generator function. */
1604
-                    esc_html__(
1605
-                        'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1606
-                        'event_espresso'
1607
-                    ),
1608
-                    $UUID,
1609
-                    '`Cuid::cuid()`'
1610
-                )
1611
-            );
1612
-        }
1613
-        $this->set('FSC_UUID', $UUID);
1614
-    }
1231
+		if ($echo) {
1232
+			echo wp_kses($status, AllowedTags::getAllowedTags());
1233
+			return '';
1234
+		}
1235
+		return $status;
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 * @return bool|int
1241
+	 * @throws EE_Error
1242
+	 * @throws ReflectionException
1243
+	 */
1244
+	public function get_number_of_tickets_sold()
1245
+	{
1246
+		$tkt_sold = 0;
1247
+		if (! $this->ID()) {
1248
+			return 0;
1249
+		}
1250
+		$datetimes = $this->datetimes();
1251
+		foreach ($datetimes as $datetime) {
1252
+			if ($datetime instanceof EE_Datetime) {
1253
+				$tkt_sold += $datetime->sold();
1254
+			}
1255
+		}
1256
+		return $tkt_sold;
1257
+	}
1258
+
1259
+
1260
+	/**
1261
+	 * This just returns a count of all the registrations for this event
1262
+	 *
1263
+	 * @return int
1264
+	 * @throws EE_Error
1265
+	 * @throws ReflectionException
1266
+	 */
1267
+	public function get_count_of_all_registrations(): int
1268
+	{
1269
+		return EEM_Event::instance()->count_related($this, 'Registration');
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * This returns the ticket with the earliest start time that is
1275
+	 * available for this event (across all datetimes attached to the event)
1276
+	 *
1277
+	 * @return EE_Base_Class|EE_Ticket|null
1278
+	 * @throws EE_Error
1279
+	 * @throws ReflectionException
1280
+	 */
1281
+	public function get_ticket_with_earliest_start_time()
1282
+	{
1283
+		$where['Datetime.EVT_ID'] = $this->ID();
1284
+		$query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1285
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * This returns the ticket with the latest end time that is available
1291
+	 * for this event (across all datetimes attached to the event)
1292
+	 *
1293
+	 * @return EE_Base_Class|EE_Ticket|null
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function get_ticket_with_latest_end_time()
1298
+	{
1299
+		$where['Datetime.EVT_ID'] = $this->ID();
1300
+		$query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1301
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1302
+	}
1303
+
1304
+
1305
+	/**
1306
+	 * This returns the number of different ticket types currently on sale for this event.
1307
+	 *
1308
+	 * @return int
1309
+	 * @throws EE_Error
1310
+	 * @throws ReflectionException
1311
+	 */
1312
+	public function countTicketsOnSale(): int
1313
+	{
1314
+		$where = [
1315
+			'Datetime.EVT_ID' => $this->ID(),
1316
+			'TKT_start_date'  => ['<', time()],
1317
+			'TKT_end_date'    => ['>', time()],
1318
+		];
1319
+		return EEM_Ticket::instance()->count([$where]);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * This returns whether there are any tickets on sale for this event.
1325
+	 *
1326
+	 * @return bool true = YES tickets on sale.
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 */
1330
+	public function tickets_on_sale(): bool
1331
+	{
1332
+		return $this->countTicketsOnSale() > 0;
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1338
+	 * to check for an external URL first
1339
+	 *
1340
+	 * @return string
1341
+	 * @throws EE_Error
1342
+	 * @throws ReflectionException
1343
+	 */
1344
+	public function get_permalink(): string
1345
+	{
1346
+		if ($this->external_url()) {
1347
+			return $this->external_url();
1348
+		}
1349
+		return parent::get_permalink();
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * Gets the first term for 'espresso_event_categories' we can find
1355
+	 *
1356
+	 * @param array $query_params
1357
+	 * @return EE_Base_Class|EE_Term|null
1358
+	 * @throws EE_Error
1359
+	 * @throws ReflectionException
1360
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1361
+	 */
1362
+	public function first_event_category(array $query_params = []): ?EE_Term
1363
+	{
1364
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1365
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1366
+		return EEM_Term::instance()->get_one($query_params);
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * Gets all terms for 'espresso_event_categories' we can find
1372
+	 *
1373
+	 * @param array $query_params
1374
+	 * @return EE_Base_Class[]|EE_Term[]
1375
+	 * @throws EE_Error
1376
+	 * @throws ReflectionException
1377
+	 */
1378
+	public function get_all_event_categories(array $query_params = []): array
1379
+	{
1380
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1381
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1382
+		return EEM_Term::instance()->get_all($query_params);
1383
+	}
1384
+
1385
+
1386
+	/**
1387
+	 * Adds a question group to this event
1388
+	 *
1389
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1390
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1391
+	 *                                           registrant, if false will be added for others. default: false
1392
+	 * @return EE_Base_Class|EE_Question_Group
1393
+	 * @throws EE_Error
1394
+	 * @throws InvalidArgumentException
1395
+	 * @throws InvalidDataTypeException
1396
+	 * @throws InvalidInterfaceException
1397
+	 * @throws ReflectionException
1398
+	 */
1399
+	public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1400
+	{
1401
+		// If the row already exists, it will be updated. If it doesn't, it will be inserted.
1402
+		// That's in EE_HABTM_Relation::add_relation_to().
1403
+		return $this->_add_relation_to(
1404
+			$question_group_id_or_obj,
1405
+			'Question_Group',
1406
+			[
1407
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1408
+			]
1409
+		);
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * Removes a question group from the event
1415
+	 *
1416
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1417
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1418
+	 *                                           registrant, if false will be removed from others. default: false
1419
+	 * @return EE_Base_Class|EE_Question_Group|int
1420
+	 * @throws EE_Error
1421
+	 * @throws InvalidArgumentException
1422
+	 * @throws ReflectionException
1423
+	 * @throws InvalidDataTypeException
1424
+	 * @throws InvalidInterfaceException
1425
+	 */
1426
+	public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1427
+	{
1428
+		// If the question group is used for the other type (primary or additional)
1429
+		// then just update it. If not, delete it outright.
1430
+		$existing_relation = $this->get_first_related(
1431
+			'Event_Question_Group',
1432
+			[
1433
+				[
1434
+					'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1435
+				],
1436
+			]
1437
+		);
1438
+		$field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1439
+		$other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1440
+		if ($existing_relation->get($other_field) === false) {
1441
+			// Delete it. It's now no longer for primary or additional question groups.
1442
+			return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1443
+		}
1444
+		// Just update it. They'll still use this question group for the other category
1445
+		$existing_relation->save(
1446
+			[
1447
+				$field_to_update => false,
1448
+			]
1449
+		);
1450
+		return $question_group_id_or_obj;
1451
+	}
1452
+
1453
+
1454
+	/**
1455
+	 * Gets all the question groups, ordering them by QSG_order ascending
1456
+	 *
1457
+	 * @param array $query_params
1458
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1459
+	 * @throws EE_Error
1460
+	 * @throws ReflectionException
1461
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1462
+	 */
1463
+	public function question_groups(array $query_params = []): array
1464
+	{
1465
+		$query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1466
+		return $this->get_many_related('Question_Group', $query_params);
1467
+	}
1468
+
1469
+
1470
+	/**
1471
+	 * Implementation for EEI_Has_Icon interface method.
1472
+	 *
1473
+	 * @return string
1474
+	 * @see EEI_Visual_Representation for comments
1475
+	 */
1476
+	public function get_icon(): string
1477
+	{
1478
+		return '<span class="dashicons dashicons-flag"></span>';
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * Implementation for EEI_Admin_Links interface method.
1484
+	 *
1485
+	 * @return string
1486
+	 * @throws EE_Error
1487
+	 * @throws ReflectionException
1488
+	 * @see EEI_Admin_Links for comments
1489
+	 */
1490
+	public function get_admin_details_link(): string
1491
+	{
1492
+		return $this->get_admin_edit_link();
1493
+	}
1494
+
1495
+
1496
+	/**
1497
+	 * Implementation for EEI_Admin_Links interface method.
1498
+	 *
1499
+	 * @return string
1500
+	 * @throws EE_Error
1501
+	 * @throws ReflectionException
1502
+	 * @see EEI_Admin_Links for comments
1503
+	 */
1504
+	public function get_admin_edit_link(): string
1505
+	{
1506
+		return EEH_URL::add_query_args_and_nonce(
1507
+			[
1508
+				'page'   => 'espresso_events',
1509
+				'action' => 'edit',
1510
+				'post'   => $this->ID(),
1511
+			],
1512
+			admin_url('admin.php')
1513
+		);
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * Implementation for EEI_Admin_Links interface method.
1519
+	 *
1520
+	 * @return string
1521
+	 * @see EEI_Admin_Links for comments
1522
+	 */
1523
+	public function get_admin_settings_link(): string
1524
+	{
1525
+		return EEH_URL::add_query_args_and_nonce(
1526
+			[
1527
+				'page'   => 'espresso_events',
1528
+				'action' => 'default_event_settings',
1529
+			],
1530
+			admin_url('admin.php')
1531
+		);
1532
+	}
1533
+
1534
+
1535
+	/**
1536
+	 * Implementation for EEI_Admin_Links interface method.
1537
+	 *
1538
+	 * @return string
1539
+	 * @see EEI_Admin_Links for comments
1540
+	 */
1541
+	public function get_admin_overview_link(): string
1542
+	{
1543
+		return EEH_URL::add_query_args_and_nonce(
1544
+			[
1545
+				'page'   => 'espresso_events',
1546
+				'action' => 'default',
1547
+			],
1548
+			admin_url('admin.php')
1549
+		);
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * @return string|null
1555
+	 * @throws EE_Error
1556
+	 * @throws ReflectionException
1557
+	 */
1558
+	public function registrationFormUuid(): ?string
1559
+	{
1560
+		return $this->get('FSC_UUID');
1561
+	}
1562
+
1563
+
1564
+	/**
1565
+	 * Gets all the form sections for this event
1566
+	 *
1567
+	 * @return EE_Base_Class[]|EE_Form_Section[]
1568
+	 * @throws EE_Error
1569
+	 * @throws ReflectionException
1570
+	 */
1571
+	public function registrationForm(): array
1572
+	{
1573
+		$FSC_UUID = $this->registrationFormUuid();
1574
+
1575
+		if (empty($FSC_UUID)) {
1576
+			return [];
1577
+		}
1578
+
1579
+		return EEM_Form_Section::instance()->get_all(
1580
+			[
1581
+				[
1582
+					'OR' => [
1583
+						'FSC_UUID'      => $FSC_UUID, // top level form
1584
+						'FSC_belongsTo' => $FSC_UUID, // child form sections
1585
+					],
1586
+				],
1587
+				'order_by' => ['FSC_order' => 'ASC'],
1588
+			]
1589
+		);
1590
+	}
1591
+
1592
+
1593
+	/**
1594
+	 * @param string $UUID
1595
+	 * @throws EE_Error
1596
+	 * @throws ReflectionException
1597
+	 */
1598
+	public function setRegistrationFormUuid(string $UUID): void
1599
+	{
1600
+		if (! Cuid::isCuid($UUID)) {
1601
+			throw new InvalidArgumentException(
1602
+				sprintf(
1603
+				/* translators: 1: UUID value, 2: UUID generator function. */
1604
+					esc_html__(
1605
+						'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1606
+						'event_espresso'
1607
+					),
1608
+					$UUID,
1609
+					'`Cuid::cuid()`'
1610
+				)
1611
+			);
1612
+		}
1613
+		$this->set('FSC_UUID', $UUID);
1614
+	}
1615 1615
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function getAvailableSpacesCalculator(): EventSpacesCalculator
77 77
     {
78
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
78
+        if ( ! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79 79
             $this->available_spaces_calculator = new EventSpacesCalculator($this);
80 80
         }
81 81
         return $this->available_spaces_calculator;
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
         bool $try_to_exclude_expired = true,
257 257
         bool $try_to_exclude_deleted = true
258 258
     ): ?EE_Datetime {
259
-        if (! empty($this->_Primary_Datetime)) {
259
+        if ( ! empty($this->_Primary_Datetime)) {
260 260
             return $this->_Primary_Datetime;
261 261
         }
262 262
         $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
     {
282 282
         // first get all datetimes
283 283
         $datetimes = $this->datetimes_ordered();
284
-        if (! $datetimes) {
284
+        if ( ! $datetimes) {
285 285
             return [];
286 286
         }
287 287
         $datetime_ids = [];
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
     public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491 491
     {
492 492
         $short_desc = $this->get('EVT_short_desc');
493
-        if (! empty($short_desc) || $not_full_desc) {
493
+        if ( ! empty($short_desc) || $not_full_desc) {
494 494
             return $short_desc;
495 495
         }
496 496
         $full_desc = $this->get('EVT_desc');
@@ -998,7 +998,7 @@  discard block
 block discarded – undo
998 998
     public function perform_sold_out_status_check(): bool
999 999
     {
1000 1000
         // get all tickets
1001
-        $tickets     = $this->tickets(
1001
+        $tickets = $this->tickets(
1002 1002
             [
1003 1003
                 'default_where_conditions' => 'none',
1004 1004
                 'order_by'                 => ['TKT_qty' => 'ASC'],
@@ -1006,7 +1006,7 @@  discard block
 block discarded – undo
1006 1006
         );
1007 1007
         $all_expired = true;
1008 1008
         foreach ($tickets as $ticket) {
1009
-            if (! $ticket->is_expired()) {
1009
+            if ( ! $ticket->is_expired()) {
1010 1010
                 $all_expired = false;
1011 1011
                 break;
1012 1012
             }
@@ -1100,7 +1100,7 @@  discard block
 block discarded – undo
1100 1100
      */
1101 1101
     public function is_sold_out(bool $actual = false): bool
1102 1102
     {
1103
-        if (! $actual) {
1103
+        if ( ! $actual) {
1104 1104
             return $this->status() === EEM_Event::sold_out;
1105 1105
         }
1106 1106
         return $this->perform_sold_out_status_check();
@@ -1146,11 +1146,11 @@  discard block
 block discarded – undo
1146 1146
     public function get_active_status(bool $reset = false)
1147 1147
     {
1148 1148
         // if the active status has already been set, then just use that value (unless we are resetting it)
1149
-        if (! empty($this->_active_status) && ! $reset) {
1149
+        if ( ! empty($this->_active_status) && ! $reset) {
1150 1150
             return $this->_active_status;
1151 1151
         }
1152 1152
         // first check if event id is present on this object
1153
-        if (! $this->ID()) {
1153
+        if ( ! $this->ID()) {
1154 1154
             return false;
1155 1155
         }
1156 1156
         $where_params_for_event = [['EVT_ID' => $this->ID()]];
@@ -1226,7 +1226,7 @@  discard block
 block discarded – undo
1226 1226
         $active_status = $this->get_active_status();
1227 1227
         $status        = "
1228 1228
         <span class='ee-status ee-status-bg--$active_status event-active-status-$active_status'>
1229
-            " . EEH_Template::pretty_status($active_status, false, 'sentence') . "
1229
+            ".EEH_Template::pretty_status($active_status, false, 'sentence')."
1230 1230
         </span >";
1231 1231
         if ($echo) {
1232 1232
             echo wp_kses($status, AllowedTags::getAllowedTags());
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
     public function get_number_of_tickets_sold()
1245 1245
     {
1246 1246
         $tkt_sold = 0;
1247
-        if (! $this->ID()) {
1247
+        if ( ! $this->ID()) {
1248 1248
             return 0;
1249 1249
         }
1250 1250
         $datetimes = $this->datetimes();
@@ -1436,7 +1436,7 @@  discard block
 block discarded – undo
1436 1436
             ]
1437 1437
         );
1438 1438
         $field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1439
-        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1439
+        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext( ! $for_primary);
1440 1440
         if ($existing_relation->get($other_field) === false) {
1441 1441
             // Delete it. It's now no longer for primary or additional question groups.
1442 1442
             return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
@@ -1597,7 +1597,7 @@  discard block
 block discarded – undo
1597 1597
      */
1598 1598
     public function setRegistrationFormUuid(string $UUID): void
1599 1599
     {
1600
-        if (! Cuid::isCuid($UUID)) {
1600
+        if ( ! Cuid::isCuid($UUID)) {
1601 1601
             throw new InvalidArgumentException(
1602 1602
                 sprintf(
1603 1603
                 /* translators: 1: UUID value, 2: UUID generator function. */
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 1 patch
Indentation   +1552 added lines, -1552 removed lines patch added patch discarded remove patch
@@ -12,1560 +12,1560 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15
-    /**
16
-     * constant used by get_active_status, indicates datetime has no more available spaces
17
-     */
18
-    const sold_out = 'DTS';
19
-
20
-    /**
21
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
-     */
23
-    const active = 'DTA';
24
-
25
-    /**
26
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
-     * expired
28
-     */
29
-    const upcoming = 'DTU';
30
-
31
-    /**
32
-     * Datetime is postponed
33
-     */
34
-    const postponed = 'DTP';
35
-
36
-    /**
37
-     * Datetime is cancelled
38
-     */
39
-    const cancelled = 'DTC';
40
-
41
-    /**
42
-     * constant used by get_active_status, indicates datetime has expired (event is over)
43
-     */
44
-    const expired = 'DTE';
45
-
46
-    /**
47
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
-     */
49
-    const inactive = 'DTI';
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values    incoming values
54
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
-     *                                  and the second value is the time format
57
-     * @return EE_Datetime
58
-     * @throws ReflectionException
59
-     * @throws InvalidArgumentException
60
-     * @throws InvalidInterfaceException
61
-     * @throws InvalidDataTypeException
62
-     * @throws EE_Error
63
-     */
64
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
-    {
66
-        $has_object = parent::_check_for_object(
67
-            $props_n_values,
68
-            __CLASS__,
69
-            $timezone,
70
-            $date_formats
71
-        );
72
-        return $has_object
73
-            ? $has_object
74
-            : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Datetime
83
-     * @throws ReflectionException
84
-     * @throws InvalidArgumentException
85
-     * @throws InvalidInterfaceException
86
-     * @throws InvalidDataTypeException
87
-     * @throws EE_Error
88
-     */
89
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
-    {
91
-        return new self($props_n_values, true, $timezone);
92
-    }
93
-
94
-
95
-    /**
96
-     * @param $name
97
-     * @throws ReflectionException
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidInterfaceException
100
-     * @throws InvalidDataTypeException
101
-     * @throws EE_Error
102
-     */
103
-    public function set_name($name)
104
-    {
105
-        $this->set('DTT_name', $name);
106
-    }
107
-
108
-
109
-    /**
110
-     * @param $description
111
-     * @throws ReflectionException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidInterfaceException
114
-     * @throws InvalidDataTypeException
115
-     * @throws EE_Error
116
-     */
117
-    public function set_description($description)
118
-    {
119
-        $this->set('DTT_description', $description);
120
-    }
121
-
122
-
123
-    /**
124
-     * Set event start date
125
-     * set the start date for an event
126
-     *
127
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
-     * @throws ReflectionException
129
-     * @throws InvalidArgumentException
130
-     * @throws InvalidInterfaceException
131
-     * @throws InvalidDataTypeException
132
-     * @throws EE_Error
133
-     */
134
-    public function set_start_date($date)
135
-    {
136
-        $this->_set_date_for($date, 'DTT_EVT_start');
137
-    }
138
-
139
-
140
-    /**
141
-     * Set event start time
142
-     * set the start time for an event
143
-     *
144
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
-     * @throws ReflectionException
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidInterfaceException
148
-     * @throws InvalidDataTypeException
149
-     * @throws EE_Error
150
-     */
151
-    public function set_start_time($time)
152
-    {
153
-        $this->_set_time_for($time, 'DTT_EVT_start');
154
-    }
155
-
156
-
157
-    /**
158
-     * Set event end date
159
-     * set the end date for an event
160
-     *
161
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
-     * @throws ReflectionException
163
-     * @throws InvalidArgumentException
164
-     * @throws InvalidInterfaceException
165
-     * @throws InvalidDataTypeException
166
-     * @throws EE_Error
167
-     */
168
-    public function set_end_date($date)
169
-    {
170
-        $this->_set_date_for($date, 'DTT_EVT_end');
171
-    }
172
-
173
-
174
-    /**
175
-     * Set event end time
176
-     * set the end time for an event
177
-     *
178
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
-     * @throws ReflectionException
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidInterfaceException
182
-     * @throws InvalidDataTypeException
183
-     * @throws EE_Error
184
-     */
185
-    public function set_end_time($time)
186
-    {
187
-        $this->_set_time_for($time, 'DTT_EVT_end');
188
-    }
189
-
190
-
191
-    /**
192
-     * Set registration limit
193
-     * set the maximum number of attendees that can be registered for this datetime slot
194
-     *
195
-     * @param int|float $reg_limit
196
-     * @throws ReflectionException
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidInterfaceException
199
-     * @throws InvalidDataTypeException
200
-     * @throws EE_Error
201
-     */
202
-    public function set_reg_limit($reg_limit)
203
-    {
204
-        $this->set('DTT_reg_limit', $reg_limit);
205
-    }
206
-
207
-
208
-    /**
209
-     * get the number of tickets sold for this datetime slot
210
-     *
211
-     * @return mixed int on success, FALSE on fail
212
-     * @throws ReflectionException
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidInterfaceException
215
-     * @throws InvalidDataTypeException
216
-     * @throws EE_Error
217
-     */
218
-    public function sold()
219
-    {
220
-        return $this->get_raw('DTT_sold');
221
-    }
222
-
223
-
224
-    /**
225
-     * @param int $sold
226
-     * @throws ReflectionException
227
-     * @throws InvalidArgumentException
228
-     * @throws InvalidInterfaceException
229
-     * @throws InvalidDataTypeException
230
-     * @throws EE_Error
231
-     */
232
-    public function set_sold($sold)
233
-    {
234
-        // sold can not go below zero
235
-        $sold = max(0, $sold);
236
-        $this->set('DTT_sold', $sold);
237
-    }
238
-
239
-
240
-    /**
241
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
-     *
244
-     * @param int $qty
245
-     * @param boolean $also_decrease_reserved
246
-     * @return boolean indicating success
247
-     * @throws ReflectionException
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidInterfaceException
250
-     * @throws InvalidDataTypeException
251
-     * @throws EE_Error
252
-     */
253
-    public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
-    {
255
-        $qty = absint($qty);
256
-        if ($also_decrease_reserved) {
257
-            $success = $this->adjustNumericFieldsInDb(
258
-                [
259
-                    'DTT_reserved' => $qty * -1,
260
-                    'DTT_sold' => $qty
261
-                ]
262
-            );
263
-        } else {
264
-            $success = $this->adjustNumericFieldsInDb(
265
-                [
266
-                    'DTT_sold' => $qty
267
-                ]
268
-            );
269
-        }
270
-
271
-        do_action(
272
-            'AHEE__EE_Datetime__increase_sold',
273
-            $this,
274
-            $qty,
275
-            $this->sold(),
276
-            $success
277
-        );
278
-        return $success;
279
-    }
280
-
281
-
282
-    /**
283
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
-     * to save afterwards.)
285
-     *
286
-     * @param int $qty
287
-     * @return boolean indicating success
288
-     * @throws ReflectionException
289
-     * @throws InvalidArgumentException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidDataTypeException
292
-     * @throws EE_Error
293
-     */
294
-    public function decreaseSold(int $qty = 1): bool
295
-    {
296
-        $qty = absint($qty);
297
-        $success = $this->adjustNumericFieldsInDb(
298
-            [
299
-                'DTT_sold' => $qty * -1
300
-            ]
301
-        );
302
-        do_action(
303
-            'AHEE__EE_Datetime__decrease_sold',
304
-            $this,
305
-            $qty,
306
-            $this->sold(),
307
-            $success
308
-        );
309
-        return $success;
310
-    }
311
-
312
-
313
-    /**
314
-     * Gets qty of reserved tickets for this datetime
315
-     *
316
-     * @return int
317
-     * @throws ReflectionException
318
-     * @throws InvalidArgumentException
319
-     * @throws InvalidInterfaceException
320
-     * @throws InvalidDataTypeException
321
-     * @throws EE_Error
322
-     */
323
-    public function reserved(): int
324
-    {
325
-        return $this->get_raw('DTT_reserved');
326
-    }
327
-
328
-
329
-    /**
330
-     * Sets qty of reserved tickets for this datetime
331
-     *
332
-     * @param int $reserved
333
-     * @throws ReflectionException
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidDataTypeException
337
-     * @throws EE_Error
338
-     */
339
-    public function set_reserved(int $reserved)
340
-    {
341
-        // reserved can not go below zero
342
-        $reserved = max(0, $reserved);
343
-        $this->set('DTT_reserved', $reserved);
344
-    }
345
-
346
-
347
-    /**
348
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
-     *
350
-     * @param int $qty
351
-     * @return boolean indicating success
352
-     * @throws ReflectionException
353
-     * @throws InvalidArgumentException
354
-     * @throws InvalidInterfaceException
355
-     * @throws InvalidDataTypeException
356
-     * @throws EE_Error
357
-     */
358
-    public function increaseReserved(int $qty = 1): bool
359
-    {
360
-        $qty = absint($qty);
361
-        $success = $this->incrementFieldConditionallyInDb(
362
-            'DTT_reserved',
363
-            'DTT_sold',
364
-            'DTT_reg_limit',
365
-            $qty
366
-        );
367
-        do_action(
368
-            'AHEE__EE_Datetime__increase_reserved',
369
-            $this,
370
-            $qty,
371
-            $this->reserved(),
372
-            $success
373
-        );
374
-        return $success;
375
-    }
376
-
377
-
378
-    /**
379
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
-     *
381
-     * @param int $qty
382
-     * @return boolean indicating success
383
-     * @throws ReflectionException
384
-     * @throws InvalidArgumentException
385
-     * @throws InvalidInterfaceException
386
-     * @throws InvalidDataTypeException
387
-     * @throws EE_Error
388
-     */
389
-    public function decreaseReserved(int $qty = 1): bool
390
-    {
391
-        $qty = absint($qty);
392
-        $success = $this->adjustNumericFieldsInDb(
393
-            [
394
-                'DTT_reserved' => $qty * -1
395
-            ]
396
-        );
397
-        do_action(
398
-            'AHEE__EE_Datetime__decrease_reserved',
399
-            $this,
400
-            $qty,
401
-            $this->reserved(),
402
-            $success
403
-        );
404
-        return $success;
405
-    }
406
-
407
-
408
-    /**
409
-     * total sold and reserved tickets
410
-     *
411
-     * @return int
412
-     * @throws ReflectionException
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidInterfaceException
415
-     * @throws InvalidDataTypeException
416
-     * @throws EE_Error
417
-     */
418
-    public function sold_and_reserved(): int
419
-    {
420
-        return $this->sold() + $this->reserved();
421
-    }
422
-
423
-
424
-    /**
425
-     * returns the datetime name
426
-     *
427
-     * @return string
428
-     * @throws ReflectionException
429
-     * @throws InvalidArgumentException
430
-     * @throws InvalidInterfaceException
431
-     * @throws InvalidDataTypeException
432
-     * @throws EE_Error
433
-     */
434
-    public function name(): string
435
-    {
436
-        return $this->get('DTT_name');
437
-    }
438
-
439
-
440
-    /**
441
-     * returns the datetime description
442
-     *
443
-     * @return string
444
-     * @throws ReflectionException
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidInterfaceException
447
-     * @throws InvalidDataTypeException
448
-     * @throws EE_Error
449
-     */
450
-    public function description(): string
451
-    {
452
-        return $this->get('DTT_description');
453
-    }
454
-
455
-
456
-    /**
457
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
-     *
459
-     * @return boolean  TRUE if is primary, FALSE if not.
460
-     * @throws ReflectionException
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     */
466
-    public function is_primary(): bool
467
-    {
468
-        return $this->get('DTT_is_primary');
469
-    }
470
-
471
-
472
-    /**
473
-     * This helper simply returns the order for the datetime
474
-     *
475
-     * @return int  The order of the datetime for this event.
476
-     * @throws ReflectionException
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidInterfaceException
479
-     * @throws InvalidDataTypeException
480
-     * @throws EE_Error
481
-     */
482
-    public function order(): int
483
-    {
484
-        return $this->get('DTT_order');
485
-    }
486
-
487
-
488
-    /**
489
-     * This helper simply returns the parent id for the datetime
490
-     *
491
-     * @return int
492
-     * @throws ReflectionException
493
-     * @throws InvalidArgumentException
494
-     * @throws InvalidInterfaceException
495
-     * @throws InvalidDataTypeException
496
-     * @throws EE_Error
497
-     */
498
-    public function parent(): int
499
-    {
500
-        return $this->get('DTT_parent');
501
-    }
502
-
503
-
504
-    /**
505
-     * show date and/or time
506
-     *
507
-     * @param string $date_or_time    whether to display a date or time or both
508
-     * @param string $start_or_end    whether to display start or end datetimes
509
-     * @param string $dt_frmt
510
-     * @param string $tm_frmt
511
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
-     *                                otherwise we use the standard formats)
513
-     * @return string|bool  string on success, FALSE on fail
514
-     * @throws ReflectionException
515
-     * @throws InvalidArgumentException
516
-     * @throws InvalidInterfaceException
517
-     * @throws InvalidDataTypeException
518
-     * @throws EE_Error
519
-     */
520
-    private function _show_datetime(
521
-        $date_or_time = null,
522
-        $start_or_end = 'start',
523
-        $dt_frmt = '',
524
-        $tm_frmt = '',
525
-        $echo = false
526
-    ) {
527
-        $field_name = "DTT_EVT_{$start_or_end}";
528
-        $dtt = $this->_get_datetime(
529
-            $field_name,
530
-            $dt_frmt,
531
-            $tm_frmt,
532
-            $date_or_time,
533
-            $echo
534
-        );
535
-        if (! $echo) {
536
-            return $dtt;
537
-        }
538
-        return '';
539
-    }
540
-
541
-
542
-    /**
543
-     * get event start date.  Provide either the date format, or NULL to re-use the
544
-     * last-used format, or '' to use the default date format
545
-     *
546
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
-     * @return mixed            string on success, FALSE on fail
548
-     * @throws ReflectionException
549
-     * @throws InvalidArgumentException
550
-     * @throws InvalidInterfaceException
551
-     * @throws InvalidDataTypeException
552
-     * @throws EE_Error
553
-     */
554
-    public function start_date($dt_frmt = '')
555
-    {
556
-        return $this->_show_datetime('D', 'start', $dt_frmt);
557
-    }
558
-
559
-
560
-    /**
561
-     * Echoes start_date()
562
-     *
563
-     * @param string $dt_frmt
564
-     * @throws ReflectionException
565
-     * @throws InvalidArgumentException
566
-     * @throws InvalidInterfaceException
567
-     * @throws InvalidDataTypeException
568
-     * @throws EE_Error
569
-     */
570
-    public function e_start_date($dt_frmt = '')
571
-    {
572
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
-    }
574
-
575
-
576
-    /**
577
-     * get end date. Provide either the date format, or NULL to re-use the
578
-     * last-used format, or '' to use the default date format
579
-     *
580
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
-     * @return mixed            string on success, FALSE on fail
582
-     * @throws ReflectionException
583
-     * @throws InvalidArgumentException
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     */
588
-    public function end_date($dt_frmt = '')
589
-    {
590
-        return $this->_show_datetime('D', 'end', $dt_frmt);
591
-    }
592
-
593
-
594
-    /**
595
-     * Echoes the end date. See end_date()
596
-     *
597
-     * @param string $dt_frmt
598
-     * @throws ReflectionException
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidInterfaceException
601
-     * @throws InvalidDataTypeException
602
-     * @throws EE_Error
603
-     */
604
-    public function e_end_date($dt_frmt = '')
605
-    {
606
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
-    }
608
-
609
-
610
-    /**
611
-     * get date_range - meaning the start AND end date
612
-     *
613
-     * @access public
614
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
615
-     * @param string $conjunction conjunction junction what's your function ?
616
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
-     * @return mixed              string on success, FALSE on fail
618
-     * @throws ReflectionException
619
-     * @throws InvalidArgumentException
620
-     * @throws InvalidInterfaceException
621
-     * @throws InvalidDataTypeException
622
-     * @throws EE_Error
623
-     */
624
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
625
-    {
626
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
-        $start = str_replace(
628
-            ' ',
629
-            '&nbsp;',
630
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
-        );
632
-        $end = str_replace(
633
-            ' ',
634
-            '&nbsp;',
635
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
-        );
637
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
-    }
639
-
640
-
641
-    /**
642
-     * @param string $dt_frmt
643
-     * @param string $conjunction
644
-     * @throws ReflectionException
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
-    {
652
-        echo esc_html($this->date_range($dt_frmt, $conjunction));
653
-    }
654
-
655
-
656
-    /**
657
-     * get start time
658
-     *
659
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
-     * @return mixed        string on success, FALSE on fail
661
-     * @throws ReflectionException
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     */
667
-    public function start_time($tm_format = '')
668
-    {
669
-        return $this->_show_datetime('T', 'start', null, $tm_format);
670
-    }
671
-
672
-
673
-    /**
674
-     * @param string $tm_format
675
-     * @throws ReflectionException
676
-     * @throws InvalidArgumentException
677
-     * @throws InvalidInterfaceException
678
-     * @throws InvalidDataTypeException
679
-     * @throws EE_Error
680
-     */
681
-    public function e_start_time($tm_format = '')
682
-    {
683
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
684
-    }
685
-
686
-
687
-    /**
688
-     * get end time
689
-     *
690
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
691
-     * @return mixed                string on success, FALSE on fail
692
-     * @throws ReflectionException
693
-     * @throws InvalidArgumentException
694
-     * @throws InvalidInterfaceException
695
-     * @throws InvalidDataTypeException
696
-     * @throws EE_Error
697
-     */
698
-    public function end_time($tm_format = '')
699
-    {
700
-        return $this->_show_datetime('T', 'end', null, $tm_format);
701
-    }
702
-
703
-
704
-    /**
705
-     * @param string $tm_format
706
-     * @throws ReflectionException
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidInterfaceException
709
-     * @throws InvalidDataTypeException
710
-     * @throws EE_Error
711
-     */
712
-    public function e_end_time($tm_format = '')
713
-    {
714
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
715
-    }
716
-
717
-
718
-    /**
719
-     * get time_range
720
-     *
721
-     * @access public
722
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
-     * @param string $conjunction conjunction junction what's your function ?
724
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
-     * @return mixed              string on success, FALSE on fail
726
-     * @throws ReflectionException
727
-     * @throws InvalidArgumentException
728
-     * @throws InvalidInterfaceException
729
-     * @throws InvalidDataTypeException
730
-     * @throws EE_Error
731
-     */
732
-    public function time_range($tm_format = '', $conjunction = ' - ')
733
-    {
734
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
-        $start = str_replace(
736
-            ' ',
737
-            '&nbsp;',
738
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
-        );
740
-        $end = str_replace(
741
-            ' ',
742
-            '&nbsp;',
743
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
-        );
745
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
-    }
747
-
748
-
749
-    /**
750
-     * @param string $tm_format
751
-     * @param string $conjunction
752
-     * @throws ReflectionException
753
-     * @throws InvalidArgumentException
754
-     * @throws InvalidInterfaceException
755
-     * @throws InvalidDataTypeException
756
-     * @throws EE_Error
757
-     */
758
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
759
-    {
760
-        echo esc_html($this->time_range($tm_format, $conjunction));
761
-    }
762
-
763
-
764
-    /**
765
-     * This returns a range representation of the date and times.
766
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
-     * Also, the return value is localized.
768
-     *
769
-     * @param string $dt_format
770
-     * @param string $tm_format
771
-     * @param string $conjunction used between two different dates or times.
772
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
-     * @param string $separator   used between the date and time formats.
774
-     *                            ex: Dec 1, 2016{$separator}2pm
775
-     * @return string
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    public function date_and_time_range(
783
-        $dt_format = '',
784
-        $tm_format = '',
785
-        $conjunction = ' - ',
786
-        $separator = ' '
787
-    ) {
788
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
-        $full_format = $dt_format . $separator . $tm_format;
791
-        // the range output depends on various conditions
792
-        switch (true) {
793
-            // start date timestamp and end date timestamp are the same.
794
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
-                break;
797
-            // start and end date are the same but times are different
798
-            case ($this->start_date() === $this->end_date()):
799
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
-                          . $conjunction
801
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
-                break;
803
-            // all other conditions
804
-            default:
805
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
-                          . $conjunction
807
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
-                break;
809
-        }
810
-        return $output;
811
-    }
812
-
813
-
814
-    /**
815
-     * This echos the results of date and time range.
816
-     *
817
-     * @see date_and_time_range() for more details on purpose.
818
-     * @param string $dt_format
819
-     * @param string $tm_format
820
-     * @param string $conjunction
821
-     * @return void
822
-     * @throws ReflectionException
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidInterfaceException
825
-     * @throws InvalidDataTypeException
826
-     * @throws EE_Error
827
-     */
828
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
-    {
830
-        echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
-    }
832
-
833
-
834
-    /**
835
-     * get start date and start time
836
-     *
837
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
-     * @return    mixed    string on success, FALSE on fail
840
-     * @throws ReflectionException
841
-     * @throws InvalidArgumentException
842
-     * @throws InvalidInterfaceException
843
-     * @throws InvalidDataTypeException
844
-     * @throws EE_Error
845
-     */
846
-    public function start_date_and_time($dt_format = '', $tm_format = '')
847
-    {
848
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
-    }
850
-
851
-
852
-    /**
853
-     * @param string $dt_frmt
854
-     * @param string $tm_format
855
-     * @throws ReflectionException
856
-     * @throws InvalidArgumentException
857
-     * @throws InvalidInterfaceException
858
-     * @throws InvalidDataTypeException
859
-     * @throws EE_Error
860
-     */
861
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
-    {
863
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
-    }
865
-
866
-
867
-    /**
868
-     * Shows the length of the event (start to end time).
869
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
870
-     * By default, rounds up. (So if you use 'days', and then event
871
-     * only occurs for 1 hour, it will return 1 day).
872
-     *
873
-     * @param string $units 'seconds','minutes','hours','days'
874
-     * @param bool   $round_up
875
-     * @return float|int|mixed
876
-     * @throws ReflectionException
877
-     * @throws InvalidArgumentException
878
-     * @throws InvalidInterfaceException
879
-     * @throws InvalidDataTypeException
880
-     * @throws EE_Error
881
-     */
882
-    public function length($units = 'seconds', $round_up = false)
883
-    {
884
-        $start = $this->get_raw('DTT_EVT_start');
885
-        $end = $this->get_raw('DTT_EVT_end');
886
-        $length_in_units = $end - $start;
887
-        switch ($units) {
888
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
889
-            /** @noinspection PhpMissingBreakStatementInspection */
890
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
-            case 'days':
892
-                $length_in_units /= 24;
893
-            /** @noinspection PhpMissingBreakStatementInspection */
894
-            case 'hours':
895
-                // fall through is intentional
896
-                $length_in_units /= 60;
897
-            /** @noinspection PhpMissingBreakStatementInspection */
898
-            case 'minutes':
899
-                // fall through is intentional
900
-                $length_in_units /= 60;
901
-            case 'seconds':
902
-            default:
903
-                $length_in_units = ceil($length_in_units);
904
-        }
905
-        // phpcs:enable
906
-        if ($round_up) {
907
-            $length_in_units = max($length_in_units, 1);
908
-        }
909
-        return $length_in_units;
910
-    }
911
-
912
-
913
-    /**
914
-     *        get end date and time
915
-     *
916
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
-     * @return    mixed                string on success, FALSE on fail
919
-     * @throws ReflectionException
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidInterfaceException
922
-     * @throws InvalidDataTypeException
923
-     * @throws EE_Error
924
-     */
925
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
-    {
927
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
-    }
929
-
930
-
931
-    /**
932
-     * @param string $dt_frmt
933
-     * @param string $tm_format
934
-     * @throws ReflectionException
935
-     * @throws InvalidArgumentException
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidDataTypeException
938
-     * @throws EE_Error
939
-     */
940
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
-    {
942
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
-    }
944
-
945
-
946
-    /**
947
-     *        get start timestamp
948
-     *
949
-     * @return        int
950
-     * @throws ReflectionException
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidInterfaceException
953
-     * @throws InvalidDataTypeException
954
-     * @throws EE_Error
955
-     */
956
-    public function start()
957
-    {
958
-        return $this->get_raw('DTT_EVT_start');
959
-    }
960
-
961
-
962
-    /**
963
-     *        get end timestamp
964
-     *
965
-     * @return        int
966
-     * @throws ReflectionException
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidInterfaceException
969
-     * @throws InvalidDataTypeException
970
-     * @throws EE_Error
971
-     */
972
-    public function end()
973
-    {
974
-        return $this->get_raw('DTT_EVT_end');
975
-    }
976
-
977
-
978
-    /**
979
-     *    get the registration limit for this datetime slot
980
-     *
981
-     * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
-     * @throws ReflectionException
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidInterfaceException
985
-     * @throws InvalidDataTypeException
986
-     * @throws EE_Error
987
-     */
988
-    public function reg_limit()
989
-    {
990
-        return $this->get_raw('DTT_reg_limit');
991
-    }
992
-
993
-
994
-    /**
995
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
-     *
997
-     * @return boolean
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     */
1004
-    public function sold_out()
1005
-    {
1006
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
-    }
1008
-
1009
-
1010
-    /**
1011
-     * return the total number of spaces remaining at this venue.
1012
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
-     *
1014
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
-     *                               Because if all tickets attached to this datetime have no spaces left,
1016
-     *                               then this datetime IS effectively sold out.
1017
-     *                               However, there are cases where we just want to know the spaces
1018
-     *                               remaining for this particular datetime, hence the flag.
1019
-     * @return int|float
1020
-     * @throws ReflectionException
1021
-     * @throws InvalidArgumentException
1022
-     * @throws InvalidInterfaceException
1023
-     * @throws InvalidDataTypeException
1024
-     * @throws EE_Error
1025
-     */
1026
-    public function spaces_remaining($consider_tickets = false)
1027
-    {
1028
-        // tickets remaining available for purchase
1029
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
-        if (! $consider_tickets) {
1032
-            return $dtt_remaining;
1033
-        }
1034
-        $tickets_remaining = $this->tickets_remaining();
1035
-        return min($dtt_remaining, $tickets_remaining);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Counts the total tickets available
1041
-     * (from all the different types of tickets which are available for this datetime).
1042
-     *
1043
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
-     * @return int
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidArgumentException
1047
-     * @throws InvalidInterfaceException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws EE_Error
1050
-     */
1051
-    public function tickets_remaining($query_params = array())
1052
-    {
1053
-        $sum = 0;
1054
-        $tickets = $this->tickets($query_params);
1055
-        if (! empty($tickets)) {
1056
-            foreach ($tickets as $ticket) {
1057
-                if ($ticket instanceof EE_Ticket) {
1058
-                    // get the actual amount of tickets that can be sold
1059
-                    $qty = $ticket->qty('saleable');
1060
-                    if ($qty === EE_INF) {
1061
-                        return EE_INF;
1062
-                    }
1063
-                    // no negative ticket quantities plz
1064
-                    if ($qty > 0) {
1065
-                        $sum += $qty;
1066
-                    }
1067
-                }
1068
-            }
1069
-        }
1070
-        return $sum;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1076
-     * before any were sold
1077
-     *
1078
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
-     * @return int
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function sum_tickets_initially_available($query_params = array())
1087
-    {
1088
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
-     * that is available for this datetime).
1096
-     *
1097
-     * @return int
1098
-     * @throws ReflectionException
1099
-     * @throws InvalidArgumentException
1100
-     * @throws InvalidInterfaceException
1101
-     * @throws InvalidDataTypeException
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function total_tickets_available_at_this_datetime()
1105
-    {
1106
-        return $this->spaces_remaining(true);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * This simply compares the internal dtt for the given string with NOW
1112
-     * and determines if the date is upcoming or not.
1113
-     *
1114
-     * @access public
1115
-     * @return boolean
1116
-     * @throws ReflectionException
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidInterfaceException
1119
-     * @throws InvalidDataTypeException
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function is_upcoming()
1123
-    {
1124
-        return ($this->get_raw('DTT_EVT_start') > time());
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * This simply compares the internal datetime for the given string with NOW
1130
-     * and returns if the date is active (i.e. start and end time)
1131
-     *
1132
-     * @return boolean
1133
-     * @throws ReflectionException
1134
-     * @throws InvalidArgumentException
1135
-     * @throws InvalidInterfaceException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function is_active()
1140
-    {
1141
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * This simply compares the internal dtt for the given string with NOW
1147
-     * and determines if the date is expired or not.
1148
-     *
1149
-     * @return boolean
1150
-     * @throws ReflectionException
1151
-     * @throws InvalidArgumentException
1152
-     * @throws InvalidInterfaceException
1153
-     * @throws InvalidDataTypeException
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function is_expired()
1157
-    {
1158
-        return ($this->get_raw('DTT_EVT_end') < time());
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * This returns the active status for whether an event is active, upcoming, or expired
1164
-     *
1165
-     * @return int return value will be one of the EE_Datetime status constants.
1166
-     * @throws ReflectionException
1167
-     * @throws InvalidArgumentException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws InvalidDataTypeException
1170
-     * @throws EE_Error
1171
-     */
1172
-    public function get_active_status()
1173
-    {
1174
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
-            return EE_Datetime::sold_out;
1177
-        }
1178
-        if ($this->is_expired()) {
1179
-            return EE_Datetime::expired;
1180
-        }
1181
-        if ($this->is_upcoming()) {
1182
-            return EE_Datetime::upcoming;
1183
-        }
1184
-        if ($this->is_active()) {
1185
-            return EE_Datetime::active;
1186
-        }
1187
-        return null;
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
-     *
1194
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
-     * @return string
1196
-     * @throws ReflectionException
1197
-     * @throws InvalidArgumentException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function get_dtt_display_name($use_dtt_name = false)
1203
-    {
1204
-        if ($use_dtt_name) {
1205
-            $dtt_name = $this->name();
1206
-            if (! empty($dtt_name)) {
1207
-                return $dtt_name;
1208
-            }
1209
-        }
1210
-        // first condition is to see if the months are different
1211
-        if (
1212
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
-        ) {
1214
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
-            // next condition is if its the same month but different day
1216
-        } else {
1217
-            if (
1218
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
-            ) {
1221
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
-            } else {
1223
-                $display_date = $this->start_date('F j\, Y')
1224
-                                . ' @ '
1225
-                                . $this->start_date('g:i a')
1226
-                                . ' - '
1227
-                                . $this->end_date('g:i a');
1228
-            }
1229
-        }
1230
-        return $display_date;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     * Gets all the tickets for this datetime
1236
-     *
1237
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
-     * @return EE_Base_Class[]|EE_Ticket[]
1239
-     * @throws ReflectionException
1240
-     * @throws InvalidArgumentException
1241
-     * @throws InvalidInterfaceException
1242
-     * @throws InvalidDataTypeException
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function tickets($query_params = array())
1246
-    {
1247
-        return $this->get_many_related('Ticket', $query_params);
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * Gets all the ticket types currently available for purchase
1253
-     *
1254
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
-     * @return EE_Ticket[]
1256
-     * @throws ReflectionException
1257
-     * @throws InvalidArgumentException
1258
-     * @throws InvalidInterfaceException
1259
-     * @throws InvalidDataTypeException
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function ticket_types_available_for_purchase($query_params = array())
1263
-    {
1264
-        // first check if datetime is valid
1265
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
-            return array();
1267
-        }
1268
-        if (empty($query_params)) {
1269
-            $query_params = array(
1270
-                array(
1271
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
-                    'TKT_deleted'    => false,
1274
-                ),
1275
-            );
1276
-        }
1277
-        return $this->tickets($query_params);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * @return EE_Base_Class|EE_Event
1283
-     * @throws ReflectionException
1284
-     * @throws InvalidArgumentException
1285
-     * @throws InvalidInterfaceException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws EE_Error
1288
-     */
1289
-    public function event()
1290
-    {
1291
-        return $this->get_first_related('Event');
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
-     * (via the tickets).
1298
-     *
1299
-     * @return int
1300
-     * @throws ReflectionException
1301
-     * @throws InvalidArgumentException
1302
-     * @throws InvalidInterfaceException
1303
-     * @throws InvalidDataTypeException
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function update_sold()
1307
-    {
1308
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
-            array(
1310
-                array(
1311
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1312
-                    'REG_deleted'            => 0,
1313
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
-                ),
1315
-            )
1316
-        );
1317
-        $this->set_sold($count_regs_for_this_datetime);
1318
-        $this->save();
1319
-        return $count_regs_for_this_datetime;
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Adds a venue to this event
1325
-     *
1326
-     * @param int|EE_Venue /int $venue_id_or_obj
1327
-     * @return EE_Base_Class|EE_Venue
1328
-     * @throws EE_Error
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function add_venue($venue_id_or_obj): EE_Venue
1332
-    {
1333
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Removes a venue from the event
1339
-     *
1340
-     * @param EE_Venue /int $venue_id_or_obj
1341
-     * @return EE_Base_Class|EE_Venue
1342
-     * @throws EE_Error
1343
-     * @throws ReflectionException
1344
-     */
1345
-    public function remove_venue($venue_id_or_obj): EE_Venue
1346
-    {
1347
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Gets the venue related to the event. May provide additional $query_params if desired
1354
-     *
1355
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
-     * @return int
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function venue_ID(array $query_params = []): int
1361
-    {
1362
-        $venue = $this->get_first_related('Venue', $query_params);
1363
-        return $venue instanceof EE_Venue
1364
-            ? $venue->ID()
1365
-            : 0;
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Gets the venue related to the event. May provide additional $query_params if desired
1371
-     *
1372
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
-     * @return EE_Base_Class|EE_Venue
1374
-     * @throws EE_Error
1375
-     * @throws ReflectionException
1376
-     */
1377
-    public function venue(array $query_params = [])
1378
-    {
1379
-        return $this->get_first_related('Venue', $query_params);
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
-     * @param string                   $relationName
1386
-     * @param array                    $extra_join_model_fields_n_values
1387
-     * @param string|null              $cache_id
1388
-     * @return EE_Base_Class
1389
-     * @throws EE_Error
1390
-     * @throws ReflectionException
1391
-     * @since   $VID:$
1392
-     */
1393
-    public function _add_relation_to(
1394
-        $otherObjectModelObjectOrID,
1395
-        $relationName,
1396
-        $extra_join_model_fields_n_values = [],
1397
-        $cache_id = null
1398
-    ) {
1399
-        // if we're adding a new relation to a ticket
1400
-        if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
-            /** @var EE_Ticket $ticket */
1402
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
-            $this->increaseSold($ticket->sold(), false);
1404
-            $this->increaseReserved($ticket->reserved());
1405
-            $this->save();
1406
-            $otherObjectModelObjectOrID = $ticket;
1407
-        }
1408
-        return parent::_add_relation_to(
1409
-            $otherObjectModelObjectOrID,
1410
-            $relationName,
1411
-            $extra_join_model_fields_n_values,
1412
-            $cache_id
1413
-        );
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
-     * @param string                   $relationName
1420
-     * @param array                    $where_query
1421
-     * @return bool|EE_Base_Class|null
1422
-     * @throws EE_Error
1423
-     * @throws ReflectionException
1424
-     * @since   $VID:$
1425
-     */
1426
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
-    {
1428
-        if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
-            /** @var EE_Ticket $ticket */
1430
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
-            $this->decreaseSold($ticket->sold());
1432
-            $this->decreaseReserved($ticket->reserved());
1433
-            $this->save();
1434
-            $otherObjectModelObjectOrID = $ticket;
1435
-        }
1436
-        return parent::_remove_relation_to(
1437
-            $otherObjectModelObjectOrID,
1438
-            $relationName,
1439
-            $where_query
1440
-        );
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Removes ALL the related things for the $relationName.
1446
-     *
1447
-     * @param string $relationName
1448
-     * @param array  $where_query_params
1449
-     * @return EE_Base_Class
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
-     */
1457
-    public function _remove_relations($relationName, $where_query_params = [])
1458
-    {
1459
-        if ($relationName === 'Ticket') {
1460
-            $tickets = $this->tickets();
1461
-            foreach ($tickets as $ticket) {
1462
-                $this->decreaseSold($ticket->sold());
1463
-                $this->decreaseReserved($ticket->reserved());
1464
-                $this->save();
1465
-            }
1466
-        }
1467
-        return parent::_remove_relations($relationName, $where_query_params);
1468
-    }
1469
-
1470
-
1471
-    /*******************************************************************
15
+	/**
16
+	 * constant used by get_active_status, indicates datetime has no more available spaces
17
+	 */
18
+	const sold_out = 'DTS';
19
+
20
+	/**
21
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
+	 */
23
+	const active = 'DTA';
24
+
25
+	/**
26
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
+	 * expired
28
+	 */
29
+	const upcoming = 'DTU';
30
+
31
+	/**
32
+	 * Datetime is postponed
33
+	 */
34
+	const postponed = 'DTP';
35
+
36
+	/**
37
+	 * Datetime is cancelled
38
+	 */
39
+	const cancelled = 'DTC';
40
+
41
+	/**
42
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
43
+	 */
44
+	const expired = 'DTE';
45
+
46
+	/**
47
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
+	 */
49
+	const inactive = 'DTI';
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values    incoming values
54
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
+	 *                                  and the second value is the time format
57
+	 * @return EE_Datetime
58
+	 * @throws ReflectionException
59
+	 * @throws InvalidArgumentException
60
+	 * @throws InvalidInterfaceException
61
+	 * @throws InvalidDataTypeException
62
+	 * @throws EE_Error
63
+	 */
64
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
+	{
66
+		$has_object = parent::_check_for_object(
67
+			$props_n_values,
68
+			__CLASS__,
69
+			$timezone,
70
+			$date_formats
71
+		);
72
+		return $has_object
73
+			? $has_object
74
+			: new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Datetime
83
+	 * @throws ReflectionException
84
+	 * @throws InvalidArgumentException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws EE_Error
88
+	 */
89
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
+	{
91
+		return new self($props_n_values, true, $timezone);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param $name
97
+	 * @throws ReflectionException
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidInterfaceException
100
+	 * @throws InvalidDataTypeException
101
+	 * @throws EE_Error
102
+	 */
103
+	public function set_name($name)
104
+	{
105
+		$this->set('DTT_name', $name);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param $description
111
+	 * @throws ReflectionException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws InvalidDataTypeException
115
+	 * @throws EE_Error
116
+	 */
117
+	public function set_description($description)
118
+	{
119
+		$this->set('DTT_description', $description);
120
+	}
121
+
122
+
123
+	/**
124
+	 * Set event start date
125
+	 * set the start date for an event
126
+	 *
127
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
+	 * @throws ReflectionException
129
+	 * @throws InvalidArgumentException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws EE_Error
133
+	 */
134
+	public function set_start_date($date)
135
+	{
136
+		$this->_set_date_for($date, 'DTT_EVT_start');
137
+	}
138
+
139
+
140
+	/**
141
+	 * Set event start time
142
+	 * set the start time for an event
143
+	 *
144
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
+	 * @throws ReflectionException
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidInterfaceException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws EE_Error
150
+	 */
151
+	public function set_start_time($time)
152
+	{
153
+		$this->_set_time_for($time, 'DTT_EVT_start');
154
+	}
155
+
156
+
157
+	/**
158
+	 * Set event end date
159
+	 * set the end date for an event
160
+	 *
161
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
+	 * @throws ReflectionException
163
+	 * @throws InvalidArgumentException
164
+	 * @throws InvalidInterfaceException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws EE_Error
167
+	 */
168
+	public function set_end_date($date)
169
+	{
170
+		$this->_set_date_for($date, 'DTT_EVT_end');
171
+	}
172
+
173
+
174
+	/**
175
+	 * Set event end time
176
+	 * set the end time for an event
177
+	 *
178
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
+	 * @throws ReflectionException
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidInterfaceException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws EE_Error
184
+	 */
185
+	public function set_end_time($time)
186
+	{
187
+		$this->_set_time_for($time, 'DTT_EVT_end');
188
+	}
189
+
190
+
191
+	/**
192
+	 * Set registration limit
193
+	 * set the maximum number of attendees that can be registered for this datetime slot
194
+	 *
195
+	 * @param int|float $reg_limit
196
+	 * @throws ReflectionException
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidInterfaceException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws EE_Error
201
+	 */
202
+	public function set_reg_limit($reg_limit)
203
+	{
204
+		$this->set('DTT_reg_limit', $reg_limit);
205
+	}
206
+
207
+
208
+	/**
209
+	 * get the number of tickets sold for this datetime slot
210
+	 *
211
+	 * @return mixed int on success, FALSE on fail
212
+	 * @throws ReflectionException
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidInterfaceException
215
+	 * @throws InvalidDataTypeException
216
+	 * @throws EE_Error
217
+	 */
218
+	public function sold()
219
+	{
220
+		return $this->get_raw('DTT_sold');
221
+	}
222
+
223
+
224
+	/**
225
+	 * @param int $sold
226
+	 * @throws ReflectionException
227
+	 * @throws InvalidArgumentException
228
+	 * @throws InvalidInterfaceException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws EE_Error
231
+	 */
232
+	public function set_sold($sold)
233
+	{
234
+		// sold can not go below zero
235
+		$sold = max(0, $sold);
236
+		$this->set('DTT_sold', $sold);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
+	 *
244
+	 * @param int $qty
245
+	 * @param boolean $also_decrease_reserved
246
+	 * @return boolean indicating success
247
+	 * @throws ReflectionException
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws EE_Error
252
+	 */
253
+	public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
+	{
255
+		$qty = absint($qty);
256
+		if ($also_decrease_reserved) {
257
+			$success = $this->adjustNumericFieldsInDb(
258
+				[
259
+					'DTT_reserved' => $qty * -1,
260
+					'DTT_sold' => $qty
261
+				]
262
+			);
263
+		} else {
264
+			$success = $this->adjustNumericFieldsInDb(
265
+				[
266
+					'DTT_sold' => $qty
267
+				]
268
+			);
269
+		}
270
+
271
+		do_action(
272
+			'AHEE__EE_Datetime__increase_sold',
273
+			$this,
274
+			$qty,
275
+			$this->sold(),
276
+			$success
277
+		);
278
+		return $success;
279
+	}
280
+
281
+
282
+	/**
283
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
+	 * to save afterwards.)
285
+	 *
286
+	 * @param int $qty
287
+	 * @return boolean indicating success
288
+	 * @throws ReflectionException
289
+	 * @throws InvalidArgumentException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws EE_Error
293
+	 */
294
+	public function decreaseSold(int $qty = 1): bool
295
+	{
296
+		$qty = absint($qty);
297
+		$success = $this->adjustNumericFieldsInDb(
298
+			[
299
+				'DTT_sold' => $qty * -1
300
+			]
301
+		);
302
+		do_action(
303
+			'AHEE__EE_Datetime__decrease_sold',
304
+			$this,
305
+			$qty,
306
+			$this->sold(),
307
+			$success
308
+		);
309
+		return $success;
310
+	}
311
+
312
+
313
+	/**
314
+	 * Gets qty of reserved tickets for this datetime
315
+	 *
316
+	 * @return int
317
+	 * @throws ReflectionException
318
+	 * @throws InvalidArgumentException
319
+	 * @throws InvalidInterfaceException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws EE_Error
322
+	 */
323
+	public function reserved(): int
324
+	{
325
+		return $this->get_raw('DTT_reserved');
326
+	}
327
+
328
+
329
+	/**
330
+	 * Sets qty of reserved tickets for this datetime
331
+	 *
332
+	 * @param int $reserved
333
+	 * @throws ReflectionException
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws EE_Error
338
+	 */
339
+	public function set_reserved(int $reserved)
340
+	{
341
+		// reserved can not go below zero
342
+		$reserved = max(0, $reserved);
343
+		$this->set('DTT_reserved', $reserved);
344
+	}
345
+
346
+
347
+	/**
348
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
+	 *
350
+	 * @param int $qty
351
+	 * @return boolean indicating success
352
+	 * @throws ReflectionException
353
+	 * @throws InvalidArgumentException
354
+	 * @throws InvalidInterfaceException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws EE_Error
357
+	 */
358
+	public function increaseReserved(int $qty = 1): bool
359
+	{
360
+		$qty = absint($qty);
361
+		$success = $this->incrementFieldConditionallyInDb(
362
+			'DTT_reserved',
363
+			'DTT_sold',
364
+			'DTT_reg_limit',
365
+			$qty
366
+		);
367
+		do_action(
368
+			'AHEE__EE_Datetime__increase_reserved',
369
+			$this,
370
+			$qty,
371
+			$this->reserved(),
372
+			$success
373
+		);
374
+		return $success;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
+	 *
381
+	 * @param int $qty
382
+	 * @return boolean indicating success
383
+	 * @throws ReflectionException
384
+	 * @throws InvalidArgumentException
385
+	 * @throws InvalidInterfaceException
386
+	 * @throws InvalidDataTypeException
387
+	 * @throws EE_Error
388
+	 */
389
+	public function decreaseReserved(int $qty = 1): bool
390
+	{
391
+		$qty = absint($qty);
392
+		$success = $this->adjustNumericFieldsInDb(
393
+			[
394
+				'DTT_reserved' => $qty * -1
395
+			]
396
+		);
397
+		do_action(
398
+			'AHEE__EE_Datetime__decrease_reserved',
399
+			$this,
400
+			$qty,
401
+			$this->reserved(),
402
+			$success
403
+		);
404
+		return $success;
405
+	}
406
+
407
+
408
+	/**
409
+	 * total sold and reserved tickets
410
+	 *
411
+	 * @return int
412
+	 * @throws ReflectionException
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidInterfaceException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws EE_Error
417
+	 */
418
+	public function sold_and_reserved(): int
419
+	{
420
+		return $this->sold() + $this->reserved();
421
+	}
422
+
423
+
424
+	/**
425
+	 * returns the datetime name
426
+	 *
427
+	 * @return string
428
+	 * @throws ReflectionException
429
+	 * @throws InvalidArgumentException
430
+	 * @throws InvalidInterfaceException
431
+	 * @throws InvalidDataTypeException
432
+	 * @throws EE_Error
433
+	 */
434
+	public function name(): string
435
+	{
436
+		return $this->get('DTT_name');
437
+	}
438
+
439
+
440
+	/**
441
+	 * returns the datetime description
442
+	 *
443
+	 * @return string
444
+	 * @throws ReflectionException
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidInterfaceException
447
+	 * @throws InvalidDataTypeException
448
+	 * @throws EE_Error
449
+	 */
450
+	public function description(): string
451
+	{
452
+		return $this->get('DTT_description');
453
+	}
454
+
455
+
456
+	/**
457
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
+	 *
459
+	 * @return boolean  TRUE if is primary, FALSE if not.
460
+	 * @throws ReflectionException
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 */
466
+	public function is_primary(): bool
467
+	{
468
+		return $this->get('DTT_is_primary');
469
+	}
470
+
471
+
472
+	/**
473
+	 * This helper simply returns the order for the datetime
474
+	 *
475
+	 * @return int  The order of the datetime for this event.
476
+	 * @throws ReflectionException
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidInterfaceException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws EE_Error
481
+	 */
482
+	public function order(): int
483
+	{
484
+		return $this->get('DTT_order');
485
+	}
486
+
487
+
488
+	/**
489
+	 * This helper simply returns the parent id for the datetime
490
+	 *
491
+	 * @return int
492
+	 * @throws ReflectionException
493
+	 * @throws InvalidArgumentException
494
+	 * @throws InvalidInterfaceException
495
+	 * @throws InvalidDataTypeException
496
+	 * @throws EE_Error
497
+	 */
498
+	public function parent(): int
499
+	{
500
+		return $this->get('DTT_parent');
501
+	}
502
+
503
+
504
+	/**
505
+	 * show date and/or time
506
+	 *
507
+	 * @param string $date_or_time    whether to display a date or time or both
508
+	 * @param string $start_or_end    whether to display start or end datetimes
509
+	 * @param string $dt_frmt
510
+	 * @param string $tm_frmt
511
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
+	 *                                otherwise we use the standard formats)
513
+	 * @return string|bool  string on success, FALSE on fail
514
+	 * @throws ReflectionException
515
+	 * @throws InvalidArgumentException
516
+	 * @throws InvalidInterfaceException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws EE_Error
519
+	 */
520
+	private function _show_datetime(
521
+		$date_or_time = null,
522
+		$start_or_end = 'start',
523
+		$dt_frmt = '',
524
+		$tm_frmt = '',
525
+		$echo = false
526
+	) {
527
+		$field_name = "DTT_EVT_{$start_or_end}";
528
+		$dtt = $this->_get_datetime(
529
+			$field_name,
530
+			$dt_frmt,
531
+			$tm_frmt,
532
+			$date_or_time,
533
+			$echo
534
+		);
535
+		if (! $echo) {
536
+			return $dtt;
537
+		}
538
+		return '';
539
+	}
540
+
541
+
542
+	/**
543
+	 * get event start date.  Provide either the date format, or NULL to re-use the
544
+	 * last-used format, or '' to use the default date format
545
+	 *
546
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
+	 * @return mixed            string on success, FALSE on fail
548
+	 * @throws ReflectionException
549
+	 * @throws InvalidArgumentException
550
+	 * @throws InvalidInterfaceException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws EE_Error
553
+	 */
554
+	public function start_date($dt_frmt = '')
555
+	{
556
+		return $this->_show_datetime('D', 'start', $dt_frmt);
557
+	}
558
+
559
+
560
+	/**
561
+	 * Echoes start_date()
562
+	 *
563
+	 * @param string $dt_frmt
564
+	 * @throws ReflectionException
565
+	 * @throws InvalidArgumentException
566
+	 * @throws InvalidInterfaceException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws EE_Error
569
+	 */
570
+	public function e_start_date($dt_frmt = '')
571
+	{
572
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
+	}
574
+
575
+
576
+	/**
577
+	 * get end date. Provide either the date format, or NULL to re-use the
578
+	 * last-used format, or '' to use the default date format
579
+	 *
580
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
+	 * @return mixed            string on success, FALSE on fail
582
+	 * @throws ReflectionException
583
+	 * @throws InvalidArgumentException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 */
588
+	public function end_date($dt_frmt = '')
589
+	{
590
+		return $this->_show_datetime('D', 'end', $dt_frmt);
591
+	}
592
+
593
+
594
+	/**
595
+	 * Echoes the end date. See end_date()
596
+	 *
597
+	 * @param string $dt_frmt
598
+	 * @throws ReflectionException
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws InvalidDataTypeException
602
+	 * @throws EE_Error
603
+	 */
604
+	public function e_end_date($dt_frmt = '')
605
+	{
606
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
+	}
608
+
609
+
610
+	/**
611
+	 * get date_range - meaning the start AND end date
612
+	 *
613
+	 * @access public
614
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
615
+	 * @param string $conjunction conjunction junction what's your function ?
616
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
+	 * @return mixed              string on success, FALSE on fail
618
+	 * @throws ReflectionException
619
+	 * @throws InvalidArgumentException
620
+	 * @throws InvalidInterfaceException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws EE_Error
623
+	 */
624
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
625
+	{
626
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
+		$start = str_replace(
628
+			' ',
629
+			'&nbsp;',
630
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
+		);
632
+		$end = str_replace(
633
+			' ',
634
+			'&nbsp;',
635
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
+		);
637
+		return $start !== $end ? $start . $conjunction . $end : $start;
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param string $dt_frmt
643
+	 * @param string $conjunction
644
+	 * @throws ReflectionException
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
+	{
652
+		echo esc_html($this->date_range($dt_frmt, $conjunction));
653
+	}
654
+
655
+
656
+	/**
657
+	 * get start time
658
+	 *
659
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
+	 * @return mixed        string on success, FALSE on fail
661
+	 * @throws ReflectionException
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 */
667
+	public function start_time($tm_format = '')
668
+	{
669
+		return $this->_show_datetime('T', 'start', null, $tm_format);
670
+	}
671
+
672
+
673
+	/**
674
+	 * @param string $tm_format
675
+	 * @throws ReflectionException
676
+	 * @throws InvalidArgumentException
677
+	 * @throws InvalidInterfaceException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws EE_Error
680
+	 */
681
+	public function e_start_time($tm_format = '')
682
+	{
683
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
684
+	}
685
+
686
+
687
+	/**
688
+	 * get end time
689
+	 *
690
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
691
+	 * @return mixed                string on success, FALSE on fail
692
+	 * @throws ReflectionException
693
+	 * @throws InvalidArgumentException
694
+	 * @throws InvalidInterfaceException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws EE_Error
697
+	 */
698
+	public function end_time($tm_format = '')
699
+	{
700
+		return $this->_show_datetime('T', 'end', null, $tm_format);
701
+	}
702
+
703
+
704
+	/**
705
+	 * @param string $tm_format
706
+	 * @throws ReflectionException
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidInterfaceException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws EE_Error
711
+	 */
712
+	public function e_end_time($tm_format = '')
713
+	{
714
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
715
+	}
716
+
717
+
718
+	/**
719
+	 * get time_range
720
+	 *
721
+	 * @access public
722
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
+	 * @param string $conjunction conjunction junction what's your function ?
724
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
+	 * @return mixed              string on success, FALSE on fail
726
+	 * @throws ReflectionException
727
+	 * @throws InvalidArgumentException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws InvalidDataTypeException
730
+	 * @throws EE_Error
731
+	 */
732
+	public function time_range($tm_format = '', $conjunction = ' - ')
733
+	{
734
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
+		$start = str_replace(
736
+			' ',
737
+			'&nbsp;',
738
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
+		);
740
+		$end = str_replace(
741
+			' ',
742
+			'&nbsp;',
743
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
+		);
745
+		return $start !== $end ? $start . $conjunction . $end : $start;
746
+	}
747
+
748
+
749
+	/**
750
+	 * @param string $tm_format
751
+	 * @param string $conjunction
752
+	 * @throws ReflectionException
753
+	 * @throws InvalidArgumentException
754
+	 * @throws InvalidInterfaceException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws EE_Error
757
+	 */
758
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
759
+	{
760
+		echo esc_html($this->time_range($tm_format, $conjunction));
761
+	}
762
+
763
+
764
+	/**
765
+	 * This returns a range representation of the date and times.
766
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
+	 * Also, the return value is localized.
768
+	 *
769
+	 * @param string $dt_format
770
+	 * @param string $tm_format
771
+	 * @param string $conjunction used between two different dates or times.
772
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
+	 * @param string $separator   used between the date and time formats.
774
+	 *                            ex: Dec 1, 2016{$separator}2pm
775
+	 * @return string
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	public function date_and_time_range(
783
+		$dt_format = '',
784
+		$tm_format = '',
785
+		$conjunction = ' - ',
786
+		$separator = ' '
787
+	) {
788
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
+		$full_format = $dt_format . $separator . $tm_format;
791
+		// the range output depends on various conditions
792
+		switch (true) {
793
+			// start date timestamp and end date timestamp are the same.
794
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
+				break;
797
+			// start and end date are the same but times are different
798
+			case ($this->start_date() === $this->end_date()):
799
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
+						  . $conjunction
801
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
+				break;
803
+			// all other conditions
804
+			default:
805
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
+						  . $conjunction
807
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
+				break;
809
+		}
810
+		return $output;
811
+	}
812
+
813
+
814
+	/**
815
+	 * This echos the results of date and time range.
816
+	 *
817
+	 * @see date_and_time_range() for more details on purpose.
818
+	 * @param string $dt_format
819
+	 * @param string $tm_format
820
+	 * @param string $conjunction
821
+	 * @return void
822
+	 * @throws ReflectionException
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidInterfaceException
825
+	 * @throws InvalidDataTypeException
826
+	 * @throws EE_Error
827
+	 */
828
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
+	{
830
+		echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
+	}
832
+
833
+
834
+	/**
835
+	 * get start date and start time
836
+	 *
837
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
+	 * @return    mixed    string on success, FALSE on fail
840
+	 * @throws ReflectionException
841
+	 * @throws InvalidArgumentException
842
+	 * @throws InvalidInterfaceException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws EE_Error
845
+	 */
846
+	public function start_date_and_time($dt_format = '', $tm_format = '')
847
+	{
848
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
+	}
850
+
851
+
852
+	/**
853
+	 * @param string $dt_frmt
854
+	 * @param string $tm_format
855
+	 * @throws ReflectionException
856
+	 * @throws InvalidArgumentException
857
+	 * @throws InvalidInterfaceException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws EE_Error
860
+	 */
861
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
+	{
863
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
+	}
865
+
866
+
867
+	/**
868
+	 * Shows the length of the event (start to end time).
869
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
870
+	 * By default, rounds up. (So if you use 'days', and then event
871
+	 * only occurs for 1 hour, it will return 1 day).
872
+	 *
873
+	 * @param string $units 'seconds','minutes','hours','days'
874
+	 * @param bool   $round_up
875
+	 * @return float|int|mixed
876
+	 * @throws ReflectionException
877
+	 * @throws InvalidArgumentException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws EE_Error
881
+	 */
882
+	public function length($units = 'seconds', $round_up = false)
883
+	{
884
+		$start = $this->get_raw('DTT_EVT_start');
885
+		$end = $this->get_raw('DTT_EVT_end');
886
+		$length_in_units = $end - $start;
887
+		switch ($units) {
888
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
889
+			/** @noinspection PhpMissingBreakStatementInspection */
890
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
+			case 'days':
892
+				$length_in_units /= 24;
893
+			/** @noinspection PhpMissingBreakStatementInspection */
894
+			case 'hours':
895
+				// fall through is intentional
896
+				$length_in_units /= 60;
897
+			/** @noinspection PhpMissingBreakStatementInspection */
898
+			case 'minutes':
899
+				// fall through is intentional
900
+				$length_in_units /= 60;
901
+			case 'seconds':
902
+			default:
903
+				$length_in_units = ceil($length_in_units);
904
+		}
905
+		// phpcs:enable
906
+		if ($round_up) {
907
+			$length_in_units = max($length_in_units, 1);
908
+		}
909
+		return $length_in_units;
910
+	}
911
+
912
+
913
+	/**
914
+	 *        get end date and time
915
+	 *
916
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
+	 * @return    mixed                string on success, FALSE on fail
919
+	 * @throws ReflectionException
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidInterfaceException
922
+	 * @throws InvalidDataTypeException
923
+	 * @throws EE_Error
924
+	 */
925
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
+	{
927
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
+	}
929
+
930
+
931
+	/**
932
+	 * @param string $dt_frmt
933
+	 * @param string $tm_format
934
+	 * @throws ReflectionException
935
+	 * @throws InvalidArgumentException
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws EE_Error
939
+	 */
940
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
+	{
942
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
+	}
944
+
945
+
946
+	/**
947
+	 *        get start timestamp
948
+	 *
949
+	 * @return        int
950
+	 * @throws ReflectionException
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidInterfaceException
953
+	 * @throws InvalidDataTypeException
954
+	 * @throws EE_Error
955
+	 */
956
+	public function start()
957
+	{
958
+		return $this->get_raw('DTT_EVT_start');
959
+	}
960
+
961
+
962
+	/**
963
+	 *        get end timestamp
964
+	 *
965
+	 * @return        int
966
+	 * @throws ReflectionException
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidInterfaceException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws EE_Error
971
+	 */
972
+	public function end()
973
+	{
974
+		return $this->get_raw('DTT_EVT_end');
975
+	}
976
+
977
+
978
+	/**
979
+	 *    get the registration limit for this datetime slot
980
+	 *
981
+	 * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
+	 * @throws ReflectionException
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidInterfaceException
985
+	 * @throws InvalidDataTypeException
986
+	 * @throws EE_Error
987
+	 */
988
+	public function reg_limit()
989
+	{
990
+		return $this->get_raw('DTT_reg_limit');
991
+	}
992
+
993
+
994
+	/**
995
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
+	 *
997
+	 * @return boolean
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 */
1004
+	public function sold_out()
1005
+	{
1006
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
+	}
1008
+
1009
+
1010
+	/**
1011
+	 * return the total number of spaces remaining at this venue.
1012
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
+	 *
1014
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1016
+	 *                               then this datetime IS effectively sold out.
1017
+	 *                               However, there are cases where we just want to know the spaces
1018
+	 *                               remaining for this particular datetime, hence the flag.
1019
+	 * @return int|float
1020
+	 * @throws ReflectionException
1021
+	 * @throws InvalidArgumentException
1022
+	 * @throws InvalidInterfaceException
1023
+	 * @throws InvalidDataTypeException
1024
+	 * @throws EE_Error
1025
+	 */
1026
+	public function spaces_remaining($consider_tickets = false)
1027
+	{
1028
+		// tickets remaining available for purchase
1029
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
+		if (! $consider_tickets) {
1032
+			return $dtt_remaining;
1033
+		}
1034
+		$tickets_remaining = $this->tickets_remaining();
1035
+		return min($dtt_remaining, $tickets_remaining);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Counts the total tickets available
1041
+	 * (from all the different types of tickets which are available for this datetime).
1042
+	 *
1043
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
+	 * @return int
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws EE_Error
1050
+	 */
1051
+	public function tickets_remaining($query_params = array())
1052
+	{
1053
+		$sum = 0;
1054
+		$tickets = $this->tickets($query_params);
1055
+		if (! empty($tickets)) {
1056
+			foreach ($tickets as $ticket) {
1057
+				if ($ticket instanceof EE_Ticket) {
1058
+					// get the actual amount of tickets that can be sold
1059
+					$qty = $ticket->qty('saleable');
1060
+					if ($qty === EE_INF) {
1061
+						return EE_INF;
1062
+					}
1063
+					// no negative ticket quantities plz
1064
+					if ($qty > 0) {
1065
+						$sum += $qty;
1066
+					}
1067
+				}
1068
+			}
1069
+		}
1070
+		return $sum;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1076
+	 * before any were sold
1077
+	 *
1078
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
+	 * @return int
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function sum_tickets_initially_available($query_params = array())
1087
+	{
1088
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
+	 * that is available for this datetime).
1096
+	 *
1097
+	 * @return int
1098
+	 * @throws ReflectionException
1099
+	 * @throws InvalidArgumentException
1100
+	 * @throws InvalidInterfaceException
1101
+	 * @throws InvalidDataTypeException
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function total_tickets_available_at_this_datetime()
1105
+	{
1106
+		return $this->spaces_remaining(true);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * This simply compares the internal dtt for the given string with NOW
1112
+	 * and determines if the date is upcoming or not.
1113
+	 *
1114
+	 * @access public
1115
+	 * @return boolean
1116
+	 * @throws ReflectionException
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidInterfaceException
1119
+	 * @throws InvalidDataTypeException
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function is_upcoming()
1123
+	{
1124
+		return ($this->get_raw('DTT_EVT_start') > time());
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * This simply compares the internal datetime for the given string with NOW
1130
+	 * and returns if the date is active (i.e. start and end time)
1131
+	 *
1132
+	 * @return boolean
1133
+	 * @throws ReflectionException
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws InvalidInterfaceException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function is_active()
1140
+	{
1141
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * This simply compares the internal dtt for the given string with NOW
1147
+	 * and determines if the date is expired or not.
1148
+	 *
1149
+	 * @return boolean
1150
+	 * @throws ReflectionException
1151
+	 * @throws InvalidArgumentException
1152
+	 * @throws InvalidInterfaceException
1153
+	 * @throws InvalidDataTypeException
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function is_expired()
1157
+	{
1158
+		return ($this->get_raw('DTT_EVT_end') < time());
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * This returns the active status for whether an event is active, upcoming, or expired
1164
+	 *
1165
+	 * @return int return value will be one of the EE_Datetime status constants.
1166
+	 * @throws ReflectionException
1167
+	 * @throws InvalidArgumentException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws InvalidDataTypeException
1170
+	 * @throws EE_Error
1171
+	 */
1172
+	public function get_active_status()
1173
+	{
1174
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
+			return EE_Datetime::sold_out;
1177
+		}
1178
+		if ($this->is_expired()) {
1179
+			return EE_Datetime::expired;
1180
+		}
1181
+		if ($this->is_upcoming()) {
1182
+			return EE_Datetime::upcoming;
1183
+		}
1184
+		if ($this->is_active()) {
1185
+			return EE_Datetime::active;
1186
+		}
1187
+		return null;
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
+	 *
1194
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
+	 * @return string
1196
+	 * @throws ReflectionException
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function get_dtt_display_name($use_dtt_name = false)
1203
+	{
1204
+		if ($use_dtt_name) {
1205
+			$dtt_name = $this->name();
1206
+			if (! empty($dtt_name)) {
1207
+				return $dtt_name;
1208
+			}
1209
+		}
1210
+		// first condition is to see if the months are different
1211
+		if (
1212
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
+		) {
1214
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+			// next condition is if its the same month but different day
1216
+		} else {
1217
+			if (
1218
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
+			) {
1221
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+			} else {
1223
+				$display_date = $this->start_date('F j\, Y')
1224
+								. ' @ '
1225
+								. $this->start_date('g:i a')
1226
+								. ' - '
1227
+								. $this->end_date('g:i a');
1228
+			}
1229
+		}
1230
+		return $display_date;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 * Gets all the tickets for this datetime
1236
+	 *
1237
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
+	 * @return EE_Base_Class[]|EE_Ticket[]
1239
+	 * @throws ReflectionException
1240
+	 * @throws InvalidArgumentException
1241
+	 * @throws InvalidInterfaceException
1242
+	 * @throws InvalidDataTypeException
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function tickets($query_params = array())
1246
+	{
1247
+		return $this->get_many_related('Ticket', $query_params);
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * Gets all the ticket types currently available for purchase
1253
+	 *
1254
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
+	 * @return EE_Ticket[]
1256
+	 * @throws ReflectionException
1257
+	 * @throws InvalidArgumentException
1258
+	 * @throws InvalidInterfaceException
1259
+	 * @throws InvalidDataTypeException
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function ticket_types_available_for_purchase($query_params = array())
1263
+	{
1264
+		// first check if datetime is valid
1265
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
+			return array();
1267
+		}
1268
+		if (empty($query_params)) {
1269
+			$query_params = array(
1270
+				array(
1271
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
+					'TKT_deleted'    => false,
1274
+				),
1275
+			);
1276
+		}
1277
+		return $this->tickets($query_params);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * @return EE_Base_Class|EE_Event
1283
+	 * @throws ReflectionException
1284
+	 * @throws InvalidArgumentException
1285
+	 * @throws InvalidInterfaceException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws EE_Error
1288
+	 */
1289
+	public function event()
1290
+	{
1291
+		return $this->get_first_related('Event');
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
+	 * (via the tickets).
1298
+	 *
1299
+	 * @return int
1300
+	 * @throws ReflectionException
1301
+	 * @throws InvalidArgumentException
1302
+	 * @throws InvalidInterfaceException
1303
+	 * @throws InvalidDataTypeException
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function update_sold()
1307
+	{
1308
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
+			array(
1310
+				array(
1311
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1312
+					'REG_deleted'            => 0,
1313
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
+				),
1315
+			)
1316
+		);
1317
+		$this->set_sold($count_regs_for_this_datetime);
1318
+		$this->save();
1319
+		return $count_regs_for_this_datetime;
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Adds a venue to this event
1325
+	 *
1326
+	 * @param int|EE_Venue /int $venue_id_or_obj
1327
+	 * @return EE_Base_Class|EE_Venue
1328
+	 * @throws EE_Error
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function add_venue($venue_id_or_obj): EE_Venue
1332
+	{
1333
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Removes a venue from the event
1339
+	 *
1340
+	 * @param EE_Venue /int $venue_id_or_obj
1341
+	 * @return EE_Base_Class|EE_Venue
1342
+	 * @throws EE_Error
1343
+	 * @throws ReflectionException
1344
+	 */
1345
+	public function remove_venue($venue_id_or_obj): EE_Venue
1346
+	{
1347
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1354
+	 *
1355
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
+	 * @return int
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function venue_ID(array $query_params = []): int
1361
+	{
1362
+		$venue = $this->get_first_related('Venue', $query_params);
1363
+		return $venue instanceof EE_Venue
1364
+			? $venue->ID()
1365
+			: 0;
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1371
+	 *
1372
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
+	 * @return EE_Base_Class|EE_Venue
1374
+	 * @throws EE_Error
1375
+	 * @throws ReflectionException
1376
+	 */
1377
+	public function venue(array $query_params = [])
1378
+	{
1379
+		return $this->get_first_related('Venue', $query_params);
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
+	 * @param string                   $relationName
1386
+	 * @param array                    $extra_join_model_fields_n_values
1387
+	 * @param string|null              $cache_id
1388
+	 * @return EE_Base_Class
1389
+	 * @throws EE_Error
1390
+	 * @throws ReflectionException
1391
+	 * @since   $VID:$
1392
+	 */
1393
+	public function _add_relation_to(
1394
+		$otherObjectModelObjectOrID,
1395
+		$relationName,
1396
+		$extra_join_model_fields_n_values = [],
1397
+		$cache_id = null
1398
+	) {
1399
+		// if we're adding a new relation to a ticket
1400
+		if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
+			/** @var EE_Ticket $ticket */
1402
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
+			$this->increaseSold($ticket->sold(), false);
1404
+			$this->increaseReserved($ticket->reserved());
1405
+			$this->save();
1406
+			$otherObjectModelObjectOrID = $ticket;
1407
+		}
1408
+		return parent::_add_relation_to(
1409
+			$otherObjectModelObjectOrID,
1410
+			$relationName,
1411
+			$extra_join_model_fields_n_values,
1412
+			$cache_id
1413
+		);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
+	 * @param string                   $relationName
1420
+	 * @param array                    $where_query
1421
+	 * @return bool|EE_Base_Class|null
1422
+	 * @throws EE_Error
1423
+	 * @throws ReflectionException
1424
+	 * @since   $VID:$
1425
+	 */
1426
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
+	{
1428
+		if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
+			/** @var EE_Ticket $ticket */
1430
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
+			$this->decreaseSold($ticket->sold());
1432
+			$this->decreaseReserved($ticket->reserved());
1433
+			$this->save();
1434
+			$otherObjectModelObjectOrID = $ticket;
1435
+		}
1436
+		return parent::_remove_relation_to(
1437
+			$otherObjectModelObjectOrID,
1438
+			$relationName,
1439
+			$where_query
1440
+		);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Removes ALL the related things for the $relationName.
1446
+	 *
1447
+	 * @param string $relationName
1448
+	 * @param array  $where_query_params
1449
+	 * @return EE_Base_Class
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
+	 */
1457
+	public function _remove_relations($relationName, $where_query_params = [])
1458
+	{
1459
+		if ($relationName === 'Ticket') {
1460
+			$tickets = $this->tickets();
1461
+			foreach ($tickets as $ticket) {
1462
+				$this->decreaseSold($ticket->sold());
1463
+				$this->decreaseReserved($ticket->reserved());
1464
+				$this->save();
1465
+			}
1466
+		}
1467
+		return parent::_remove_relations($relationName, $where_query_params);
1468
+	}
1469
+
1470
+
1471
+	/*******************************************************************
1472 1472
      ***********************  DEPRECATED METHODS  **********************
1473 1473
      *******************************************************************/
1474 1474
 
1475 1475
 
1476
-    /**
1477
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
-     *
1479
-     * @deprecated 4.9.80.p
1480
-     * @param int $qty
1481
-     * @return boolean
1482
-     * @throws ReflectionException
1483
-     * @throws InvalidArgumentException
1484
-     * @throws InvalidInterfaceException
1485
-     * @throws InvalidDataTypeException
1486
-     * @throws EE_Error
1487
-     */
1488
-    public function increase_sold($qty = 1)
1489
-    {
1490
-        EE_Error::doing_it_wrong(
1491
-            __FUNCTION__,
1492
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
-            '4.9.80.p',
1494
-            '5.0.0.p'
1495
-        );
1496
-        return $this->increaseSold($qty);
1497
-    }
1498
-
1499
-
1500
-    /**
1501
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
-     * to save afterwards.)
1503
-     *
1504
-     * @deprecated 4.9.80.p
1505
-     * @param int $qty
1506
-     * @return boolean
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    public function decrease_sold($qty = 1)
1514
-    {
1515
-        EE_Error::doing_it_wrong(
1516
-            __FUNCTION__,
1517
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
-            '4.9.80.p',
1519
-            '5.0.0.p'
1520
-        );
1521
-        return $this->decreaseSold($qty);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
-     *
1528
-     * @deprecated 4.9.80.p
1529
-     * @param int $qty
1530
-     * @return boolean indicating success
1531
-     * @throws ReflectionException
1532
-     * @throws InvalidArgumentException
1533
-     * @throws InvalidInterfaceException
1534
-     * @throws InvalidDataTypeException
1535
-     * @throws EE_Error
1536
-     */
1537
-    public function increase_reserved($qty = 1)
1538
-    {
1539
-        EE_Error::doing_it_wrong(
1540
-            __FUNCTION__,
1541
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
-            '4.9.80.p',
1543
-            '5.0.0.p'
1544
-        );
1545
-        return $this->increaseReserved($qty);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
-     *
1552
-     * @deprecated 4.9.80.p
1553
-     * @param int $qty
1554
-     * @return boolean
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    public function decrease_reserved($qty = 1)
1562
-    {
1563
-        EE_Error::doing_it_wrong(
1564
-            __FUNCTION__,
1565
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
-            '4.9.80.p',
1567
-            '5.0.0.p'
1568
-        );
1569
-        return $this->decreaseReserved($qty);
1570
-    }
1476
+	/**
1477
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
+	 *
1479
+	 * @deprecated 4.9.80.p
1480
+	 * @param int $qty
1481
+	 * @return boolean
1482
+	 * @throws ReflectionException
1483
+	 * @throws InvalidArgumentException
1484
+	 * @throws InvalidInterfaceException
1485
+	 * @throws InvalidDataTypeException
1486
+	 * @throws EE_Error
1487
+	 */
1488
+	public function increase_sold($qty = 1)
1489
+	{
1490
+		EE_Error::doing_it_wrong(
1491
+			__FUNCTION__,
1492
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
+			'4.9.80.p',
1494
+			'5.0.0.p'
1495
+		);
1496
+		return $this->increaseSold($qty);
1497
+	}
1498
+
1499
+
1500
+	/**
1501
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
+	 * to save afterwards.)
1503
+	 *
1504
+	 * @deprecated 4.9.80.p
1505
+	 * @param int $qty
1506
+	 * @return boolean
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	public function decrease_sold($qty = 1)
1514
+	{
1515
+		EE_Error::doing_it_wrong(
1516
+			__FUNCTION__,
1517
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
+			'4.9.80.p',
1519
+			'5.0.0.p'
1520
+		);
1521
+		return $this->decreaseSold($qty);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
+	 *
1528
+	 * @deprecated 4.9.80.p
1529
+	 * @param int $qty
1530
+	 * @return boolean indicating success
1531
+	 * @throws ReflectionException
1532
+	 * @throws InvalidArgumentException
1533
+	 * @throws InvalidInterfaceException
1534
+	 * @throws InvalidDataTypeException
1535
+	 * @throws EE_Error
1536
+	 */
1537
+	public function increase_reserved($qty = 1)
1538
+	{
1539
+		EE_Error::doing_it_wrong(
1540
+			__FUNCTION__,
1541
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
+			'4.9.80.p',
1543
+			'5.0.0.p'
1544
+		);
1545
+		return $this->increaseReserved($qty);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
+	 *
1552
+	 * @deprecated 4.9.80.p
1553
+	 * @param int $qty
1554
+	 * @return boolean
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	public function decrease_reserved($qty = 1)
1562
+	{
1563
+		EE_Error::doing_it_wrong(
1564
+			__FUNCTION__,
1565
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
+			'4.9.80.p',
1567
+			'5.0.0.p'
1568
+		);
1569
+		return $this->decreaseReserved($qty);
1570
+	}
1571 1571
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6553 added lines, -6553 removed lines patch added patch discarded remove patch
@@ -37,6561 +37,6561 @@
 block discarded – undo
37 37
  */
38 38
 abstract class EEM_Base extends EE_Base implements ResettableInterface
39 39
 {
40
-    /**
41
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
-     * They almost always WILL NOT, but it's not necessarily a requirement.
44
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
-     *
46
-     * @var boolean
47
-     */
48
-    private $_values_already_prepared_by_model_object = 0;
49
-
50
-    /**
51
-     * when $_values_already_prepared_by_model_object equals this, we assume
52
-     * the data is just like form input that needs to have the model fields'
53
-     * prepare_for_set and prepare_for_use_in_db called on it
54
-     */
55
-    const not_prepared_by_model_object = 0;
56
-
57
-    /**
58
-     * when $_values_already_prepared_by_model_object equals this, we
59
-     * assume this value is coming from a model object and doesn't need to have
60
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
61
-     */
62
-    const prepared_by_model_object = 1;
63
-
64
-    /**
65
-     * when $_values_already_prepared_by_model_object equals this, we assume
66
-     * the values are already to be used in the database (ie no processing is done
67
-     * on them by the model's fields)
68
-     */
69
-    const prepared_for_use_in_db = 2;
70
-
71
-
72
-    protected $singular_item = 'Item';
73
-
74
-    protected $plural_item   = 'Items';
75
-
76
-    /**
77
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
-     */
79
-    protected $_tables;
80
-
81
-    /**
82
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
-     *
86
-     * @var EE_Model_Field_Base[][] $_fields
87
-     */
88
-    protected $_fields;
89
-
90
-    /**
91
-     * array of different kinds of relations
92
-     *
93
-     * @var EE_Model_Relation_Base[] $_model_relations
94
-     */
95
-    protected $_model_relations = [];
96
-
97
-    /**
98
-     * @var EE_Index[] $_indexes
99
-     */
100
-    protected $_indexes = [];
101
-
102
-    /**
103
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
104
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
-     * by setting the same columns as used in these queries in the query yourself.
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_default_where_conditions_strategy;
110
-
111
-    /**
112
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
-     * This is particularly useful when you want something between 'none' and 'default'
114
-     *
115
-     * @var EE_Default_Where_Conditions
116
-     */
117
-    protected $_minimum_where_conditions_strategy;
118
-
119
-    /**
120
-     * String describing how to find the "owner" of this model's objects.
121
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
-     * But when there isn't, this indicates which related model, or transiently-related model,
123
-     * has the foreign key to the wp_users table.
124
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
-     * related to events, and events have a foreign key to wp_users.
126
-     * On EEM_Transaction, this would be 'Transaction.Event'
127
-     *
128
-     * @var string
129
-     */
130
-    protected $_model_chain_to_wp_user = '';
131
-
132
-    /**
133
-     * String describing how to find the model with a password controlling access to this model. This property has the
134
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
-     * This value is the path of models to follow to arrive at the model with the password field.
136
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
-     * model with a password that should affect reading this on the front-end.
138
-     * Eg this is an empty string for the Event model because it has a password.
139
-     * This is null for the Registration model, because its event's password has no bearing on whether
140
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
-     * should hide tickets for datetimes for events that have a password set.
143
-     *
144
-     * @var string |null
145
-     */
146
-    protected $model_chain_to_password = null;
147
-
148
-    /**
149
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
-     * don't need it (particularly CPT models)
151
-     *
152
-     * @var bool
153
-     */
154
-    protected $_ignore_where_strategy = false;
155
-
156
-    /**
157
-     * String used in caps relating to this model. Eg, if the caps relating to this
158
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
-     *
160
-     * @var string. If null it hasn't been initialized yet. If false then we
161
-     * have indicated capabilities don't apply to this
162
-     */
163
-    protected $_caps_slug = null;
164
-
165
-    /**
166
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
-     * and next-level keys are capability names, and each's value is a
168
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
-     * they specify which context to use (ie, frontend, backend, edit or delete)
170
-     * and then each capability in the corresponding sub-array that they're missing
171
-     * adds the where conditions onto the query.
172
-     *
173
-     * @var array
174
-     */
175
-    protected $_cap_restrictions = [
176
-        self::caps_read       => [],
177
-        self::caps_read_admin => [],
178
-        self::caps_edit       => [],
179
-        self::caps_delete     => [],
180
-    ];
181
-
182
-    /**
183
-     * Array defining which cap restriction generators to use to create default
184
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
185
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
-     * automatically set this to false (not just null).
188
-     *
189
-     * @var EE_Restriction_Generator_Base[]
190
-     */
191
-    protected $_cap_restriction_generators = [];
192
-
193
-    /**
194
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
-     */
196
-    const caps_read       = 'read';
197
-
198
-    const caps_read_admin = 'read_admin';
199
-
200
-    const caps_edit       = 'edit';
201
-
202
-    const caps_delete     = 'delete';
203
-
204
-    /**
205
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
-     * maps to 'read' because when looking for relevant permissions we're going to use
208
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
209
-     *
210
-     * @var array
211
-     */
212
-    protected $_cap_contexts_to_cap_action_map = [
213
-        self::caps_read       => 'read',
214
-        self::caps_read_admin => 'read',
215
-        self::caps_edit       => 'edit',
216
-        self::caps_delete     => 'delete',
217
-    ];
218
-
219
-    /**
220
-     * Timezone
221
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
-     * EE_Datetime_Field data type will have access to it.
225
-     *
226
-     * @var string
227
-     */
228
-    protected $_timezone;
229
-
230
-
231
-    /**
232
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
-     * multisite.
234
-     *
235
-     * @var int
236
-     */
237
-    protected static $_model_query_blog_id;
238
-
239
-    /**
240
-     * A copy of _fields, except the array keys are the model names pointed to by
241
-     * the field
242
-     *
243
-     * @var EE_Model_Field_Base[]
244
-     */
245
-    private $_cache_foreign_key_to_fields = [];
246
-
247
-    /**
248
-     * Cached list of all the fields on the model, indexed by their name
249
-     *
250
-     * @var EE_Model_Field_Base[]
251
-     */
252
-    private $_cached_fields = null;
253
-
254
-    /**
255
-     * Cached list of all the fields on the model, except those that are
256
-     * marked as only pertinent to the database
257
-     *
258
-     * @var EE_Model_Field_Base[]
259
-     */
260
-    private $_cached_fields_non_db_only = null;
261
-
262
-    /**
263
-     * A cached reference to the primary key for quick lookup
264
-     *
265
-     * @var EE_Model_Field_Base
266
-     */
267
-    private $_primary_key_field = null;
268
-
269
-    /**
270
-     * Flag indicating whether this model has a primary key or not
271
-     *
272
-     * @var boolean
273
-     */
274
-    protected $_has_primary_key_field = null;
275
-
276
-    /**
277
-     * array in the format:  [ FK alias => full PK ]
278
-     * where keys are local column name aliases for foreign keys
279
-     * and values are the fully qualified column name for the primary key they represent
280
-     *  ex:
281
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
-     *
283
-     * @var array $foreign_key_aliases
284
-     */
285
-    protected $foreign_key_aliases = [];
286
-
287
-    /**
288
-     * Whether or not this model is based off a table in WP core only (CPTs should set
289
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
-     * This should be true for models that deal with data that should exist independent of EE.
291
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
293
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
295
-     *
296
-     * @var boolean
297
-     */
298
-    protected $_wp_core_model = false;
299
-
300
-    /**
301
-     * @var bool stores whether this model has a password field or not.
302
-     * null until initialized by hasPasswordField()
303
-     */
304
-    protected $has_password_field;
305
-
306
-    /**
307
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
-     */
309
-    protected $password_field;
310
-
311
-    /**
312
-     *    List of valid operators that can be used for querying.
313
-     * The keys are all operators we'll accept, the values are the real SQL
314
-     * operators used
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_valid_operators = [
319
-        '='           => '=',
320
-        '<='          => '<=',
321
-        '<'           => '<',
322
-        '>='          => '>=',
323
-        '>'           => '>',
324
-        '!='          => '!=',
325
-        'LIKE'        => 'LIKE',
326
-        'like'        => 'LIKE',
327
-        'NOT_LIKE'    => 'NOT LIKE',
328
-        'not_like'    => 'NOT LIKE',
329
-        'NOT LIKE'    => 'NOT LIKE',
330
-        'not like'    => 'NOT LIKE',
331
-        'IN'          => 'IN',
332
-        'in'          => 'IN',
333
-        'NOT_IN'      => 'NOT IN',
334
-        'not_in'      => 'NOT IN',
335
-        'NOT IN'      => 'NOT IN',
336
-        'not in'      => 'NOT IN',
337
-        'between'     => 'BETWEEN',
338
-        'BETWEEN'     => 'BETWEEN',
339
-        'IS_NOT_NULL' => 'IS NOT NULL',
340
-        'is_not_null' => 'IS NOT NULL',
341
-        'IS NOT NULL' => 'IS NOT NULL',
342
-        'is not null' => 'IS NOT NULL',
343
-        'IS_NULL'     => 'IS NULL',
344
-        'is_null'     => 'IS NULL',
345
-        'IS NULL'     => 'IS NULL',
346
-        'is null'     => 'IS NULL',
347
-        'REGEXP'      => 'REGEXP',
348
-        'regexp'      => 'REGEXP',
349
-        'NOT_REGEXP'  => 'NOT REGEXP',
350
-        'not_regexp'  => 'NOT REGEXP',
351
-        'NOT REGEXP'  => 'NOT REGEXP',
352
-        'not regexp'  => 'NOT REGEXP',
353
-    ];
354
-
355
-    /**
356
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
-     *
358
-     * @var array
359
-     */
360
-    protected $_in_style_operators = ['IN', 'NOT IN'];
361
-
362
-    /**
363
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
-     * '12-31-2012'"
365
-     *
366
-     * @var array
367
-     */
368
-    protected $_between_style_operators = ['BETWEEN'];
369
-
370
-    /**
371
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
-     *
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
-
377
-    /**
378
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
-     * on a join table.
380
-     *
381
-     * @var array
382
-     */
383
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
-
385
-    /**
386
-     * Allowed values for $query_params['order'] for ordering in queries
387
-     *
388
-     * @var array
389
-     */
390
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
-
392
-    /**
393
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
395
-     *
396
-     * @var array
397
-     */
398
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
-
400
-    /**
401
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
403
-     *
404
-     * @var array
405
-     */
406
-    private $_allowed_query_params = [
407
-        0,
408
-        'limit',
409
-        'order_by',
410
-        'group_by',
411
-        'having',
412
-        'force_join',
413
-        'order',
414
-        'on_join_limit',
415
-        'default_where_conditions',
416
-        'caps',
417
-        'extra_selects',
418
-        'exclude_protected',
419
-    ];
420
-
421
-    /**
422
-     * All the data types that can be used in $wpdb->prepare statements.
423
-     *
424
-     * @var array
425
-     */
426
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
-
428
-    /**
429
-     * @var EE_Registry $EE
430
-     */
431
-    protected $EE = null;
432
-
433
-
434
-    /**
435
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
-     *
437
-     * @var int
438
-     */
439
-    protected $_show_next_x_db_queries = 0;
440
-
441
-    /**
442
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
-     * WHERE, GROUP_BY, etc.
445
-     *
446
-     * @var CustomSelects
447
-     */
448
-    protected $_custom_selections = [];
449
-
450
-    /**
451
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
-     * caches every model object we've fetched from the DB on this request
453
-     *
454
-     * @var array
455
-     */
456
-    protected $_entity_map;
457
-
458
-    /**
459
-     * @var LoaderInterface
460
-     */
461
-    protected static $loader;
462
-
463
-    /**
464
-     * @var Mirror
465
-     */
466
-    private static $mirror;
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-    /**
547
-     * About all child constructors:
548
-     * they should define the _tables, _fields and _model_relations arrays.
549
-     * Should ALWAYS be called after child constructor.
550
-     * In order to make the child constructors to be as simple as possible, this parent constructor
551
-     * finalizes constructing all the object's attributes.
552
-     * Generally, rather than requiring a child to code
553
-     * $this->_tables = array(
554
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
-     *        ...);
556
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
-     * each EE_Table has a function to set the table's alias after the constructor, using
558
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
-     * do something similar.
560
-     *
561
-     * @param null $timezone
562
-     * @throws EE_Error
563
-     */
564
-    protected function __construct($timezone = null)
565
-    {
566
-        // check that the model has not been loaded too soon
567
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
-            throw new EE_Error(
569
-                sprintf(
570
-                    esc_html__(
571
-                        '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.',
572
-                        'event_espresso'
573
-                    ),
574
-                    get_class($this)
575
-                )
576
-            );
577
-        }
578
-        /**
579
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
-         */
581
-        if (empty(EEM_Base::$_model_query_blog_id)) {
582
-            EEM_Base::set_model_query_blog_id();
583
-        }
584
-        /**
585
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
-         * just use EE_Register_Model_Extension
587
-         *
588
-         * @var EE_Table_Base[] $_tables
589
-         */
590
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
-        foreach ($this->_tables as $table_alias => $table_obj) {
592
-            /** @var $table_obj EE_Table_Base */
593
-            $table_obj->_construct_finalize_with_alias($table_alias);
594
-            if ($table_obj instanceof EE_Secondary_Table) {
595
-                /** @var $table_obj EE_Secondary_Table */
596
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
-            }
598
-        }
599
-        /**
600
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
-         * EE_Register_Model_Extension
602
-         *
603
-         * @param EE_Model_Field_Base[] $_fields
604
-         */
605
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
-        $this->_invalidate_field_caches();
607
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
608
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
-                throw new EE_Error(
610
-                    sprintf(
611
-                        esc_html__(
612
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
-                            'event_espresso'
614
-                        ),
615
-                        $table_alias,
616
-                        implode(",", $this->_fields)
617
-                    )
618
-                );
619
-            }
620
-            foreach ($fields_for_table as $field_name => $field_obj) {
621
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
-                // primary key field base has a slightly different _construct_finalize
623
-                /** @var $field_obj EE_Model_Field_Base */
624
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
-            }
626
-        }
627
-        // everything is related to Extra_Meta
628
-        if (get_class($this) !== 'EEM_Extra_Meta') {
629
-            // make extra meta related to everything, but don't block deleting things just
630
-            // because they have related extra meta info. For now just orphan those extra meta
631
-            // in the future we should automatically delete them
632
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
-        }
634
-        // and change logs
635
-        if (get_class($this) !== 'EEM_Change_Log') {
636
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
-        }
638
-        /**
639
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
-         * EE_Register_Model_Extension
641
-         *
642
-         * @param EE_Model_Relation_Base[] $_model_relations
643
-         */
644
-        $this->_model_relations = (array) apply_filters(
645
-            'FHEE__' . get_class($this) . '__construct__model_relations',
646
-            $this->_model_relations
647
-        );
648
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
649
-            /** @var $relation_obj EE_Model_Relation_Base */
650
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
-        }
652
-        foreach ($this->_indexes as $index_name => $index_obj) {
653
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
-        }
655
-        $this->set_timezone($timezone);
656
-        // finalize default where condition strategy, or set default
657
-        if (! $this->_default_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
662
-        if (! $this->_minimum_where_conditions_strategy) {
663
-            // nothing was set during child constructor, so set default
664
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
-        }
666
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
668
-        // to indicate to NOT set it, set it to the logical default
669
-        if ($this->_caps_slug === null) {
670
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
-        }
672
-        // initialize the standard cap restriction generators if none were specified by the child constructor
673
-        if (is_array($this->_cap_restriction_generators)) {
674
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
-                        new EE_Restriction_Generator_Protected(),
679
-                        $cap_context,
680
-                        $this
681
-                    );
682
-                }
683
-            }
684
-        }
685
-        // if there are cap restriction generators, use them to make the default cap restrictions
686
-        if (is_array($this->_cap_restriction_generators)) {
687
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
-                if (! $generator_object) {
689
-                    continue;
690
-                }
691
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
-                    throw new EE_Error(
693
-                        sprintf(
694
-                            esc_html__(
695
-                                '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.',
696
-                                'event_espresso'
697
-                            ),
698
-                            $context,
699
-                            $this->get_this_model_name()
700
-                        )
701
-                    );
702
-                }
703
-                $action = $this->cap_action_for_context($context);
704
-                if (! $generator_object->construction_finalized()) {
705
-                    $generator_object->_construct_finalize($this, $action);
706
-                }
707
-            }
708
-        }
709
-        do_action('AHEE__' . get_class($this) . '__construct__end');
710
-    }
711
-
712
-
713
-    /**
714
-     * @return LoaderInterface
715
-     * @throws InvalidArgumentException
716
-     * @throws InvalidDataTypeException
717
-     * @throws InvalidInterfaceException
718
-     */
719
-    protected static function getLoader(): LoaderInterface
720
-    {
721
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
722
-            EEM_Base::$loader = LoaderFactory::getLoader();
723
-        }
724
-        return EEM_Base::$loader;
725
-    }
726
-
727
-
728
-    /**
729
-     * @return Mirror
730
-     * @since   $VID:$
731
-     */
732
-    private static function getMirror(): Mirror
733
-    {
734
-        if (! EEM_Base::$mirror instanceof Mirror) {
735
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
-        }
737
-        return EEM_Base::$mirror;
738
-    }
739
-
740
-
741
-    /**
742
-     * @param string $model_class_Name
743
-     * @param string $timezone
744
-     * @return array
745
-     * @throws ReflectionException
746
-     * @since   $VID:$
747
-     */
748
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
749
-    {
750
-        $arguments = [$timezone];
751
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
-        if (count($params) > 1) {
753
-            if ($params[1]->getName() === 'model_field_factory') {
754
-                $arguments = [
755
-                    $timezone,
756
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
-                    $timezone,
762
-                ];
763
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
764
-                $arguments = [
765
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
-                    $timezone,
768
-                ];
769
-            }
770
-        }
771
-        return $arguments;
772
-    }
773
-
774
-
775
-    /**
776
-     * This function is a singleton method used to instantiate the Espresso_model object
777
-     *
778
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
-     *                                (and any incoming timezone data that gets saved).
780
-     *                                Note this just sends the timezone info to the date time model field objects.
781
-     *                                Default is NULL
782
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
-     * @return static (as in the concrete child class)
784
-     * @throws EE_Error
785
-     * @throws ReflectionException
786
-     */
787
-    public static function instance($timezone = null)
788
-    {
789
-        // check if instance of Espresso_model already exists
790
-        if (! static::$_instance instanceof static) {
791
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
-            $model     = new static(...$arguments);
793
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
-            static::$_instance = $model;
795
-        }
796
-        // we might have a timezone set, let set_timezone decide what to do with it
797
-        if ($timezone) {
798
-            static::$_instance->set_timezone($timezone);
799
-        }
800
-        // Espresso_model object
801
-        return static::$_instance;
802
-    }
803
-
804
-
805
-    /**
806
-     * resets the model and returns it
807
-     *
808
-     * @param string|null $timezone
809
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
-     * all its properties reset; if it wasn't instantiated, returns null)
811
-     * @throws EE_Error
812
-     * @throws ReflectionException
813
-     * @throws InvalidArgumentException
814
-     * @throws InvalidDataTypeException
815
-     * @throws InvalidInterfaceException
816
-     */
817
-    public static function reset($timezone = null)
818
-    {
819
-        if (! static::$_instance instanceof EEM_Base) {
820
-            return null;
821
-        }
822
-        // Let's NOT swap out the current instance for a new one
823
-        // because if someone has a reference to it, we can't remove their reference.
824
-        // It's best to keep using the same reference but change the original object instead,
825
-        // so reset all its properties to their original values as defined in the class.
826
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
-            // don't set instance to null like it was originally,
829
-            // but it's static anyways, and we're ignoring static properties (for now at least)
830
-            if (! isset($static_properties[ $property ])) {
831
-                static::$_instance->{$property} = $value;
832
-            }
833
-        }
834
-        // and then directly call its constructor again, like we would if we were creating a new one
835
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
-        static::$_instance->__construct(...$arguments);
837
-        return self::instance();
838
-    }
839
-
840
-
841
-    /**
842
-     * Used to set the $_model_query_blog_id static property.
843
-     *
844
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
-     *                      value for get_current_blog_id() will be used.
846
-     */
847
-    public static function set_model_query_blog_id($blog_id = 0)
848
-    {
849
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
850
-            ? (int) $blog_id
851
-            : get_current_blog_id();
852
-    }
853
-
854
-
855
-    /**
856
-     * Returns whatever is set as the internal $model_query_blog_id.
857
-     *
858
-     * @return int
859
-     */
860
-    public static function get_model_query_blog_id()
861
-    {
862
-        return EEM_Base::$_model_query_blog_id;
863
-    }
864
-
865
-
866
-    /**
867
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
-     *
869
-     * @param boolean $translated return localized strings or JUST the array.
870
-     * @return array
871
-     * @throws EE_Error
872
-     * @throws InvalidArgumentException
873
-     * @throws InvalidDataTypeException
874
-     * @throws InvalidInterfaceException
875
-     */
876
-    public function status_array($translated = false)
877
-    {
878
-        if (! array_key_exists('Status', $this->_model_relations)) {
879
-            return [];
880
-        }
881
-        $model_name   = $this->get_this_model_name();
882
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
-        $status_array = [];
885
-        foreach ($stati as $status) {
886
-            $status_array[ $status->ID() ] = $status->get('STS_code');
887
-        }
888
-        return $translated
889
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
-            : $status_array;
891
-    }
892
-
893
-
894
-    /**
895
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
-     *
897
-     * @param array $query_params             @see
898
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
-     *                                        or if you have the development copy of EE you can view this at the path:
900
-     *                                        /docs/G--Model-System/model-query-params.md
901
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
-     *                                        EEM_Transaction::instance()->get_all( array( array(
906
-     *                                        'OR'=>array(
907
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
-     *                                        )
910
-     *                                        ),
911
-     *                                        'limit'=>10,
912
-     *                                        'group_by'=>'TXN_ID'
913
-     *                                        ));
914
-     *                                        get all the answers to the question titled "shirt size" for event with id
915
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
-     *                                        'Question.QST_display_text'=>'shirt size',
917
-     *                                        'Registration.Event.EVT_ID'=>12
918
-     *                                        ),
919
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
920
-     *                                        ));
921
-     * @throws EE_Error
922
-     */
923
-    public function get_all($query_params = [])
924
-    {
925
-        if (
926
-            isset($query_params['limit'])
927
-            && ! isset($query_params['group_by'])
928
-        ) {
929
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
930
-        }
931
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
932
-    }
933
-
934
-
935
-    /**
936
-     * Modifies the query parameters so we only get back model objects
937
-     * that "belong" to the current user
938
-     *
939
-     * @param array $query_params @see
940
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
941
-     * @return array @see
942
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
943
-     */
944
-    public function alter_query_params_to_only_include_mine($query_params = [])
945
-    {
946
-        $wp_user_field_name = $this->wp_user_field_name();
947
-        if ($wp_user_field_name) {
948
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
949
-        }
950
-        return $query_params;
951
-    }
952
-
953
-
954
-    /**
955
-     * Returns the name of the field's name that points to the WP_User table
956
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
957
-     * foreign key to the WP_User table)
958
-     *
959
-     * @return string|boolean string on success, boolean false when there is no
960
-     * foreign key to the WP_User table
961
-     */
962
-    public function wp_user_field_name()
963
-    {
964
-        try {
965
-            if (! empty($this->_model_chain_to_wp_user)) {
966
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
967
-                $last_model_name              = end($models_to_follow_to_wp_users);
968
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
969
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
970
-            } else {
971
-                $model_with_fk_to_wp_users = $this;
972
-                $model_chain_to_wp_user    = '';
973
-            }
974
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
975
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
976
-        } catch (EE_Error $e) {
977
-            return false;
978
-        }
979
-    }
980
-
981
-
982
-    /**
983
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
984
-     * (or transiently-related model) has a foreign key to the wp_users table;
985
-     * useful for finding if model objects of this type are 'owned' by the current user.
986
-     * This is an empty string when the foreign key is on this model and when it isn't,
987
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
988
-     * (or transiently-related model)
989
-     *
990
-     * @return string
991
-     */
992
-    public function model_chain_to_wp_user()
993
-    {
994
-        return $this->_model_chain_to_wp_user;
995
-    }
996
-
997
-
998
-    /**
999
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1000
-     * like how registrations don't have a foreign key to wp_users, but the
1001
-     * events they are for are), or is unrelated to wp users.
1002
-     * generally available
1003
-     *
1004
-     * @return boolean
1005
-     */
1006
-    public function is_owned()
1007
-    {
1008
-        if ($this->model_chain_to_wp_user()) {
1009
-            return true;
1010
-        }
1011
-        try {
1012
-            $this->get_foreign_key_to('WP_User');
1013
-            return true;
1014
-        } catch (EE_Error $e) {
1015
-            return false;
1016
-        }
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1022
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1023
-     * the model)
1024
-     *
1025
-     * @param array  $query_params      @see
1026
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1027
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1028
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1029
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1030
-     *                                  override this and set the select to "*", or a specific column name, like
1031
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1032
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1033
-     *                                  the aliases used to refer to this selection, and values are to be
1034
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1035
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1036
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1037
-     * @throws EE_Error
1038
-     * @throws InvalidArgumentException
1039
-     */
1040
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1041
-    {
1042
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1043
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1044
-        $select_expressions       = $columns_to_select === null
1045
-            ? $this->_construct_default_select_sql($model_query_info)
1046
-            : '';
1047
-        if ($this->_custom_selections instanceof CustomSelects) {
1048
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1049
-            $select_expressions .= $select_expressions
1050
-                ? ', ' . $custom_expressions
1051
-                : $custom_expressions;
1052
-        }
1053
-
1054
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1055
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1061
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1062
-     * method of including extra select information.
1063
-     *
1064
-     * @param array             $query_params
1065
-     * @param null|array|string $columns_to_select
1066
-     * @return null|CustomSelects
1067
-     * @throws InvalidArgumentException
1068
-     */
1069
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1070
-    {
1071
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1072
-            return null;
1073
-        }
1074
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1075
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1076
-        return new CustomSelects($selects);
1077
-    }
1078
-
1079
-
1080
-    /**
1081
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1082
-     * but you can use the model query params to more easily
1083
-     * take care of joins, field preparation etc.
1084
-     *
1085
-     * @param array  $query_params      @see
1086
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1087
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1088
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1089
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1090
-     *                                  override this and set the select to "*", or a specific column name, like
1091
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1092
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1093
-     *                                  the aliases used to refer to this selection, and values are to be
1094
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1095
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1096
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1097
-     * @throws EE_Error
1098
-     */
1099
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1100
-    {
1101
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * For creating a custom select statement
1107
-     *
1108
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
-     *                                 SQL, and 1=>is the datatype
1111
-     * @return string
1112
-     * @throws EE_Error
1113
-     */
1114
-    private function _construct_select_from_input($columns_to_select)
1115
-    {
1116
-        if (is_array($columns_to_select)) {
1117
-            $select_sql_array = [];
1118
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
-                    throw new EE_Error(
1121
-                        sprintf(
1122
-                            esc_html__(
1123
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
-                                'event_espresso'
1125
-                            ),
1126
-                            $selection_and_datatype,
1127
-                            $alias
1128
-                        )
1129
-                    );
1130
-                }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype[1],
1139
-                            $selection_and_datatype[0],
1140
-                            $alias,
1141
-                            implode(', ', $this->_valid_wpdb_data_types)
1142
-                        )
1143
-                    );
1144
-                }
1145
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
-            }
1147
-            $columns_to_select_string = implode(', ', $select_sql_array);
1148
-        } else {
1149
-            $columns_to_select_string = $columns_to_select;
1150
-        }
1151
-        return $columns_to_select_string;
1152
-    }
1153
-
1154
-
1155
-    /**
1156
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
-     *
1158
-     * @return string
1159
-     * @throws EE_Error
1160
-     */
1161
-    public function primary_key_name()
1162
-    {
1163
-        return $this->get_primary_key_field()->get_name();
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1169
-     * If there is no primary key on this model, $id is treated as primary key string
1170
-     *
1171
-     * @param mixed $id int or string, depending on the type of the model's primary key
1172
-     * @return EE_Base_Class|mixed|null
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get_one_by_ID($id)
1176
-    {
1177
-        if ($this->get_from_entity_map($id)) {
1178
-            return $this->get_from_entity_map($id);
1179
-        }
1180
-        $model_object = $this->get_one(
1181
-            $this->alter_query_params_to_restrict_by_ID(
1182
-                $id,
1183
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1184
-            )
1185
-        );
1186
-        $className    = $this->_get_class_name();
1187
-        if ($model_object instanceof $className) {
1188
-            // make sure valid objects get added to the entity map
1189
-            // so that the next call to this method doesn't trigger another trip to the db
1190
-            $this->add_to_entity_map($model_object);
1191
-        }
1192
-        return $model_object;
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * Alters query parameters to only get items with this ID are returned.
1198
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1199
-     * or could just be a simple primary key ID
1200
-     *
1201
-     * @param int   $id
1202
-     * @param array $query_params
1203
-     * @return array of normal query params, @see
1204
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1208
-    {
1209
-        if (! isset($query_params[0])) {
1210
-            $query_params[0] = [];
1211
-        }
1212
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1213
-        if ($conditions_from_id === null) {
1214
-            $query_params[0][ $this->primary_key_name() ] = $id;
1215
-        } else {
1216
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1217
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1218
-        }
1219
-        return $query_params;
1220
-    }
1221
-
1222
-
1223
-    /**
1224
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1225
-     * array. If no item is found, null is returned.
1226
-     *
1227
-     * @param array $query_params like EEM_Base's $query_params variable.
1228
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1229
-     * @throws EE_Error
1230
-     */
1231
-    public function get_one($query_params = [])
1232
-    {
1233
-        if (! is_array($query_params)) {
1234
-            EE_Error::doing_it_wrong(
1235
-                'EEM_Base::get_one',
1236
-                sprintf(
1237
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1238
-                    gettype($query_params)
1239
-                ),
1240
-                '4.6.0'
1241
-            );
1242
-            $query_params = [];
1243
-        }
1244
-        $query_params['limit'] = 1;
1245
-        $items                 = $this->get_all($query_params);
1246
-        if (empty($items)) {
1247
-            return null;
1248
-        }
1249
-        return array_shift($items);
1250
-    }
1251
-
1252
-
1253
-    /**
1254
-     * Returns the next x number of items in sequence from the given value as
1255
-     * found in the database matching the given query conditions.
1256
-     *
1257
-     * @param mixed $current_field_value    Value used for the reference point.
1258
-     * @param null  $field_to_order_by      What field is used for the
1259
-     *                                      reference point.
1260
-     * @param int   $limit                  How many to return.
1261
-     * @param array $query_params           Extra conditions on the query.
1262
-     * @param null  $columns_to_select      If left null, then an array of
1263
-     *                                      EE_Base_Class objects is returned,
1264
-     *                                      otherwise you can indicate just the
1265
-     *                                      columns you want returned.
1266
-     * @return EE_Base_Class[]|array
1267
-     * @throws EE_Error
1268
-     */
1269
-    public function next_x(
1270
-        $current_field_value,
1271
-        $field_to_order_by = null,
1272
-        $limit = 1,
1273
-        $query_params = [],
1274
-        $columns_to_select = null
1275
-    ) {
1276
-        return $this->_get_consecutive(
1277
-            $current_field_value,
1278
-            '>',
1279
-            $field_to_order_by,
1280
-            $limit,
1281
-            $query_params,
1282
-            $columns_to_select
1283
-        );
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Returns the previous x number of items in sequence from the given value
1289
-     * as found in the database matching the given query conditions.
1290
-     *
1291
-     * @param mixed $current_field_value    Value used for the reference point.
1292
-     * @param null  $field_to_order_by      What field is used for the
1293
-     *                                      reference point.
1294
-     * @param int   $limit                  How many to return.
1295
-     * @param array $query_params           Extra conditions on the query.
1296
-     * @param null  $columns_to_select      If left null, then an array of
1297
-     *                                      EE_Base_Class objects is returned,
1298
-     *                                      otherwise you can indicate just the
1299
-     *                                      columns you want returned.
1300
-     * @return EE_Base_Class[]|array
1301
-     * @throws EE_Error
1302
-     */
1303
-    public function previous_x(
1304
-        $current_field_value,
1305
-        $field_to_order_by = null,
1306
-        $limit = 1,
1307
-        $query_params = [],
1308
-        $columns_to_select = null
1309
-    ) {
1310
-        return $this->_get_consecutive(
1311
-            $current_field_value,
1312
-            '<',
1313
-            $field_to_order_by,
1314
-            $limit,
1315
-            $query_params,
1316
-            $columns_to_select
1317
-        );
1318
-    }
1319
-
1320
-
1321
-    /**
1322
-     * Returns the next item in sequence from the given value as found in the
1323
-     * database matching the given query conditions.
1324
-     *
1325
-     * @param mixed $current_field_value    Value used for the reference point.
1326
-     * @param null  $field_to_order_by      What field is used for the
1327
-     *                                      reference point.
1328
-     * @param array $query_params           Extra conditions on the query.
1329
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1330
-     *                                      object is returned, otherwise you
1331
-     *                                      can indicate just the columns you
1332
-     *                                      want and a single array indexed by
1333
-     *                                      the columns will be returned.
1334
-     * @return EE_Base_Class|null|array()
1335
-     * @throws EE_Error
1336
-     */
1337
-    public function next(
1338
-        $current_field_value,
1339
-        $field_to_order_by = null,
1340
-        $query_params = [],
1341
-        $columns_to_select = null
1342
-    ) {
1343
-        $results = $this->_get_consecutive(
1344
-            $current_field_value,
1345
-            '>',
1346
-            $field_to_order_by,
1347
-            1,
1348
-            $query_params,
1349
-            $columns_to_select
1350
-        );
1351
-        return empty($results) ? null : reset($results);
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * Returns the previous item in sequence from the given value as found in
1357
-     * the database matching the given query conditions.
1358
-     *
1359
-     * @param mixed $current_field_value    Value used for the reference point.
1360
-     * @param null  $field_to_order_by      What field is used for the
1361
-     *                                      reference point.
1362
-     * @param array $query_params           Extra conditions on the query.
1363
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1364
-     *                                      object is returned, otherwise you
1365
-     *                                      can indicate just the columns you
1366
-     *                                      want and a single array indexed by
1367
-     *                                      the columns will be returned.
1368
-     * @return EE_Base_Class|null|array()
1369
-     * @throws EE_Error
1370
-     */
1371
-    public function previous(
1372
-        $current_field_value,
1373
-        $field_to_order_by = null,
1374
-        $query_params = [],
1375
-        $columns_to_select = null
1376
-    ) {
1377
-        $results = $this->_get_consecutive(
1378
-            $current_field_value,
1379
-            '<',
1380
-            $field_to_order_by,
1381
-            1,
1382
-            $query_params,
1383
-            $columns_to_select
1384
-        );
1385
-        return empty($results) ? null : reset($results);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * Returns the a consecutive number of items in sequence from the given
1391
-     * value as found in the database matching the given query conditions.
1392
-     *
1393
-     * @param mixed  $current_field_value   Value used for the reference point.
1394
-     * @param string $operand               What operand is used for the sequence.
1395
-     * @param string $field_to_order_by     What field is used for the reference point.
1396
-     * @param int    $limit                 How many to return.
1397
-     * @param array  $query_params          Extra conditions on the query.
1398
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1399
-     *                                      otherwise you can indicate just the columns you want returned.
1400
-     * @return EE_Base_Class[]|array
1401
-     * @throws EE_Error
1402
-     */
1403
-    protected function _get_consecutive(
1404
-        $current_field_value,
1405
-        $operand = '>',
1406
-        $field_to_order_by = null,
1407
-        $limit = 1,
1408
-        $query_params = [],
1409
-        $columns_to_select = null
1410
-    ) {
1411
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1412
-        if (empty($field_to_order_by)) {
1413
-            if ($this->has_primary_key_field()) {
1414
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1415
-            } else {
1416
-                if (WP_DEBUG) {
1417
-                    throw new EE_Error(
1418
-                        esc_html__(
1419
-                            '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).',
1420
-                            'event_espresso'
1421
-                        )
1422
-                    );
1423
-                }
1424
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1425
-                return [];
1426
-            }
1427
-        }
1428
-        if (! is_array($query_params)) {
1429
-            EE_Error::doing_it_wrong(
1430
-                'EEM_Base::_get_consecutive',
1431
-                sprintf(
1432
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1433
-                    gettype($query_params)
1434
-                ),
1435
-                '4.6.0'
1436
-            );
1437
-            $query_params = [];
1438
-        }
1439
-        // let's add the where query param for consecutive look up.
1440
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1441
-        $query_params['limit']                 = $limit;
1442
-        // set direction
1443
-        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1444
-        $query_params['order_by'] = $operand === '>'
1445
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1446
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1447
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1448
-        if (empty($columns_to_select)) {
1449
-            return $this->get_all($query_params);
1450
-        }
1451
-        // getting just the fields
1452
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1453
-    }
1454
-
1455
-
1456
-    /**
1457
-     * This sets the _timezone property after model object has been instantiated.
1458
-     *
1459
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
-     */
1461
-    public function set_timezone($timezone)
1462
-    {
1463
-        if ($timezone !== null) {
1464
-            $this->_timezone = $timezone;
1465
-        }
1466
-        // note we need to loop through relations and set the timezone on those objects as well.
1467
-        foreach ($this->_model_relations as $relation) {
1468
-            $relation->set_timezone($timezone);
1469
-        }
1470
-        // and finally we do the same for any datetime fields
1471
-        foreach ($this->_fields as $field) {
1472
-            if ($field instanceof EE_Datetime_Field) {
1473
-                $field->set_timezone($timezone);
1474
-            }
1475
-        }
1476
-    }
1477
-
1478
-
1479
-    /**
1480
-     * This just returns whatever is set for the current timezone.
1481
-     *
1482
-     * @access public
1483
-     * @return string
1484
-     */
1485
-    public function get_timezone()
1486
-    {
1487
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1488
-        if (empty($this->_timezone)) {
1489
-            foreach ($this->_fields as $field) {
1490
-                if ($field instanceof EE_Datetime_Field) {
1491
-                    $this->set_timezone($field->get_timezone());
1492
-                    break;
1493
-                }
1494
-            }
1495
-        }
1496
-        // if timezone STILL empty then return the default timezone for the site.
1497
-        if (empty($this->_timezone)) {
1498
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1499
-        }
1500
-        return $this->_timezone;
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * This returns the date formats set for the given field name and also ensures that
1506
-     * $this->_timezone property is set correctly.
1507
-     *
1508
-     * @param string $field_name The name of the field the formats are being retrieved for.
1509
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1510
-     * @return array formats in an array with the date format first, and the time format last.
1511
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1512
-     * @since 4.6.x
1513
-     */
1514
-    public function get_formats_for($field_name, $pretty = false)
1515
-    {
1516
-        $field_settings = $this->field_settings_for($field_name);
1517
-        // if not a valid EE_Datetime_Field then throw error
1518
-        if (! $field_settings instanceof EE_Datetime_Field) {
1519
-            throw new EE_Error(
1520
-                sprintf(
1521
-                    esc_html__(
1522
-                        '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.',
1523
-                        'event_espresso'
1524
-                    ),
1525
-                    $field_name
1526
-                )
1527
-            );
1528
-        }
1529
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1530
-        // the field.
1531
-        $this->_timezone = $field_settings->get_timezone();
1532
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1533
-    }
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     *
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1553
-     *                                 exception is triggered.
1554
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1555
-     * @since 4.6.x
1556
-     */
1557
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1558
-    {
1559
-        $formats  = $this->get_formats_for($field_name);
1560
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1561
-        if ($timestamp) {
1562
-            return $DateTime->format('U');
1563
-        }
1564
-        // not returning timestamp, so return formatted string in timezone.
1565
-        switch ($what) {
1566
-            case 'time':
1567
-                return $DateTime->format($formats[1]);
1568
-                break;
1569
-            case 'date':
1570
-                return $DateTime->format($formats[0]);
1571
-                break;
1572
-            default:
1573
-                return $DateTime->format(implode(' ', $formats));
1574
-                break;
1575
-        }
1576
-    }
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        // just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        // load EEH_DTT_Helper
1601
-        $set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
-    }
1606
-
1607
-
1608
-    /**
1609
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
-     *
1611
-     * @return EE_Table_Base[]
1612
-     */
1613
-    public function get_tables()
1614
-    {
1615
-        return $this->_tables;
1616
-    }
1617
-
1618
-
1619
-    /**
1620
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1621
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1622
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1623
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1624
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1625
-     * model object with EVT_ID = 1
1626
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1627
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1628
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1629
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1630
-     * are not specified)
1631
-     *
1632
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1633
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1634
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1635
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1636
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1637
-     *                                         ID=34, we'd use this method as follows:
1638
-     *                                         EEM_Transaction::instance()->update(
1639
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1640
-     *                                         array(array('TXN_ID'=>34)));
1641
-     * @param array   $query_params            @see
1642
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1644
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1645
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1646
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1647
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1648
-     *                                         TRUE, it is assumed that you've already called
1649
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1650
-     *                                         malicious javascript. However, if
1651
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1652
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1653
-     *                                         and every other field, before insertion. We provide this parameter
1654
-     *                                         because model objects perform their prepare_for_set function on all
1655
-     *                                         their values, and so don't need to be called again (and in many cases,
1656
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1657
-     *                                         prepare_for_set method...)
1658
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1659
-     *                                         in this model's entity map according to $fields_n_values that match
1660
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1661
-     *                                         by setting this to FALSE, but be aware that model objects being used
1662
-     *                                         could get out-of-sync with the database
1663
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1664
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1665
-     *                                         bad)
1666
-     * @throws EE_Error
1667
-     */
1668
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1669
-    {
1670
-        if (! is_array($query_params)) {
1671
-            EE_Error::doing_it_wrong(
1672
-                'EEM_Base::update',
1673
-                sprintf(
1674
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
-                    gettype($query_params)
1676
-                ),
1677
-                '4.6.0'
1678
-            );
1679
-            $query_params = [];
1680
-        }
1681
-        /**
1682
-         * Action called before a model update call has been made.
1683
-         *
1684
-         * @param EEM_Base $model
1685
-         * @param array    $fields_n_values the updated fields and their new values
1686
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1687
-         */
1688
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1689
-        /**
1690
-         * Filters the fields about to be updated given the query parameters. You can provide the
1691
-         * $query_params to $this->get_all() to find exactly which records will be updated
1692
-         *
1693
-         * @param array    $fields_n_values fields and their new values
1694
-         * @param EEM_Base $model           the model being queried
1695
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1696
-         */
1697
-        $fields_n_values = (array) apply_filters(
1698
-            'FHEE__EEM_Base__update__fields_n_values',
1699
-            $fields_n_values,
1700
-            $this,
1701
-            $query_params
1702
-        );
1703
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1704
-        // to do that, for each table, verify that it's PK isn't null.
1705
-        $tables = $this->get_tables();
1706
-        // 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
1707
-        // NOTE: we should make this code more efficient by NOT querying twice
1708
-        // before the real update, but that needs to first go through ALPHA testing
1709
-        // as it's dangerous. says Mike August 8 2014
1710
-        // we want to make sure the default_where strategy is ignored
1711
-        $this->_ignore_where_strategy = true;
1712
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1713
-        foreach ($wpdb_select_results as $wpdb_result) {
1714
-            // type cast stdClass as array
1715
-            $wpdb_result = (array) $wpdb_result;
1716
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1717
-            if ($this->has_primary_key_field()) {
1718
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1719
-            } else {
1720
-                // 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)
1721
-                $main_table_pk_value = null;
1722
-            }
1723
-            // 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
1724
-            // 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
1725
-            if (count($tables) > 1) {
1726
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1727
-                // in that table, and so we'll want to insert one
1728
-                foreach ($tables as $table_obj) {
1729
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1730
-                    // if there is no private key for this table on the results, it means there's no entry
1731
-                    // in this table, right? so insert a row in the current table, using any fields available
1732
-                    if (
1733
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1734
-                           && $wpdb_result[ $this_table_pk_column ])
1735
-                    ) {
1736
-                        $success = $this->_insert_into_specific_table(
1737
-                            $table_obj,
1738
-                            $fields_n_values,
1739
-                            $main_table_pk_value
1740
-                        );
1741
-                        // if we died here, report the error
1742
-                        if (! $success) {
1743
-                            return false;
1744
-                        }
1745
-                    }
1746
-                }
1747
-            }
1748
-            //              //and now check that if we have cached any models by that ID on the model, that
1749
-            //              //they also get updated properly
1750
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1751
-            //              if( $model_object ){
1752
-            //                  foreach( $fields_n_values as $field => $value ){
1753
-            //                      $model_object->set($field, $value);
1754
-            // let's make sure default_where strategy is followed now
1755
-            $this->_ignore_where_strategy = false;
1756
-        }
1757
-        // if we want to keep model objects in sync, AND
1758
-        // if this wasn't called from a model object (to update itself)
1759
-        // then we want to make sure we keep all the existing
1760
-        // model objects in sync with the db
1761
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1762
-            if ($this->has_primary_key_field()) {
1763
-                $model_objs_affected_ids = $this->get_col($query_params);
1764
-            } else {
1765
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1766
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1767
-                $model_objs_affected_ids     = [];
1768
-                foreach ($models_affected_key_columns as $row) {
1769
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1770
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1771
-                }
1772
-            }
1773
-            if (! $model_objs_affected_ids) {
1774
-                // wait wait wait- if nothing was affected let's stop here
1775
-                return 0;
1776
-            }
1777
-            foreach ($model_objs_affected_ids as $id) {
1778
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1779
-                if ($model_obj_in_entity_map) {
1780
-                    foreach ($fields_n_values as $field => $new_value) {
1781
-                        $model_obj_in_entity_map->set($field, $new_value);
1782
-                    }
1783
-                }
1784
-            }
1785
-            // if there is a primary key on this model, we can now do a slight optimization
1786
-            if ($this->has_primary_key_field()) {
1787
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1788
-                $query_params = [
1789
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1790
-                    'limit'                    => count($model_objs_affected_ids),
1791
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1792
-                ];
1793
-            }
1794
-        }
1795
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
-
1797
-        $SQL = "UPDATE {$model_query_info->get_full_join_sql()} 
40
+	/**
41
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
42
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
43
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
44
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
45
+	 *
46
+	 * @var boolean
47
+	 */
48
+	private $_values_already_prepared_by_model_object = 0;
49
+
50
+	/**
51
+	 * when $_values_already_prepared_by_model_object equals this, we assume
52
+	 * the data is just like form input that needs to have the model fields'
53
+	 * prepare_for_set and prepare_for_use_in_db called on it
54
+	 */
55
+	const not_prepared_by_model_object = 0;
56
+
57
+	/**
58
+	 * when $_values_already_prepared_by_model_object equals this, we
59
+	 * assume this value is coming from a model object and doesn't need to have
60
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
61
+	 */
62
+	const prepared_by_model_object = 1;
63
+
64
+	/**
65
+	 * when $_values_already_prepared_by_model_object equals this, we assume
66
+	 * the values are already to be used in the database (ie no processing is done
67
+	 * on them by the model's fields)
68
+	 */
69
+	const prepared_for_use_in_db = 2;
70
+
71
+
72
+	protected $singular_item = 'Item';
73
+
74
+	protected $plural_item   = 'Items';
75
+
76
+	/**
77
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
78
+	 */
79
+	protected $_tables;
80
+
81
+	/**
82
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
83
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
84
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
85
+	 *
86
+	 * @var EE_Model_Field_Base[][] $_fields
87
+	 */
88
+	protected $_fields;
89
+
90
+	/**
91
+	 * array of different kinds of relations
92
+	 *
93
+	 * @var EE_Model_Relation_Base[] $_model_relations
94
+	 */
95
+	protected $_model_relations = [];
96
+
97
+	/**
98
+	 * @var EE_Index[] $_indexes
99
+	 */
100
+	protected $_indexes = [];
101
+
102
+	/**
103
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
104
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
105
+	 * by setting the same columns as used in these queries in the query yourself.
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_default_where_conditions_strategy;
110
+
111
+	/**
112
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
113
+	 * This is particularly useful when you want something between 'none' and 'default'
114
+	 *
115
+	 * @var EE_Default_Where_Conditions
116
+	 */
117
+	protected $_minimum_where_conditions_strategy;
118
+
119
+	/**
120
+	 * String describing how to find the "owner" of this model's objects.
121
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
122
+	 * But when there isn't, this indicates which related model, or transiently-related model,
123
+	 * has the foreign key to the wp_users table.
124
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
125
+	 * related to events, and events have a foreign key to wp_users.
126
+	 * On EEM_Transaction, this would be 'Transaction.Event'
127
+	 *
128
+	 * @var string
129
+	 */
130
+	protected $_model_chain_to_wp_user = '';
131
+
132
+	/**
133
+	 * String describing how to find the model with a password controlling access to this model. This property has the
134
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
135
+	 * This value is the path of models to follow to arrive at the model with the password field.
136
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
137
+	 * model with a password that should affect reading this on the front-end.
138
+	 * Eg this is an empty string for the Event model because it has a password.
139
+	 * This is null for the Registration model, because its event's password has no bearing on whether
140
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
141
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
142
+	 * should hide tickets for datetimes for events that have a password set.
143
+	 *
144
+	 * @var string |null
145
+	 */
146
+	protected $model_chain_to_password = null;
147
+
148
+	/**
149
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
150
+	 * don't need it (particularly CPT models)
151
+	 *
152
+	 * @var bool
153
+	 */
154
+	protected $_ignore_where_strategy = false;
155
+
156
+	/**
157
+	 * String used in caps relating to this model. Eg, if the caps relating to this
158
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
159
+	 *
160
+	 * @var string. If null it hasn't been initialized yet. If false then we
161
+	 * have indicated capabilities don't apply to this
162
+	 */
163
+	protected $_caps_slug = null;
164
+
165
+	/**
166
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
167
+	 * and next-level keys are capability names, and each's value is a
168
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
169
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
170
+	 * and then each capability in the corresponding sub-array that they're missing
171
+	 * adds the where conditions onto the query.
172
+	 *
173
+	 * @var array
174
+	 */
175
+	protected $_cap_restrictions = [
176
+		self::caps_read       => [],
177
+		self::caps_read_admin => [],
178
+		self::caps_edit       => [],
179
+		self::caps_delete     => [],
180
+	];
181
+
182
+	/**
183
+	 * Array defining which cap restriction generators to use to create default
184
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
185
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
186
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
187
+	 * automatically set this to false (not just null).
188
+	 *
189
+	 * @var EE_Restriction_Generator_Base[]
190
+	 */
191
+	protected $_cap_restriction_generators = [];
192
+
193
+	/**
194
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
195
+	 */
196
+	const caps_read       = 'read';
197
+
198
+	const caps_read_admin = 'read_admin';
199
+
200
+	const caps_edit       = 'edit';
201
+
202
+	const caps_delete     = 'delete';
203
+
204
+	/**
205
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
206
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
207
+	 * maps to 'read' because when looking for relevant permissions we're going to use
208
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
209
+	 *
210
+	 * @var array
211
+	 */
212
+	protected $_cap_contexts_to_cap_action_map = [
213
+		self::caps_read       => 'read',
214
+		self::caps_read_admin => 'read',
215
+		self::caps_edit       => 'edit',
216
+		self::caps_delete     => 'delete',
217
+	];
218
+
219
+	/**
220
+	 * Timezone
221
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
222
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
223
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
224
+	 * EE_Datetime_Field data type will have access to it.
225
+	 *
226
+	 * @var string
227
+	 */
228
+	protected $_timezone;
229
+
230
+
231
+	/**
232
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
233
+	 * multisite.
234
+	 *
235
+	 * @var int
236
+	 */
237
+	protected static $_model_query_blog_id;
238
+
239
+	/**
240
+	 * A copy of _fields, except the array keys are the model names pointed to by
241
+	 * the field
242
+	 *
243
+	 * @var EE_Model_Field_Base[]
244
+	 */
245
+	private $_cache_foreign_key_to_fields = [];
246
+
247
+	/**
248
+	 * Cached list of all the fields on the model, indexed by their name
249
+	 *
250
+	 * @var EE_Model_Field_Base[]
251
+	 */
252
+	private $_cached_fields = null;
253
+
254
+	/**
255
+	 * Cached list of all the fields on the model, except those that are
256
+	 * marked as only pertinent to the database
257
+	 *
258
+	 * @var EE_Model_Field_Base[]
259
+	 */
260
+	private $_cached_fields_non_db_only = null;
261
+
262
+	/**
263
+	 * A cached reference to the primary key for quick lookup
264
+	 *
265
+	 * @var EE_Model_Field_Base
266
+	 */
267
+	private $_primary_key_field = null;
268
+
269
+	/**
270
+	 * Flag indicating whether this model has a primary key or not
271
+	 *
272
+	 * @var boolean
273
+	 */
274
+	protected $_has_primary_key_field = null;
275
+
276
+	/**
277
+	 * array in the format:  [ FK alias => full PK ]
278
+	 * where keys are local column name aliases for foreign keys
279
+	 * and values are the fully qualified column name for the primary key they represent
280
+	 *  ex:
281
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
282
+	 *
283
+	 * @var array $foreign_key_aliases
284
+	 */
285
+	protected $foreign_key_aliases = [];
286
+
287
+	/**
288
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
289
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
290
+	 * This should be true for models that deal with data that should exist independent of EE.
291
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
292
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
293
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
294
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
295
+	 *
296
+	 * @var boolean
297
+	 */
298
+	protected $_wp_core_model = false;
299
+
300
+	/**
301
+	 * @var bool stores whether this model has a password field or not.
302
+	 * null until initialized by hasPasswordField()
303
+	 */
304
+	protected $has_password_field;
305
+
306
+	/**
307
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
308
+	 */
309
+	protected $password_field;
310
+
311
+	/**
312
+	 *    List of valid operators that can be used for querying.
313
+	 * The keys are all operators we'll accept, the values are the real SQL
314
+	 * operators used
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_valid_operators = [
319
+		'='           => '=',
320
+		'<='          => '<=',
321
+		'<'           => '<',
322
+		'>='          => '>=',
323
+		'>'           => '>',
324
+		'!='          => '!=',
325
+		'LIKE'        => 'LIKE',
326
+		'like'        => 'LIKE',
327
+		'NOT_LIKE'    => 'NOT LIKE',
328
+		'not_like'    => 'NOT LIKE',
329
+		'NOT LIKE'    => 'NOT LIKE',
330
+		'not like'    => 'NOT LIKE',
331
+		'IN'          => 'IN',
332
+		'in'          => 'IN',
333
+		'NOT_IN'      => 'NOT IN',
334
+		'not_in'      => 'NOT IN',
335
+		'NOT IN'      => 'NOT IN',
336
+		'not in'      => 'NOT IN',
337
+		'between'     => 'BETWEEN',
338
+		'BETWEEN'     => 'BETWEEN',
339
+		'IS_NOT_NULL' => 'IS NOT NULL',
340
+		'is_not_null' => 'IS NOT NULL',
341
+		'IS NOT NULL' => 'IS NOT NULL',
342
+		'is not null' => 'IS NOT NULL',
343
+		'IS_NULL'     => 'IS NULL',
344
+		'is_null'     => 'IS NULL',
345
+		'IS NULL'     => 'IS NULL',
346
+		'is null'     => 'IS NULL',
347
+		'REGEXP'      => 'REGEXP',
348
+		'regexp'      => 'REGEXP',
349
+		'NOT_REGEXP'  => 'NOT REGEXP',
350
+		'not_regexp'  => 'NOT REGEXP',
351
+		'NOT REGEXP'  => 'NOT REGEXP',
352
+		'not regexp'  => 'NOT REGEXP',
353
+	];
354
+
355
+	/**
356
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
357
+	 *
358
+	 * @var array
359
+	 */
360
+	protected $_in_style_operators = ['IN', 'NOT IN'];
361
+
362
+	/**
363
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
364
+	 * '12-31-2012'"
365
+	 *
366
+	 * @var array
367
+	 */
368
+	protected $_between_style_operators = ['BETWEEN'];
369
+
370
+	/**
371
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
376
+
377
+	/**
378
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
379
+	 * on a join table.
380
+	 *
381
+	 * @var array
382
+	 */
383
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
384
+
385
+	/**
386
+	 * Allowed values for $query_params['order'] for ordering in queries
387
+	 *
388
+	 * @var array
389
+	 */
390
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
391
+
392
+	/**
393
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
394
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
395
+	 *
396
+	 * @var array
397
+	 */
398
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
399
+
400
+	/**
401
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
402
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
403
+	 *
404
+	 * @var array
405
+	 */
406
+	private $_allowed_query_params = [
407
+		0,
408
+		'limit',
409
+		'order_by',
410
+		'group_by',
411
+		'having',
412
+		'force_join',
413
+		'order',
414
+		'on_join_limit',
415
+		'default_where_conditions',
416
+		'caps',
417
+		'extra_selects',
418
+		'exclude_protected',
419
+	];
420
+
421
+	/**
422
+	 * All the data types that can be used in $wpdb->prepare statements.
423
+	 *
424
+	 * @var array
425
+	 */
426
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
427
+
428
+	/**
429
+	 * @var EE_Registry $EE
430
+	 */
431
+	protected $EE = null;
432
+
433
+
434
+	/**
435
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
436
+	 *
437
+	 * @var int
438
+	 */
439
+	protected $_show_next_x_db_queries = 0;
440
+
441
+	/**
442
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
443
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
444
+	 * WHERE, GROUP_BY, etc.
445
+	 *
446
+	 * @var CustomSelects
447
+	 */
448
+	protected $_custom_selections = [];
449
+
450
+	/**
451
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
452
+	 * caches every model object we've fetched from the DB on this request
453
+	 *
454
+	 * @var array
455
+	 */
456
+	protected $_entity_map;
457
+
458
+	/**
459
+	 * @var LoaderInterface
460
+	 */
461
+	protected static $loader;
462
+
463
+	/**
464
+	 * @var Mirror
465
+	 */
466
+	private static $mirror;
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+	/**
547
+	 * About all child constructors:
548
+	 * they should define the _tables, _fields and _model_relations arrays.
549
+	 * Should ALWAYS be called after child constructor.
550
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
551
+	 * finalizes constructing all the object's attributes.
552
+	 * Generally, rather than requiring a child to code
553
+	 * $this->_tables = array(
554
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
555
+	 *        ...);
556
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
557
+	 * each EE_Table has a function to set the table's alias after the constructor, using
558
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
559
+	 * do something similar.
560
+	 *
561
+	 * @param null $timezone
562
+	 * @throws EE_Error
563
+	 */
564
+	protected function __construct($timezone = null)
565
+	{
566
+		// check that the model has not been loaded too soon
567
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+			throw new EE_Error(
569
+				sprintf(
570
+					esc_html__(
571
+						'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.',
572
+						'event_espresso'
573
+					),
574
+					get_class($this)
575
+				)
576
+			);
577
+		}
578
+		/**
579
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
580
+		 */
581
+		if (empty(EEM_Base::$_model_query_blog_id)) {
582
+			EEM_Base::set_model_query_blog_id();
583
+		}
584
+		/**
585
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
586
+		 * just use EE_Register_Model_Extension
587
+		 *
588
+		 * @var EE_Table_Base[] $_tables
589
+		 */
590
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+		foreach ($this->_tables as $table_alias => $table_obj) {
592
+			/** @var $table_obj EE_Table_Base */
593
+			$table_obj->_construct_finalize_with_alias($table_alias);
594
+			if ($table_obj instanceof EE_Secondary_Table) {
595
+				/** @var $table_obj EE_Secondary_Table */
596
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
597
+			}
598
+		}
599
+		/**
600
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
601
+		 * EE_Register_Model_Extension
602
+		 *
603
+		 * @param EE_Model_Field_Base[] $_fields
604
+		 */
605
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+		$this->_invalidate_field_caches();
607
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
608
+			if (! array_key_exists($table_alias, $this->_tables)) {
609
+				throw new EE_Error(
610
+					sprintf(
611
+						esc_html__(
612
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
613
+							'event_espresso'
614
+						),
615
+						$table_alias,
616
+						implode(",", $this->_fields)
617
+					)
618
+				);
619
+			}
620
+			foreach ($fields_for_table as $field_name => $field_obj) {
621
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
622
+				// primary key field base has a slightly different _construct_finalize
623
+				/** @var $field_obj EE_Model_Field_Base */
624
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
625
+			}
626
+		}
627
+		// everything is related to Extra_Meta
628
+		if (get_class($this) !== 'EEM_Extra_Meta') {
629
+			// make extra meta related to everything, but don't block deleting things just
630
+			// because they have related extra meta info. For now just orphan those extra meta
631
+			// in the future we should automatically delete them
632
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
633
+		}
634
+		// and change logs
635
+		if (get_class($this) !== 'EEM_Change_Log') {
636
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
637
+		}
638
+		/**
639
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
640
+		 * EE_Register_Model_Extension
641
+		 *
642
+		 * @param EE_Model_Relation_Base[] $_model_relations
643
+		 */
644
+		$this->_model_relations = (array) apply_filters(
645
+			'FHEE__' . get_class($this) . '__construct__model_relations',
646
+			$this->_model_relations
647
+		);
648
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
649
+			/** @var $relation_obj EE_Model_Relation_Base */
650
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
651
+		}
652
+		foreach ($this->_indexes as $index_name => $index_obj) {
653
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
654
+		}
655
+		$this->set_timezone($timezone);
656
+		// finalize default where condition strategy, or set default
657
+		if (! $this->_default_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
662
+		if (! $this->_minimum_where_conditions_strategy) {
663
+			// nothing was set during child constructor, so set default
664
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665
+		}
666
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
667
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
668
+		// to indicate to NOT set it, set it to the logical default
669
+		if ($this->_caps_slug === null) {
670
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
671
+		}
672
+		// initialize the standard cap restriction generators if none were specified by the child constructor
673
+		if (is_array($this->_cap_restriction_generators)) {
674
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678
+						new EE_Restriction_Generator_Protected(),
679
+						$cap_context,
680
+						$this
681
+					);
682
+				}
683
+			}
684
+		}
685
+		// if there are cap restriction generators, use them to make the default cap restrictions
686
+		if (is_array($this->_cap_restriction_generators)) {
687
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
+				if (! $generator_object) {
689
+					continue;
690
+				}
691
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
692
+					throw new EE_Error(
693
+						sprintf(
694
+							esc_html__(
695
+								'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.',
696
+								'event_espresso'
697
+							),
698
+							$context,
699
+							$this->get_this_model_name()
700
+						)
701
+					);
702
+				}
703
+				$action = $this->cap_action_for_context($context);
704
+				if (! $generator_object->construction_finalized()) {
705
+					$generator_object->_construct_finalize($this, $action);
706
+				}
707
+			}
708
+		}
709
+		do_action('AHEE__' . get_class($this) . '__construct__end');
710
+	}
711
+
712
+
713
+	/**
714
+	 * @return LoaderInterface
715
+	 * @throws InvalidArgumentException
716
+	 * @throws InvalidDataTypeException
717
+	 * @throws InvalidInterfaceException
718
+	 */
719
+	protected static function getLoader(): LoaderInterface
720
+	{
721
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
722
+			EEM_Base::$loader = LoaderFactory::getLoader();
723
+		}
724
+		return EEM_Base::$loader;
725
+	}
726
+
727
+
728
+	/**
729
+	 * @return Mirror
730
+	 * @since   $VID:$
731
+	 */
732
+	private static function getMirror(): Mirror
733
+	{
734
+		if (! EEM_Base::$mirror instanceof Mirror) {
735
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736
+		}
737
+		return EEM_Base::$mirror;
738
+	}
739
+
740
+
741
+	/**
742
+	 * @param string $model_class_Name
743
+	 * @param string $timezone
744
+	 * @return array
745
+	 * @throws ReflectionException
746
+	 * @since   $VID:$
747
+	 */
748
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
749
+	{
750
+		$arguments = [$timezone];
751
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
752
+		if (count($params) > 1) {
753
+			if ($params[1]->getName() === 'model_field_factory') {
754
+				$arguments = [
755
+					$timezone,
756
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
761
+					$timezone,
762
+				];
763
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
764
+				$arguments = [
765
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
766
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
767
+					$timezone,
768
+				];
769
+			}
770
+		}
771
+		return $arguments;
772
+	}
773
+
774
+
775
+	/**
776
+	 * This function is a singleton method used to instantiate the Espresso_model object
777
+	 *
778
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
779
+	 *                                (and any incoming timezone data that gets saved).
780
+	 *                                Note this just sends the timezone info to the date time model field objects.
781
+	 *                                Default is NULL
782
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
783
+	 * @return static (as in the concrete child class)
784
+	 * @throws EE_Error
785
+	 * @throws ReflectionException
786
+	 */
787
+	public static function instance($timezone = null)
788
+	{
789
+		// check if instance of Espresso_model already exists
790
+		if (! static::$_instance instanceof static) {
791
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792
+			$model     = new static(...$arguments);
793
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
794
+			static::$_instance = $model;
795
+		}
796
+		// we might have a timezone set, let set_timezone decide what to do with it
797
+		if ($timezone) {
798
+			static::$_instance->set_timezone($timezone);
799
+		}
800
+		// Espresso_model object
801
+		return static::$_instance;
802
+	}
803
+
804
+
805
+	/**
806
+	 * resets the model and returns it
807
+	 *
808
+	 * @param string|null $timezone
809
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
810
+	 * all its properties reset; if it wasn't instantiated, returns null)
811
+	 * @throws EE_Error
812
+	 * @throws ReflectionException
813
+	 * @throws InvalidArgumentException
814
+	 * @throws InvalidDataTypeException
815
+	 * @throws InvalidInterfaceException
816
+	 */
817
+	public static function reset($timezone = null)
818
+	{
819
+		if (! static::$_instance instanceof EEM_Base) {
820
+			return null;
821
+		}
822
+		// Let's NOT swap out the current instance for a new one
823
+		// because if someone has a reference to it, we can't remove their reference.
824
+		// It's best to keep using the same reference but change the original object instead,
825
+		// so reset all its properties to their original values as defined in the class.
826
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
827
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828
+			// don't set instance to null like it was originally,
829
+			// but it's static anyways, and we're ignoring static properties (for now at least)
830
+			if (! isset($static_properties[ $property ])) {
831
+				static::$_instance->{$property} = $value;
832
+			}
833
+		}
834
+		// and then directly call its constructor again, like we would if we were creating a new one
835
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
836
+		static::$_instance->__construct(...$arguments);
837
+		return self::instance();
838
+	}
839
+
840
+
841
+	/**
842
+	 * Used to set the $_model_query_blog_id static property.
843
+	 *
844
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
845
+	 *                      value for get_current_blog_id() will be used.
846
+	 */
847
+	public static function set_model_query_blog_id($blog_id = 0)
848
+	{
849
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
850
+			? (int) $blog_id
851
+			: get_current_blog_id();
852
+	}
853
+
854
+
855
+	/**
856
+	 * Returns whatever is set as the internal $model_query_blog_id.
857
+	 *
858
+	 * @return int
859
+	 */
860
+	public static function get_model_query_blog_id()
861
+	{
862
+		return EEM_Base::$_model_query_blog_id;
863
+	}
864
+
865
+
866
+	/**
867
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
868
+	 *
869
+	 * @param boolean $translated return localized strings or JUST the array.
870
+	 * @return array
871
+	 * @throws EE_Error
872
+	 * @throws InvalidArgumentException
873
+	 * @throws InvalidDataTypeException
874
+	 * @throws InvalidInterfaceException
875
+	 */
876
+	public function status_array($translated = false)
877
+	{
878
+		if (! array_key_exists('Status', $this->_model_relations)) {
879
+			return [];
880
+		}
881
+		$model_name   = $this->get_this_model_name();
882
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
883
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884
+		$status_array = [];
885
+		foreach ($stati as $status) {
886
+			$status_array[ $status->ID() ] = $status->get('STS_code');
887
+		}
888
+		return $translated
889
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
890
+			: $status_array;
891
+	}
892
+
893
+
894
+	/**
895
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
896
+	 *
897
+	 * @param array $query_params             @see
898
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
899
+	 *                                        or if you have the development copy of EE you can view this at the path:
900
+	 *                                        /docs/G--Model-System/model-query-params.md
901
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
902
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
903
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
904
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
905
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
906
+	 *                                        'OR'=>array(
907
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
908
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
909
+	 *                                        )
910
+	 *                                        ),
911
+	 *                                        'limit'=>10,
912
+	 *                                        'group_by'=>'TXN_ID'
913
+	 *                                        ));
914
+	 *                                        get all the answers to the question titled "shirt size" for event with id
915
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
916
+	 *                                        'Question.QST_display_text'=>'shirt size',
917
+	 *                                        'Registration.Event.EVT_ID'=>12
918
+	 *                                        ),
919
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
920
+	 *                                        ));
921
+	 * @throws EE_Error
922
+	 */
923
+	public function get_all($query_params = [])
924
+	{
925
+		if (
926
+			isset($query_params['limit'])
927
+			&& ! isset($query_params['group_by'])
928
+		) {
929
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
930
+		}
931
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
932
+	}
933
+
934
+
935
+	/**
936
+	 * Modifies the query parameters so we only get back model objects
937
+	 * that "belong" to the current user
938
+	 *
939
+	 * @param array $query_params @see
940
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
941
+	 * @return array @see
942
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
943
+	 */
944
+	public function alter_query_params_to_only_include_mine($query_params = [])
945
+	{
946
+		$wp_user_field_name = $this->wp_user_field_name();
947
+		if ($wp_user_field_name) {
948
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
949
+		}
950
+		return $query_params;
951
+	}
952
+
953
+
954
+	/**
955
+	 * Returns the name of the field's name that points to the WP_User table
956
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
957
+	 * foreign key to the WP_User table)
958
+	 *
959
+	 * @return string|boolean string on success, boolean false when there is no
960
+	 * foreign key to the WP_User table
961
+	 */
962
+	public function wp_user_field_name()
963
+	{
964
+		try {
965
+			if (! empty($this->_model_chain_to_wp_user)) {
966
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
967
+				$last_model_name              = end($models_to_follow_to_wp_users);
968
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
969
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
970
+			} else {
971
+				$model_with_fk_to_wp_users = $this;
972
+				$model_chain_to_wp_user    = '';
973
+			}
974
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
975
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
976
+		} catch (EE_Error $e) {
977
+			return false;
978
+		}
979
+	}
980
+
981
+
982
+	/**
983
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
984
+	 * (or transiently-related model) has a foreign key to the wp_users table;
985
+	 * useful for finding if model objects of this type are 'owned' by the current user.
986
+	 * This is an empty string when the foreign key is on this model and when it isn't,
987
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
988
+	 * (or transiently-related model)
989
+	 *
990
+	 * @return string
991
+	 */
992
+	public function model_chain_to_wp_user()
993
+	{
994
+		return $this->_model_chain_to_wp_user;
995
+	}
996
+
997
+
998
+	/**
999
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1000
+	 * like how registrations don't have a foreign key to wp_users, but the
1001
+	 * events they are for are), or is unrelated to wp users.
1002
+	 * generally available
1003
+	 *
1004
+	 * @return boolean
1005
+	 */
1006
+	public function is_owned()
1007
+	{
1008
+		if ($this->model_chain_to_wp_user()) {
1009
+			return true;
1010
+		}
1011
+		try {
1012
+			$this->get_foreign_key_to('WP_User');
1013
+			return true;
1014
+		} catch (EE_Error $e) {
1015
+			return false;
1016
+		}
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1022
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1023
+	 * the model)
1024
+	 *
1025
+	 * @param array  $query_params      @see
1026
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1027
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1028
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1029
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1030
+	 *                                  override this and set the select to "*", or a specific column name, like
1031
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1032
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1033
+	 *                                  the aliases used to refer to this selection, and values are to be
1034
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1035
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1036
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1037
+	 * @throws EE_Error
1038
+	 * @throws InvalidArgumentException
1039
+	 */
1040
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1041
+	{
1042
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1043
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1044
+		$select_expressions       = $columns_to_select === null
1045
+			? $this->_construct_default_select_sql($model_query_info)
1046
+			: '';
1047
+		if ($this->_custom_selections instanceof CustomSelects) {
1048
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1049
+			$select_expressions .= $select_expressions
1050
+				? ', ' . $custom_expressions
1051
+				: $custom_expressions;
1052
+		}
1053
+
1054
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1055
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1061
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1062
+	 * method of including extra select information.
1063
+	 *
1064
+	 * @param array             $query_params
1065
+	 * @param null|array|string $columns_to_select
1066
+	 * @return null|CustomSelects
1067
+	 * @throws InvalidArgumentException
1068
+	 */
1069
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1070
+	{
1071
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1072
+			return null;
1073
+		}
1074
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1075
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1076
+		return new CustomSelects($selects);
1077
+	}
1078
+
1079
+
1080
+	/**
1081
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1082
+	 * but you can use the model query params to more easily
1083
+	 * take care of joins, field preparation etc.
1084
+	 *
1085
+	 * @param array  $query_params      @see
1086
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1087
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1088
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1089
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1090
+	 *                                  override this and set the select to "*", or a specific column name, like
1091
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1092
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1093
+	 *                                  the aliases used to refer to this selection, and values are to be
1094
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1095
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1096
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1097
+	 * @throws EE_Error
1098
+	 */
1099
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1100
+	{
1101
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * For creating a custom select statement
1107
+	 *
1108
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
+	 *                                 SQL, and 1=>is the datatype
1111
+	 * @return string
1112
+	 * @throws EE_Error
1113
+	 */
1114
+	private function _construct_select_from_input($columns_to_select)
1115
+	{
1116
+		if (is_array($columns_to_select)) {
1117
+			$select_sql_array = [];
1118
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
+					throw new EE_Error(
1121
+						sprintf(
1122
+							esc_html__(
1123
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
+								'event_espresso'
1125
+							),
1126
+							$selection_and_datatype,
1127
+							$alias
1128
+						)
1129
+					);
1130
+				}
1131
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype[1],
1139
+							$selection_and_datatype[0],
1140
+							$alias,
1141
+							implode(', ', $this->_valid_wpdb_data_types)
1142
+						)
1143
+					);
1144
+				}
1145
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
+			}
1147
+			$columns_to_select_string = implode(', ', $select_sql_array);
1148
+		} else {
1149
+			$columns_to_select_string = $columns_to_select;
1150
+		}
1151
+		return $columns_to_select_string;
1152
+	}
1153
+
1154
+
1155
+	/**
1156
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
+	 *
1158
+	 * @return string
1159
+	 * @throws EE_Error
1160
+	 */
1161
+	public function primary_key_name()
1162
+	{
1163
+		return $this->get_primary_key_field()->get_name();
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1169
+	 * If there is no primary key on this model, $id is treated as primary key string
1170
+	 *
1171
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1172
+	 * @return EE_Base_Class|mixed|null
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get_one_by_ID($id)
1176
+	{
1177
+		if ($this->get_from_entity_map($id)) {
1178
+			return $this->get_from_entity_map($id);
1179
+		}
1180
+		$model_object = $this->get_one(
1181
+			$this->alter_query_params_to_restrict_by_ID(
1182
+				$id,
1183
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1184
+			)
1185
+		);
1186
+		$className    = $this->_get_class_name();
1187
+		if ($model_object instanceof $className) {
1188
+			// make sure valid objects get added to the entity map
1189
+			// so that the next call to this method doesn't trigger another trip to the db
1190
+			$this->add_to_entity_map($model_object);
1191
+		}
1192
+		return $model_object;
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * Alters query parameters to only get items with this ID are returned.
1198
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1199
+	 * or could just be a simple primary key ID
1200
+	 *
1201
+	 * @param int   $id
1202
+	 * @param array $query_params
1203
+	 * @return array of normal query params, @see
1204
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1208
+	{
1209
+		if (! isset($query_params[0])) {
1210
+			$query_params[0] = [];
1211
+		}
1212
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1213
+		if ($conditions_from_id === null) {
1214
+			$query_params[0][ $this->primary_key_name() ] = $id;
1215
+		} else {
1216
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1217
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1218
+		}
1219
+		return $query_params;
1220
+	}
1221
+
1222
+
1223
+	/**
1224
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1225
+	 * array. If no item is found, null is returned.
1226
+	 *
1227
+	 * @param array $query_params like EEM_Base's $query_params variable.
1228
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1229
+	 * @throws EE_Error
1230
+	 */
1231
+	public function get_one($query_params = [])
1232
+	{
1233
+		if (! is_array($query_params)) {
1234
+			EE_Error::doing_it_wrong(
1235
+				'EEM_Base::get_one',
1236
+				sprintf(
1237
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1238
+					gettype($query_params)
1239
+				),
1240
+				'4.6.0'
1241
+			);
1242
+			$query_params = [];
1243
+		}
1244
+		$query_params['limit'] = 1;
1245
+		$items                 = $this->get_all($query_params);
1246
+		if (empty($items)) {
1247
+			return null;
1248
+		}
1249
+		return array_shift($items);
1250
+	}
1251
+
1252
+
1253
+	/**
1254
+	 * Returns the next x number of items in sequence from the given value as
1255
+	 * found in the database matching the given query conditions.
1256
+	 *
1257
+	 * @param mixed $current_field_value    Value used for the reference point.
1258
+	 * @param null  $field_to_order_by      What field is used for the
1259
+	 *                                      reference point.
1260
+	 * @param int   $limit                  How many to return.
1261
+	 * @param array $query_params           Extra conditions on the query.
1262
+	 * @param null  $columns_to_select      If left null, then an array of
1263
+	 *                                      EE_Base_Class objects is returned,
1264
+	 *                                      otherwise you can indicate just the
1265
+	 *                                      columns you want returned.
1266
+	 * @return EE_Base_Class[]|array
1267
+	 * @throws EE_Error
1268
+	 */
1269
+	public function next_x(
1270
+		$current_field_value,
1271
+		$field_to_order_by = null,
1272
+		$limit = 1,
1273
+		$query_params = [],
1274
+		$columns_to_select = null
1275
+	) {
1276
+		return $this->_get_consecutive(
1277
+			$current_field_value,
1278
+			'>',
1279
+			$field_to_order_by,
1280
+			$limit,
1281
+			$query_params,
1282
+			$columns_to_select
1283
+		);
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Returns the previous x number of items in sequence from the given value
1289
+	 * as found in the database matching the given query conditions.
1290
+	 *
1291
+	 * @param mixed $current_field_value    Value used for the reference point.
1292
+	 * @param null  $field_to_order_by      What field is used for the
1293
+	 *                                      reference point.
1294
+	 * @param int   $limit                  How many to return.
1295
+	 * @param array $query_params           Extra conditions on the query.
1296
+	 * @param null  $columns_to_select      If left null, then an array of
1297
+	 *                                      EE_Base_Class objects is returned,
1298
+	 *                                      otherwise you can indicate just the
1299
+	 *                                      columns you want returned.
1300
+	 * @return EE_Base_Class[]|array
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public function previous_x(
1304
+		$current_field_value,
1305
+		$field_to_order_by = null,
1306
+		$limit = 1,
1307
+		$query_params = [],
1308
+		$columns_to_select = null
1309
+	) {
1310
+		return $this->_get_consecutive(
1311
+			$current_field_value,
1312
+			'<',
1313
+			$field_to_order_by,
1314
+			$limit,
1315
+			$query_params,
1316
+			$columns_to_select
1317
+		);
1318
+	}
1319
+
1320
+
1321
+	/**
1322
+	 * Returns the next item in sequence from the given value as found in the
1323
+	 * database matching the given query conditions.
1324
+	 *
1325
+	 * @param mixed $current_field_value    Value used for the reference point.
1326
+	 * @param null  $field_to_order_by      What field is used for the
1327
+	 *                                      reference point.
1328
+	 * @param array $query_params           Extra conditions on the query.
1329
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1330
+	 *                                      object is returned, otherwise you
1331
+	 *                                      can indicate just the columns you
1332
+	 *                                      want and a single array indexed by
1333
+	 *                                      the columns will be returned.
1334
+	 * @return EE_Base_Class|null|array()
1335
+	 * @throws EE_Error
1336
+	 */
1337
+	public function next(
1338
+		$current_field_value,
1339
+		$field_to_order_by = null,
1340
+		$query_params = [],
1341
+		$columns_to_select = null
1342
+	) {
1343
+		$results = $this->_get_consecutive(
1344
+			$current_field_value,
1345
+			'>',
1346
+			$field_to_order_by,
1347
+			1,
1348
+			$query_params,
1349
+			$columns_to_select
1350
+		);
1351
+		return empty($results) ? null : reset($results);
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * Returns the previous item in sequence from the given value as found in
1357
+	 * the database matching the given query conditions.
1358
+	 *
1359
+	 * @param mixed $current_field_value    Value used for the reference point.
1360
+	 * @param null  $field_to_order_by      What field is used for the
1361
+	 *                                      reference point.
1362
+	 * @param array $query_params           Extra conditions on the query.
1363
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1364
+	 *                                      object is returned, otherwise you
1365
+	 *                                      can indicate just the columns you
1366
+	 *                                      want and a single array indexed by
1367
+	 *                                      the columns will be returned.
1368
+	 * @return EE_Base_Class|null|array()
1369
+	 * @throws EE_Error
1370
+	 */
1371
+	public function previous(
1372
+		$current_field_value,
1373
+		$field_to_order_by = null,
1374
+		$query_params = [],
1375
+		$columns_to_select = null
1376
+	) {
1377
+		$results = $this->_get_consecutive(
1378
+			$current_field_value,
1379
+			'<',
1380
+			$field_to_order_by,
1381
+			1,
1382
+			$query_params,
1383
+			$columns_to_select
1384
+		);
1385
+		return empty($results) ? null : reset($results);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * Returns the a consecutive number of items in sequence from the given
1391
+	 * value as found in the database matching the given query conditions.
1392
+	 *
1393
+	 * @param mixed  $current_field_value   Value used for the reference point.
1394
+	 * @param string $operand               What operand is used for the sequence.
1395
+	 * @param string $field_to_order_by     What field is used for the reference point.
1396
+	 * @param int    $limit                 How many to return.
1397
+	 * @param array  $query_params          Extra conditions on the query.
1398
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1399
+	 *                                      otherwise you can indicate just the columns you want returned.
1400
+	 * @return EE_Base_Class[]|array
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	protected function _get_consecutive(
1404
+		$current_field_value,
1405
+		$operand = '>',
1406
+		$field_to_order_by = null,
1407
+		$limit = 1,
1408
+		$query_params = [],
1409
+		$columns_to_select = null
1410
+	) {
1411
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1412
+		if (empty($field_to_order_by)) {
1413
+			if ($this->has_primary_key_field()) {
1414
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1415
+			} else {
1416
+				if (WP_DEBUG) {
1417
+					throw new EE_Error(
1418
+						esc_html__(
1419
+							'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).',
1420
+							'event_espresso'
1421
+						)
1422
+					);
1423
+				}
1424
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1425
+				return [];
1426
+			}
1427
+		}
1428
+		if (! is_array($query_params)) {
1429
+			EE_Error::doing_it_wrong(
1430
+				'EEM_Base::_get_consecutive',
1431
+				sprintf(
1432
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1433
+					gettype($query_params)
1434
+				),
1435
+				'4.6.0'
1436
+			);
1437
+			$query_params = [];
1438
+		}
1439
+		// let's add the where query param for consecutive look up.
1440
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1441
+		$query_params['limit']                 = $limit;
1442
+		// set direction
1443
+		$incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1444
+		$query_params['order_by'] = $operand === '>'
1445
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1446
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1447
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1448
+		if (empty($columns_to_select)) {
1449
+			return $this->get_all($query_params);
1450
+		}
1451
+		// getting just the fields
1452
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1453
+	}
1454
+
1455
+
1456
+	/**
1457
+	 * This sets the _timezone property after model object has been instantiated.
1458
+	 *
1459
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
+	 */
1461
+	public function set_timezone($timezone)
1462
+	{
1463
+		if ($timezone !== null) {
1464
+			$this->_timezone = $timezone;
1465
+		}
1466
+		// note we need to loop through relations and set the timezone on those objects as well.
1467
+		foreach ($this->_model_relations as $relation) {
1468
+			$relation->set_timezone($timezone);
1469
+		}
1470
+		// and finally we do the same for any datetime fields
1471
+		foreach ($this->_fields as $field) {
1472
+			if ($field instanceof EE_Datetime_Field) {
1473
+				$field->set_timezone($timezone);
1474
+			}
1475
+		}
1476
+	}
1477
+
1478
+
1479
+	/**
1480
+	 * This just returns whatever is set for the current timezone.
1481
+	 *
1482
+	 * @access public
1483
+	 * @return string
1484
+	 */
1485
+	public function get_timezone()
1486
+	{
1487
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1488
+		if (empty($this->_timezone)) {
1489
+			foreach ($this->_fields as $field) {
1490
+				if ($field instanceof EE_Datetime_Field) {
1491
+					$this->set_timezone($field->get_timezone());
1492
+					break;
1493
+				}
1494
+			}
1495
+		}
1496
+		// if timezone STILL empty then return the default timezone for the site.
1497
+		if (empty($this->_timezone)) {
1498
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1499
+		}
1500
+		return $this->_timezone;
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * This returns the date formats set for the given field name and also ensures that
1506
+	 * $this->_timezone property is set correctly.
1507
+	 *
1508
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1509
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1510
+	 * @return array formats in an array with the date format first, and the time format last.
1511
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1512
+	 * @since 4.6.x
1513
+	 */
1514
+	public function get_formats_for($field_name, $pretty = false)
1515
+	{
1516
+		$field_settings = $this->field_settings_for($field_name);
1517
+		// if not a valid EE_Datetime_Field then throw error
1518
+		if (! $field_settings instanceof EE_Datetime_Field) {
1519
+			throw new EE_Error(
1520
+				sprintf(
1521
+					esc_html__(
1522
+						'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.',
1523
+						'event_espresso'
1524
+					),
1525
+					$field_name
1526
+				)
1527
+			);
1528
+		}
1529
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1530
+		// the field.
1531
+		$this->_timezone = $field_settings->get_timezone();
1532
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1533
+	}
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 *
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1553
+	 *                                 exception is triggered.
1554
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1555
+	 * @since 4.6.x
1556
+	 */
1557
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1558
+	{
1559
+		$formats  = $this->get_formats_for($field_name);
1560
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1561
+		if ($timestamp) {
1562
+			return $DateTime->format('U');
1563
+		}
1564
+		// not returning timestamp, so return formatted string in timezone.
1565
+		switch ($what) {
1566
+			case 'time':
1567
+				return $DateTime->format($formats[1]);
1568
+				break;
1569
+			case 'date':
1570
+				return $DateTime->format($formats[0]);
1571
+				break;
1572
+			default:
1573
+				return $DateTime->format(implode(' ', $formats));
1574
+				break;
1575
+		}
1576
+	}
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		// just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		// load EEH_DTT_Helper
1601
+		$set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
+	}
1606
+
1607
+
1608
+	/**
1609
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
+	 *
1611
+	 * @return EE_Table_Base[]
1612
+	 */
1613
+	public function get_tables()
1614
+	{
1615
+		return $this->_tables;
1616
+	}
1617
+
1618
+
1619
+	/**
1620
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1621
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1622
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1623
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1624
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1625
+	 * model object with EVT_ID = 1
1626
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1627
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1628
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1629
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1630
+	 * are not specified)
1631
+	 *
1632
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1633
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1634
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1635
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1636
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1637
+	 *                                         ID=34, we'd use this method as follows:
1638
+	 *                                         EEM_Transaction::instance()->update(
1639
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1640
+	 *                                         array(array('TXN_ID'=>34)));
1641
+	 * @param array   $query_params            @see
1642
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1643
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1644
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1645
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1646
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1647
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1648
+	 *                                         TRUE, it is assumed that you've already called
1649
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1650
+	 *                                         malicious javascript. However, if
1651
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1652
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1653
+	 *                                         and every other field, before insertion. We provide this parameter
1654
+	 *                                         because model objects perform their prepare_for_set function on all
1655
+	 *                                         their values, and so don't need to be called again (and in many cases,
1656
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1657
+	 *                                         prepare_for_set method...)
1658
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1659
+	 *                                         in this model's entity map according to $fields_n_values that match
1660
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1661
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1662
+	 *                                         could get out-of-sync with the database
1663
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1664
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1665
+	 *                                         bad)
1666
+	 * @throws EE_Error
1667
+	 */
1668
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1669
+	{
1670
+		if (! is_array($query_params)) {
1671
+			EE_Error::doing_it_wrong(
1672
+				'EEM_Base::update',
1673
+				sprintf(
1674
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
+					gettype($query_params)
1676
+				),
1677
+				'4.6.0'
1678
+			);
1679
+			$query_params = [];
1680
+		}
1681
+		/**
1682
+		 * Action called before a model update call has been made.
1683
+		 *
1684
+		 * @param EEM_Base $model
1685
+		 * @param array    $fields_n_values the updated fields and their new values
1686
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1687
+		 */
1688
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1689
+		/**
1690
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1691
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1692
+		 *
1693
+		 * @param array    $fields_n_values fields and their new values
1694
+		 * @param EEM_Base $model           the model being queried
1695
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1696
+		 */
1697
+		$fields_n_values = (array) apply_filters(
1698
+			'FHEE__EEM_Base__update__fields_n_values',
1699
+			$fields_n_values,
1700
+			$this,
1701
+			$query_params
1702
+		);
1703
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1704
+		// to do that, for each table, verify that it's PK isn't null.
1705
+		$tables = $this->get_tables();
1706
+		// 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
1707
+		// NOTE: we should make this code more efficient by NOT querying twice
1708
+		// before the real update, but that needs to first go through ALPHA testing
1709
+		// as it's dangerous. says Mike August 8 2014
1710
+		// we want to make sure the default_where strategy is ignored
1711
+		$this->_ignore_where_strategy = true;
1712
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1713
+		foreach ($wpdb_select_results as $wpdb_result) {
1714
+			// type cast stdClass as array
1715
+			$wpdb_result = (array) $wpdb_result;
1716
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1717
+			if ($this->has_primary_key_field()) {
1718
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1719
+			} else {
1720
+				// 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)
1721
+				$main_table_pk_value = null;
1722
+			}
1723
+			// 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
1724
+			// 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
1725
+			if (count($tables) > 1) {
1726
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1727
+				// in that table, and so we'll want to insert one
1728
+				foreach ($tables as $table_obj) {
1729
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1730
+					// if there is no private key for this table on the results, it means there's no entry
1731
+					// in this table, right? so insert a row in the current table, using any fields available
1732
+					if (
1733
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1734
+						   && $wpdb_result[ $this_table_pk_column ])
1735
+					) {
1736
+						$success = $this->_insert_into_specific_table(
1737
+							$table_obj,
1738
+							$fields_n_values,
1739
+							$main_table_pk_value
1740
+						);
1741
+						// if we died here, report the error
1742
+						if (! $success) {
1743
+							return false;
1744
+						}
1745
+					}
1746
+				}
1747
+			}
1748
+			//              //and now check that if we have cached any models by that ID on the model, that
1749
+			//              //they also get updated properly
1750
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1751
+			//              if( $model_object ){
1752
+			//                  foreach( $fields_n_values as $field => $value ){
1753
+			//                      $model_object->set($field, $value);
1754
+			// let's make sure default_where strategy is followed now
1755
+			$this->_ignore_where_strategy = false;
1756
+		}
1757
+		// if we want to keep model objects in sync, AND
1758
+		// if this wasn't called from a model object (to update itself)
1759
+		// then we want to make sure we keep all the existing
1760
+		// model objects in sync with the db
1761
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1762
+			if ($this->has_primary_key_field()) {
1763
+				$model_objs_affected_ids = $this->get_col($query_params);
1764
+			} else {
1765
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1766
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1767
+				$model_objs_affected_ids     = [];
1768
+				foreach ($models_affected_key_columns as $row) {
1769
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1770
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1771
+				}
1772
+			}
1773
+			if (! $model_objs_affected_ids) {
1774
+				// wait wait wait- if nothing was affected let's stop here
1775
+				return 0;
1776
+			}
1777
+			foreach ($model_objs_affected_ids as $id) {
1778
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1779
+				if ($model_obj_in_entity_map) {
1780
+					foreach ($fields_n_values as $field => $new_value) {
1781
+						$model_obj_in_entity_map->set($field, $new_value);
1782
+					}
1783
+				}
1784
+			}
1785
+			// if there is a primary key on this model, we can now do a slight optimization
1786
+			if ($this->has_primary_key_field()) {
1787
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1788
+				$query_params = [
1789
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1790
+					'limit'                    => count($model_objs_affected_ids),
1791
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1792
+				];
1793
+			}
1794
+		}
1795
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
+
1797
+		$SQL = "UPDATE {$model_query_info->get_full_join_sql()} 
1798 1798
                 SET {$this->_construct_update_sql($fields_n_values)}
1799 1799
                 {$model_query_info->get_where_sql()}";
1800
-        // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1801
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1802
-        /**
1803
-         * Action called after a model update call has been made.
1804
-         *
1805
-         * @param EEM_Base $model
1806
-         * @param array    $fields_n_values the updated fields and their new values
1807
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1808
-         * @param int      $rows_affected
1809
-         */
1810
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1811
-        return $rows_affected;// how many supposedly got updated
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1817
-     * are teh values of the field specified (or by default the primary key field)
1818
-     * that matched the query params. Note that you should pass the name of the
1819
-     * model FIELD, not the database table's column name.
1820
-     *
1821
-     * @param array  $query_params @see
1822
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1823
-     * @param string $field_to_select
1824
-     * @return array just like $wpdb->get_col()
1825
-     * @throws EE_Error
1826
-     */
1827
-    public function get_col($query_params = [], $field_to_select = null)
1828
-    {
1829
-        if ($field_to_select) {
1830
-            $field = $this->field_settings_for($field_to_select);
1831
-        } elseif ($this->has_primary_key_field()) {
1832
-            $field = $this->get_primary_key_field();
1833
-        } else {
1834
-            // no primary key, just grab the first column
1835
-            $field_settings = $this->field_settings();
1836
-            $field          = reset($field_settings);
1837
-        }
1838
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1839
-        $select_expressions = $field->get_qualified_column();
1840
-        $SQL                =
1841
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1842
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1843
-    }
1844
-
1845
-
1846
-    /**
1847
-     * Returns a single column value for a single row from the database
1848
-     *
1849
-     * @param array  $query_params    @see
1850
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1851
-     * @param string $field_to_select @see EEM_Base::get_col()
1852
-     * @return string
1853
-     * @throws EE_Error
1854
-     */
1855
-    public function get_var($query_params = [], $field_to_select = null)
1856
-    {
1857
-        $query_params['limit'] = 1;
1858
-        $col                   = $this->get_col($query_params, $field_to_select);
1859
-        if (! empty($col)) {
1860
-            return reset($col);
1861
-        }
1862
-        return null;
1863
-    }
1864
-
1865
-
1866
-    /**
1867
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1868
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1869
-     * injection, but currently no further filtering is done
1870
-     *
1871
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1872
-     *                               be updated to in the DB
1873
-     * @return string of SQL
1874
-     * @throws EE_Error
1875
-     * @global      $wpdb
1876
-     */
1877
-    public function _construct_update_sql($fields_n_values)
1878
-    {
1879
-        /** @type WPDB $wpdb */
1880
-        global $wpdb;
1881
-        $cols_n_values = [];
1882
-        foreach ($fields_n_values as $field_name => $value) {
1883
-            $field_obj = $this->field_settings_for($field_name);
1884
-            // if the value is NULL, we want to assign the value to that.
1885
-            // wpdb->prepare doesn't really handle that properly
1886
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1887
-            $value_sql       = $prepared_value === null ? 'NULL'
1888
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1889
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1890
-        }
1891
-        return implode(",", $cols_n_values);
1892
-    }
1893
-
1894
-
1895
-    /**
1896
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1897
-     * Performs a HARD delete, meaning the database row should always be removed,
1898
-     * not just have a flag field on it switched
1899
-     * Wrapper for EEM_Base::delete_permanently()
1900
-     *
1901
-     * @param mixed   $id
1902
-     * @param boolean $allow_blocking
1903
-     * @return int the number of rows deleted
1904
-     * @throws EE_Error
1905
-     */
1906
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1907
-    {
1908
-        return $this->delete_permanently(
1909
-            [
1910
-                [$this->get_primary_key_field()->get_name() => $id],
1911
-                'limit' => 1,
1912
-            ],
1913
-            $allow_blocking
1914
-        );
1915
-    }
1916
-
1917
-
1918
-    /**
1919
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1920
-     * Wrapper for EEM_Base::delete()
1921
-     *
1922
-     * @param mixed   $id
1923
-     * @param boolean $allow_blocking
1924
-     * @return int the number of rows deleted
1925
-     * @throws EE_Error
1926
-     */
1927
-    public function delete_by_ID($id, $allow_blocking = true)
1928
-    {
1929
-        return $this->delete(
1930
-            [
1931
-                [$this->get_primary_key_field()->get_name() => $id],
1932
-                'limit' => 1,
1933
-            ],
1934
-            $allow_blocking
1935
-        );
1936
-    }
1937
-
1938
-
1939
-    /**
1940
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1941
-     * meaning if the model has a field that indicates its been "trashed" or
1942
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1943
-     *
1944
-     * @param array   $query_params
1945
-     * @param boolean $allow_blocking
1946
-     * @return int how many rows got deleted
1947
-     * @throws EE_Error
1948
-     * @see EEM_Base::delete_permanently
1949
-     */
1950
-    public function delete($query_params, $allow_blocking = true)
1951
-    {
1952
-        return $this->delete_permanently($query_params, $allow_blocking);
1953
-    }
1954
-
1955
-
1956
-    /**
1957
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1958
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1959
-     * as archived, not actually deleted
1960
-     *
1961
-     * @param array   $query_params   @see
1962
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1963
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1964
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1965
-     *                                deletes regardless of other objects which may depend on it. Its generally
1966
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1967
-     *                                DB
1968
-     * @return int how many rows got deleted
1969
-     * @throws EE_Error
1970
-     */
1971
-    public function delete_permanently($query_params, $allow_blocking = true)
1972
-    {
1973
-        /**
1974
-         * Action called just before performing a real deletion query. You can use the
1975
-         * model and its $query_params to find exactly which items will be deleted
1976
-         *
1977
-         * @param EEM_Base $model
1978
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1979
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1980
-         *                                 to block (prevent) this deletion
1981
-         */
1982
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1983
-        // some MySQL databases may be running safe mode, which may restrict
1984
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1985
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1986
-        // to delete them
1987
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1988
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1989
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1990
-            $columns_and_ids_for_deleting
1991
-        );
1992
-        /**
1993
-         * Allows client code to act on the items being deleted before the query is actually executed.
1994
-         *
1995
-         * @param EEM_Base $this                            The model instance being acted on.
1996
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1997
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1998
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1999
-         *                                                  derived from the incoming query parameters.
2000
-         * @see details on the structure of this array in the phpdocs
2001
-         *                                                  for the `_get_ids_for_delete_method`
2002
-         *
2003
-         */
2004
-        do_action(
2005
-            'AHEE__EEM_Base__delete__before_query',
2006
-            $this,
2007
-            $query_params,
2008
-            $allow_blocking,
2009
-            $columns_and_ids_for_deleting
2010
-        );
2011
-        if ($deletion_where_query_part) {
2012
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2013
-            $table_aliases    = array_keys($this->_tables);
2014
-            $SQL              = "DELETE "
2015
-                                . implode(", ", $table_aliases)
2016
-                                . " FROM "
2017
-                                . $model_query_info->get_full_join_sql()
2018
-                                . " WHERE "
2019
-                                . $deletion_where_query_part;
2020
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2021
-        } else {
2022
-            $rows_deleted = 0;
2023
-        }
2024
-
2025
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2026
-        // there was no error with the delete query.
2027
-        if (
2028
-            $this->has_primary_key_field()
2029
-            && $rows_deleted !== false
2030
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2031
-        ) {
2032
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2033
-            foreach ($ids_for_removal as $id) {
2034
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2035
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2036
-                }
2037
-            }
2038
-
2039
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2040
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2041
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2042
-            // (although it is possible).
2043
-            // Note this can be skipped by using the provided filter and returning false.
2044
-            if (
2045
-                apply_filters(
2046
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2047
-                    ! $this instanceof EEM_Extra_Meta,
2048
-                    $this
2049
-                )
2050
-            ) {
2051
-                EEM_Extra_Meta::instance()->delete_permanently([
2052
-                                                                   0 => [
2053
-                                                                       'EXM_type' => $this->get_this_model_name(),
2054
-                                                                       'OBJ_ID'   => [
2055
-                                                                           'IN',
2056
-                                                                           $ids_for_removal,
2057
-                                                                       ],
2058
-                                                                   ],
2059
-                                                               ]);
2060
-            }
2061
-        }
2062
-
2063
-        /**
2064
-         * Action called just after performing a real deletion query. Although at this point the
2065
-         * items should have been deleted
2066
-         *
2067
-         * @param EEM_Base $model
2068
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2069
-         * @param int      $rows_deleted
2070
-         */
2071
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2072
-        return $rows_deleted;// how many supposedly got deleted
2073
-    }
2074
-
2075
-
2076
-    /**
2077
-     * Checks all the relations that throw error messages when there are blocking related objects
2078
-     * for related model objects. If there are any related model objects on those relations,
2079
-     * adds an EE_Error, and return true
2080
-     *
2081
-     * @param EE_Base_Class|int $this_model_obj_or_id
2082
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2083
-     *                                                 should be ignored when determining whether there are related
2084
-     *                                                 model objects which block this model object's deletion. Useful
2085
-     *                                                 if you know A is related to B and are considering deleting A,
2086
-     *                                                 but want to see if A has any other objects blocking its deletion
2087
-     *                                                 before removing the relation between A and B
2088
-     * @return boolean
2089
-     * @throws EE_Error
2090
-     */
2091
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2092
-    {
2093
-        // first, if $ignore_this_model_obj was supplied, get its model
2094
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2095
-            $ignored_model = $ignore_this_model_obj->get_model();
2096
-        } else {
2097
-            $ignored_model = null;
2098
-        }
2099
-        // now check all the relations of $this_model_obj_or_id and see if there
2100
-        // are any related model objects blocking it?
2101
-        $is_blocked = false;
2102
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2103
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2104
-                // if $ignore_this_model_obj was supplied, then for the query
2105
-                // on that model needs to be told to ignore $ignore_this_model_obj
2106
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2107
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2108
-                        [
2109
-                            $ignored_model->get_primary_key_field()->get_name() => [
2110
-                                '!=',
2111
-                                $ignore_this_model_obj->ID(),
2112
-                            ],
2113
-                        ],
2114
-                    ]);
2115
-                } else {
2116
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2117
-                }
2118
-                if ($related_model_objects) {
2119
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2120
-                    $is_blocked = true;
2121
-                }
2122
-            }
2123
-        }
2124
-        return $is_blocked;
2125
-    }
2126
-
2127
-
2128
-    /**
2129
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2130
-     *
2131
-     * @param array $row_results_for_deleting
2132
-     * @param bool  $allow_blocking
2133
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2134
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2135
-     *                              dimension array where the key is the fully qualified primary key column and the
2136
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2137
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2138
-     *                              be a two dimensional array where each element is a group of columns and values that
2139
-     *                              get deleted. Example: array(
2140
-     *                              0 => array(
2141
-     *                              'Term_Relationship.object_id' => 1
2142
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2143
-     *                              ),
2144
-     *                              1 => array(
2145
-     *                              'Term_Relationship.object_id' => 1
2146
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2147
-     *                              )
2148
-     *                              )
2149
-     * @throws EE_Error
2150
-     */
2151
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2152
-    {
2153
-        $ids_to_delete_indexed_by_column = [];
2154
-        if ($this->has_primary_key_field()) {
2155
-            $primary_table                   = $this->_get_main_table();
2156
-            $primary_table_pk_field          =
2157
-                $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2158
-            $other_tables                    = $this->_get_other_tables();
2159
-            $ids_to_delete_indexed_by_column = $query = [];
2160
-            foreach ($row_results_for_deleting as $item_to_delete) {
2161
-                // before we mark this item for deletion,
2162
-                // make sure there's no related entities blocking its deletion (if we're checking)
2163
-                if (
2164
-                    $allow_blocking
2165
-                    && $this->delete_is_blocked_by_related_models(
2166
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2167
-                    )
2168
-                ) {
2169
-                    continue;
2170
-                }
2171
-                // primary table deletes
2172
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2173
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2174
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2175
-                }
2176
-            }
2177
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
-            $fields = $this->get_combined_primary_key_fields();
2179
-            foreach ($row_results_for_deleting as $item_to_delete) {
2180
-                $ids_to_delete_indexed_by_column_for_row = [];
2181
-                foreach ($fields as $cpk_field) {
2182
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2183
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2184
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2185
-                    }
2186
-                }
2187
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2188
-            }
2189
-        } else {
2190
-            // so there's no primary key and no combined key...
2191
-            // sorry, can't help you
2192
-            throw new EE_Error(
2193
-                sprintf(
2194
-                    esc_html__(
2195
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2196
-                        "event_espresso"
2197
-                    ),
2198
-                    get_class($this)
2199
-                )
2200
-            );
2201
-        }
2202
-        return $ids_to_delete_indexed_by_column;
2203
-    }
2204
-
2205
-
2206
-    /**
2207
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2208
-     * the corresponding query_part for the query performing the delete.
2209
-     *
2210
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2211
-     * @return string
2212
-     * @throws EE_Error
2213
-     */
2214
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2215
-    {
2216
-        $query_part = '';
2217
-        if (empty($ids_to_delete_indexed_by_column)) {
2218
-            return $query_part;
2219
-        } elseif ($this->has_primary_key_field()) {
2220
-            $query = [];
2221
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2222
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2223
-            }
2224
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2225
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2226
-            $ways_to_identify_a_row = [];
2227
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2228
-                $values_for_each_combined_primary_key_for_a_row = [];
2229
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2230
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2231
-                }
2232
-                $ways_to_identify_a_row[] = '('
2233
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2234
-                                            . ')';
2235
-            }
2236
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2237
-        }
2238
-        return $query_part;
2239
-    }
2240
-
2241
-
2242
-    /**
2243
-     * Gets the model field by the fully qualified name
2244
-     *
2245
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2246
-     * @return EE_Model_Field_Base
2247
-     */
2248
-    public function get_field_by_column($qualified_column_name)
2249
-    {
2250
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2251
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2252
-                return $field_obj;
2253
-            }
2254
-        }
2255
-        throw new EE_Error(
2256
-            sprintf(
2257
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2258
-                $this->get_this_model_name(),
2259
-                $qualified_column_name
2260
-            )
2261
-        );
2262
-    }
2263
-
2264
-
2265
-    /**
2266
-     * Count all the rows that match criteria the model query params.
2267
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2268
-     * column
2269
-     *
2270
-     * @param array  $query_params   @see
2271
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
-     * @param string $field_to_count field on model to count by (not column name)
2273
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2274
-     *                               that by the setting $distinct to TRUE;
2275
-     * @return int
2276
-     * @throws EE_Error
2277
-     */
2278
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2279
-    {
2280
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2281
-        if ($field_to_count) {
2282
-            $field_obj       = $this->field_settings_for($field_to_count);
2283
-            $column_to_count = $field_obj->get_qualified_column();
2284
-        } elseif ($this->has_primary_key_field()) {
2285
-            $pk_field_obj    = $this->get_primary_key_field();
2286
-            $column_to_count = $pk_field_obj->get_qualified_column();
2287
-        } else {
2288
-            // there's no primary key
2289
-            // if we're counting distinct items, and there's no primary key,
2290
-            // we need to list out the columns for distinction;
2291
-            // otherwise we can just use star
2292
-            if ($distinct) {
2293
-                $columns_to_use = [];
2294
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2295
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2296
-                }
2297
-                $column_to_count = implode(',', $columns_to_use);
2298
-            } else {
2299
-                $column_to_count = '*';
2300
-            }
2301
-        }
2302
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2303
-        $SQL             =
2304
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2305
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2306
-    }
2307
-
2308
-
2309
-    /**
2310
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2311
-     *
2312
-     * @param array  $query_params @see
2313
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2314
-     * @param string $field_to_sum name of field (array key in $_fields array)
2315
-     * @return float
2316
-     * @throws EE_Error
2317
-     */
2318
-    public function sum($query_params, $field_to_sum = null)
2319
-    {
2320
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2321
-        if ($field_to_sum) {
2322
-            $field_obj = $this->field_settings_for($field_to_sum);
2323
-        } else {
2324
-            $field_obj = $this->get_primary_key_field();
2325
-        }
2326
-        $column_to_count = $field_obj->get_qualified_column();
2327
-        $SQL             =
2328
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2329
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2330
-        $data_type       = $field_obj->get_wpdb_data_type();
2331
-        if ($data_type === '%d' || $data_type === '%s') {
2332
-            return (float) $return_value;
2333
-        }
2334
-        // must be %f
2335
-        return (float) $return_value;
2336
-    }
2337
-
2338
-
2339
-    /**
2340
-     * Just calls the specified method on $wpdb with the given arguments
2341
-     * Consolidates a little extra error handling code
2342
-     *
2343
-     * @param string $wpdb_method
2344
-     * @param array  $arguments_to_provide
2345
-     * @return mixed
2346
-     * @throws EE_Error
2347
-     * @global wpdb  $wpdb
2348
-     */
2349
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2350
-    {
2351
-        // if we're in maintenance mode level 2, DON'T run any queries
2352
-        // because level 2 indicates the database needs updating and
2353
-        // is probably out of sync with the code
2354
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2355
-            throw new EE_Error(
2356
-                sprintf(
2357
-                    esc_html__(
2358
-                        "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.",
2359
-                        "event_espresso"
2360
-                    )
2361
-                )
2362
-            );
2363
-        }
2364
-        /** @type WPDB $wpdb */
2365
-        global $wpdb;
2366
-        if (! method_exists($wpdb, $wpdb_method)) {
2367
-            throw new EE_Error(
2368
-                sprintf(
2369
-                    esc_html__(
2370
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2371
-                        'event_espresso'
2372
-                    ),
2373
-                    $wpdb_method
2374
-                )
2375
-            );
2376
-        }
2377
-        if (WP_DEBUG) {
2378
-            $old_show_errors_value = $wpdb->show_errors;
2379
-            $wpdb->show_errors(false);
2380
-        }
2381
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2382
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2383
-        if (WP_DEBUG) {
2384
-            $wpdb->show_errors($old_show_errors_value);
2385
-            if (! empty($wpdb->last_error)) {
2386
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2387
-            }
2388
-            if ($result === false) {
2389
-                throw new EE_Error(
2390
-                    sprintf(
2391
-                        esc_html__(
2392
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2393
-                            'event_espresso'
2394
-                        ),
2395
-                        $wpdb_method,
2396
-                        var_export($arguments_to_provide, true)
2397
-                    )
2398
-                );
2399
-            }
2400
-        } elseif ($result === false) {
2401
-            EE_Error::add_error(
2402
-                sprintf(
2403
-                    esc_html__(
2404
-                        '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"',
2405
-                        'event_espresso'
2406
-                    ),
2407
-                    $wpdb_method,
2408
-                    var_export($arguments_to_provide, true),
2409
-                    $wpdb->last_error
2410
-                ),
2411
-                __FILE__,
2412
-                __FUNCTION__,
2413
-                __LINE__
2414
-            );
2415
-        }
2416
-        return $result;
2417
-    }
2418
-
2419
-
2420
-    /**
2421
-     * Attempts to run the indicated WPDB method with the provided arguments,
2422
-     * and if there's an error tries to verify the DB is correct. Uses
2423
-     * the static property EEM_Base::$_db_verification_level to determine whether
2424
-     * we should try to fix the EE core db, the addons, or just give up
2425
-     *
2426
-     * @param string $wpdb_method
2427
-     * @param array  $arguments_to_provide
2428
-     * @return mixed
2429
-     */
2430
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2431
-    {
2432
-        /** @type WPDB $wpdb */
2433
-        global $wpdb;
2434
-        $wpdb->last_error = null;
2435
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2436
-        // was there an error running the query? but we don't care on new activations
2437
-        // (we're going to setup the DB anyway on new activations)
2438
-        if (
2439
-            ($result === false || ! empty($wpdb->last_error))
2440
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2441
-        ) {
2442
-            switch (EEM_Base::$_db_verification_level) {
2443
-                case EEM_Base::db_verified_none:
2444
-                    // let's double-check core's DB
2445
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2446
-                    break;
2447
-                case EEM_Base::db_verified_core:
2448
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2449
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2450
-                    break;
2451
-                case EEM_Base::db_verified_addons:
2452
-                    // ummmm... you in trouble
2453
-                    return $result;
2454
-                    break;
2455
-            }
2456
-            if (! empty($error_message)) {
2457
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2458
-                trigger_error($error_message);
2459
-            }
2460
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2461
-        }
2462
-        return $result;
2463
-    }
2464
-
2465
-
2466
-    /**
2467
-     * Verifies the EE core database is up-to-date and records that we've done it on
2468
-     * EEM_Base::$_db_verification_level
2469
-     *
2470
-     * @param string $wpdb_method
2471
-     * @param array  $arguments_to_provide
2472
-     * @return string
2473
-     */
2474
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2475
-    {
2476
-        /** @type WPDB $wpdb */
2477
-        global $wpdb;
2478
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2479
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2480
-        $error_message                    = sprintf(
2481
-            esc_html__(
2482
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2483
-                'event_espresso'
2484
-            ),
2485
-            $wpdb->last_error,
2486
-            $wpdb_method,
2487
-            wp_json_encode($arguments_to_provide)
2488
-        );
2489
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2490
-        return $error_message;
2491
-    }
2492
-
2493
-
2494
-    /**
2495
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2496
-     * EEM_Base::$_db_verification_level
2497
-     *
2498
-     * @param $wpdb_method
2499
-     * @param $arguments_to_provide
2500
-     * @return string
2501
-     */
2502
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2503
-    {
2504
-        /** @type WPDB $wpdb */
2505
-        global $wpdb;
2506
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2507
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2508
-        $error_message                    = sprintf(
2509
-            esc_html__(
2510
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2511
-                'event_espresso'
2512
-            ),
2513
-            $wpdb->last_error,
2514
-            $wpdb_method,
2515
-            wp_json_encode($arguments_to_provide)
2516
-        );
2517
-        EE_System::instance()->initialize_addons();
2518
-        return $error_message;
2519
-    }
2520
-
2521
-
2522
-    /**
2523
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2524
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2525
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2526
-     * ..."
2527
-     *
2528
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2529
-     * @return string
2530
-     */
2531
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2532
-    {
2533
-        return " FROM " . $model_query_info->get_full_join_sql() .
2534
-               $model_query_info->get_where_sql() .
2535
-               $model_query_info->get_group_by_sql() .
2536
-               $model_query_info->get_having_sql() .
2537
-               $model_query_info->get_order_by_sql() .
2538
-               $model_query_info->get_limit_sql();
2539
-    }
2540
-
2541
-
2542
-    /**
2543
-     * Set to easily debug the next X queries ran from this model.
2544
-     *
2545
-     * @param int $count
2546
-     */
2547
-    public function show_next_x_db_queries($count = 1)
2548
-    {
2549
-        $this->_show_next_x_db_queries = $count;
2550
-    }
2551
-
2552
-
2553
-    /**
2554
-     * @param $sql_query
2555
-     */
2556
-    public function show_db_query_if_previously_requested($sql_query)
2557
-    {
2558
-        if ($this->_show_next_x_db_queries > 0) {
2559
-            echo esc_html($sql_query);
2560
-            $this->_show_next_x_db_queries--;
2561
-        }
2562
-    }
2563
-
2564
-
2565
-    /**
2566
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
-     * There are the 3 cases:
2568
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
-     * $otherModelObject has no ID, it is first saved.
2570
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
-     * has no ID, it is first saved.
2572
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
-     * join table
2575
-     *
2576
-     * @param EE_Base_Class                     /int $thisModelObject
2577
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
-     * @param string $relationName                     , key in EEM_Base::_relations
2579
-     *                                                 an attendee to a group, you also want to specify which role they
2580
-     *                                                 will have in that group. So you would use this parameter to
2581
-     *                                                 specify array('role-column-name'=>'role-id')
2582
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
-     *                                                 to for relation to methods that allow you to further specify
2584
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
-     *                                                 because these will be inserted in any new rows created as well.
2587
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
-     * @throws EE_Error
2589
-     */
2590
-    public function add_relationship_to(
2591
-        $id_or_obj,
2592
-        $other_model_id_or_obj,
2593
-        $relationName,
2594
-        $extra_join_model_fields_n_values = []
2595
-    ) {
2596
-        $relation_obj = $this->related_settings_for($relationName);
2597
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
-    }
2599
-
2600
-
2601
-    /**
2602
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2603
-     * There are the 3 cases:
2604
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2605
-     * error
2606
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2607
-     * an error
2608
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2609
-     *
2610
-     * @param EE_Base_Class /int $id_or_obj
2611
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2612
-     * @param string $relationName key in EEM_Base::_relations
2613
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2614
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2615
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2616
-     *                             because these will be inserted in any new rows created as well.
2617
-     * @return boolean of success
2618
-     * @throws EE_Error
2619
-     */
2620
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2621
-    {
2622
-        $relation_obj = $this->related_settings_for($relationName);
2623
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2624
-    }
2625
-
2626
-
2627
-    /**
2628
-     * @param mixed  $id_or_obj
2629
-     * @param string $relationName
2630
-     * @param array  $where_query_params
2631
-     * @param EE_Base_Class[] objects to which relations were removed
2632
-     * @return \EE_Base_Class[]
2633
-     * @throws EE_Error
2634
-     */
2635
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2636
-    {
2637
-        $relation_obj = $this->related_settings_for($relationName);
2638
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2639
-    }
2640
-
2641
-
2642
-    /**
2643
-     * Gets all the related items of the specified $model_name, using $query_params.
2644
-     * Note: by default, we remove the "default query params"
2645
-     * because we want to get even deleted items etc.
2646
-     *
2647
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2648
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2649
-     * @param array  $query_params @see
2650
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2651
-     * @return EE_Base_Class[]
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2655
-    {
2656
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2657
-        $relation_settings = $this->related_settings_for($model_name);
2658
-        return $relation_settings->get_all_related($model_obj, $query_params);
2659
-    }
2660
-
2661
-
2662
-    /**
2663
-     * Deletes all the model objects across the relation indicated by $model_name
2664
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2665
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2666
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2667
-     *
2668
-     * @param EE_Base_Class|int|string $id_or_obj
2669
-     * @param string                   $model_name
2670
-     * @param array                    $query_params
2671
-     * @return int how many deleted
2672
-     * @throws EE_Error
2673
-     */
2674
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2675
-    {
2676
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2677
-        $relation_settings = $this->related_settings_for($model_name);
2678
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2679
-    }
2680
-
2681
-
2682
-    /**
2683
-     * Hard deletes all the model objects across the relation indicated by $model_name
2684
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2685
-     * the model objects can't be hard deleted because of blocking related model objects,
2686
-     * just does a soft-delete on them instead.
2687
-     *
2688
-     * @param EE_Base_Class|int|string $id_or_obj
2689
-     * @param string                   $model_name
2690
-     * @param array                    $query_params
2691
-     * @return int how many deleted
2692
-     * @throws EE_Error
2693
-     */
2694
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2695
-    {
2696
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2697
-        $relation_settings = $this->related_settings_for($model_name);
2698
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2699
-    }
2700
-
2701
-
2702
-    /**
2703
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2704
-     * unless otherwise specified in the $query_params
2705
-     *
2706
-     * @param int             /EE_Base_Class $id_or_obj
2707
-     * @param string $model_name     like 'Event', or 'Registration'
2708
-     * @param array  $query_params   @see
2709
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2710
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2711
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2712
-     *                               that by the setting $distinct to TRUE;
2713
-     * @return int
2714
-     * @throws EE_Error
2715
-     */
2716
-    public function count_related(
2717
-        $id_or_obj,
2718
-        $model_name,
2719
-        $query_params = [],
2720
-        $field_to_count = null,
2721
-        $distinct = false
2722
-    ) {
2723
-        $related_model = $this->get_related_model_obj($model_name);
2724
-        // we're just going to use the query params on the related model's normal get_all query,
2725
-        // except add a condition to say to match the current mod
2726
-        if (! isset($query_params['default_where_conditions'])) {
2727
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2728
-        }
2729
-        $this_model_name                                                 = $this->get_this_model_name();
2730
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2731
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2732
-        return $related_model->count($query_params, $field_to_count, $distinct);
2733
-    }
2734
-
2735
-
2736
-    /**
2737
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2738
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2739
-     *
2740
-     * @param int           /EE_Base_Class $id_or_obj
2741
-     * @param string $model_name   like 'Event', or 'Registration'
2742
-     * @param array  $query_params @see
2743
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2745
-     * @return float
2746
-     * @throws EE_Error
2747
-     */
2748
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2749
-    {
2750
-        $related_model = $this->get_related_model_obj($model_name);
2751
-        if (! is_array($query_params)) {
2752
-            EE_Error::doing_it_wrong(
2753
-                'EEM_Base::sum_related',
2754
-                sprintf(
2755
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2756
-                    gettype($query_params)
2757
-                ),
2758
-                '4.6.0'
2759
-            );
2760
-            $query_params = [];
2761
-        }
2762
-        // we're just going to use the query params on the related model's normal get_all query,
2763
-        // except add a condition to say to match the current mod
2764
-        if (! isset($query_params['default_where_conditions'])) {
2765
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2766
-        }
2767
-        $this_model_name                                                 = $this->get_this_model_name();
2768
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2769
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2770
-        return $related_model->sum($query_params, $field_to_sum);
2771
-    }
2772
-
2773
-
2774
-    /**
2775
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2776
-     * $modelObject
2777
-     *
2778
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2779
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2780
-     * @param array               $query_params     @see
2781
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
-     * @return EE_Base_Class
2783
-     * @throws EE_Error
2784
-     */
2785
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2786
-    {
2787
-        $query_params['limit'] = 1;
2788
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2789
-        if ($results) {
2790
-            return array_shift($results);
2791
-        }
2792
-        return null;
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2798
-     *
2799
-     * @return string
2800
-     */
2801
-    public function get_this_model_name()
2802
-    {
2803
-        return str_replace("EEM_", "", get_class($this));
2804
-    }
2805
-
2806
-
2807
-    /**
2808
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2809
-     *
2810
-     * @return EE_Any_Foreign_Model_Name_Field
2811
-     * @throws EE_Error
2812
-     */
2813
-    public function get_field_containing_related_model_name()
2814
-    {
2815
-        foreach ($this->field_settings(true) as $field) {
2816
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2817
-                $field_with_model_name = $field;
2818
-            }
2819
-        }
2820
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2821
-            throw new EE_Error(
2822
-                sprintf(
2823
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2824
-                    $this->get_this_model_name()
2825
-                )
2826
-            );
2827
-        }
2828
-        return $field_with_model_name;
2829
-    }
2830
-
2831
-
2832
-    /**
2833
-     * Inserts a new entry into the database, for each table.
2834
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2835
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2836
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2837
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2838
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2839
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2840
-     *
2841
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2842
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2843
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2844
-     *                              of EEM_Base)
2845
-     * @return int|string new primary key on main table that got inserted
2846
-     * @throws EE_Error
2847
-     */
2848
-    public function insert($field_n_values)
2849
-    {
2850
-        /**
2851
-         * Filters the fields and their values before inserting an item using the models
2852
-         *
2853
-         * @param array    $fields_n_values keys are the fields and values are their new values
2854
-         * @param EEM_Base $model           the model used
2855
-         */
2856
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2857
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2858
-            $main_table = $this->_get_main_table();
2859
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2860
-            if ($new_id !== false) {
2861
-                foreach ($this->_get_other_tables() as $other_table) {
2862
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2863
-                }
2864
-            }
2865
-            /**
2866
-             * Done just after attempting to insert a new model object
2867
-             *
2868
-             * @param EEM_Base $model           used
2869
-             * @param array    $fields_n_values fields and their values
2870
-             * @param int|string the              ID of the newly-inserted model object
2871
-             */
2872
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2873
-            return $new_id;
2874
-        }
2875
-        return false;
2876
-    }
2877
-
2878
-
2879
-    /**
2880
-     * Checks that the result would satisfy the unique indexes on this model
2881
-     *
2882
-     * @param array  $field_n_values
2883
-     * @param string $action
2884
-     * @return boolean
2885
-     * @throws EE_Error
2886
-     */
2887
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
-    {
2889
-        foreach ($this->unique_indexes() as $index_name => $index) {
2890
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
-            if ($this->exists([$uniqueness_where_params])) {
2892
-                EE_Error::add_error(
2893
-                    sprintf(
2894
-                        esc_html__(
2895
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
-                            "event_espresso"
2897
-                        ),
2898
-                        $action,
2899
-                        $this->_get_class_name(),
2900
-                        $index_name,
2901
-                        implode(",", $index->field_names()),
2902
-                        http_build_query($uniqueness_where_params)
2903
-                    ),
2904
-                    __FILE__,
2905
-                    __FUNCTION__,
2906
-                    __LINE__
2907
-                );
2908
-                return false;
2909
-            }
2910
-        }
2911
-        return true;
2912
-    }
2913
-
2914
-
2915
-    /**
2916
-     * Checks the database for an item that conflicts (ie, if this item were
2917
-     * saved to the DB would break some uniqueness requirement, like a primary key
2918
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
-     * can be either an EE_Base_Class or an array of fields n values
2920
-     *
2921
-     * @param EE_Base_Class|array $obj_or_fields_array
2922
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2923
-     *                                                 when looking for conflicts
2924
-     *                                                 (ie, if false, we ignore the model object's primary key
2925
-     *                                                 when finding "conflicts". If true, it's also considered).
2926
-     *                                                 Only works for INT primary key,
2927
-     *                                                 STRING primary keys cannot be ignored
2928
-     * @return EE_Base_Class|array
2929
-     * @throws EE_Error
2930
-     */
2931
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2932
-    {
2933
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2934
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2935
-        } elseif (is_array($obj_or_fields_array)) {
2936
-            $fields_n_values = $obj_or_fields_array;
2937
-        } else {
2938
-            throw new EE_Error(
2939
-                sprintf(
2940
-                    esc_html__(
2941
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2942
-                        "event_espresso"
2943
-                    ),
2944
-                    get_class($this),
2945
-                    $obj_or_fields_array
2946
-                )
2947
-            );
2948
-        }
2949
-        $query_params = [];
2950
-        if (
2951
-            $this->has_primary_key_field()
2952
-            && ($include_primary_key
2953
-                || $this->get_primary_key_field()
2954
-                   instanceof
2955
-                   EE_Primary_Key_String_Field)
2956
-            && isset($fields_n_values[ $this->primary_key_name() ])
2957
-        ) {
2958
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2959
-        }
2960
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2961
-            $uniqueness_where_params                              =
2962
-                array_intersect_key($fields_n_values, $unique_index->fields());
2963
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2964
-        }
2965
-        // if there is nothing to base this search on, then we shouldn't find anything
2966
-        if (empty($query_params)) {
2967
-            return [];
2968
-        }
2969
-        return $this->get_one($query_params);
2970
-    }
2971
-
2972
-
2973
-    /**
2974
-     * Like count, but is optimized and returns a boolean instead of an int
2975
-     *
2976
-     * @param array $query_params
2977
-     * @return boolean
2978
-     * @throws EE_Error
2979
-     */
2980
-    public function exists($query_params)
2981
-    {
2982
-        $query_params['limit'] = 1;
2983
-        return $this->count($query_params) > 0;
2984
-    }
2985
-
2986
-
2987
-    /**
2988
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2989
-     *
2990
-     * @param int|string $id
2991
-     * @return boolean
2992
-     * @throws EE_Error
2993
-     */
2994
-    public function exists_by_ID($id)
2995
-    {
2996
-        return $this->exists(
2997
-            [
2998
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2999
-                [
3000
-                    $this->primary_key_name() => $id,
3001
-                ],
3002
-            ]
3003
-        );
3004
-    }
3005
-
3006
-
3007
-    /**
3008
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3009
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3010
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3011
-     * on the main table)
3012
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3013
-     * cases where we want to call it directly rather than via insert().
3014
-     *
3015
-     * @access   protected
3016
-     * @param EE_Table_Base $table
3017
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3018
-     *                                       float
3019
-     * @param int           $new_id          for now we assume only int keys
3020
-     * @return int ID of new row inserted, or FALSE on failure
3021
-     * @throws EE_Error
3022
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3023
-     */
3024
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3025
-    {
3026
-        global $wpdb;
3027
-        $insertion_col_n_values = [];
3028
-        $format_for_insertion   = [];
3029
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3030
-        foreach ($fields_on_table as $field_name => $field_obj) {
3031
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3032
-            if ($field_obj->is_auto_increment()) {
3033
-                continue;
3034
-            }
3035
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3036
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3037
-            if ($prepared_value !== null) {
3038
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3039
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3040
-            }
3041
-        }
3042
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3043
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3044
-            // so add the fk to the main table as a column
3045
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3046
-            $format_for_insertion[]                              =
3047
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3048
-        }
3049
-
3050
-        // insert the new entry
3051
-        $result = $this->_do_wpdb_query(
3052
-            'insert',
3053
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3054
-        );
3055
-        if ($result === false) {
3056
-            return false;
3057
-        }
3058
-        // ok, now what do we return for the ID of the newly-inserted thing?
3059
-        if ($this->has_primary_key_field()) {
3060
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3061
-                return $wpdb->insert_id;
3062
-            }
3063
-            // it's not an auto-increment primary key, so
3064
-            // it must have been supplied
3065
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3066
-        }
3067
-        // we can't return a  primary key because there is none. instead return
3068
-        // a unique string indicating this model
3069
-        return $this->get_index_primary_key_string($fields_n_values);
3070
-    }
3071
-
3072
-
3073
-    /**
3074
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3075
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3076
-     * and there is no default, we pass it along. WPDB will take care of it)
3077
-     *
3078
-     * @param EE_Model_Field_Base $field_obj
3079
-     * @param array               $fields_n_values
3080
-     * @return mixed string|int|float depending on what the table column will be expecting
3081
-     * @throws EE_Error
3082
-     */
3083
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3084
-    {
3085
-        $field_name = $field_obj->get_name();
3086
-        // if this field doesn't allow nullable, don't allow it
3087
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3088
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3089
-        }
3090
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3091
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
-    }
3093
-
3094
-
3095
-    /**
3096
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
-     * the field's prepare_for_set() method.
3099
-     *
3100
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
-     *                                   top of file)
3103
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
-     *                                   $value is a custom selection
3105
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
-     */
3107
-    private function _prepare_value_for_use_in_db($value, $field)
3108
-    {
3109
-        if ($field instanceof EE_Model_Field_Base) {
3110
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
-            switch ($this->_values_already_prepared_by_model_object) {
3112
-                /** @noinspection PhpMissingBreakStatementInspection */
3113
-                case self::not_prepared_by_model_object:
3114
-                    $value = $field->prepare_for_set($value);
3115
-                // purposefully left out "return"
3116
-                // no break
3117
-                case self::prepared_by_model_object:
3118
-                    /** @noinspection SuspiciousAssignmentsInspection */
3119
-                    $value = $field->prepare_for_use_in_db($value);
3120
-                // no break
3121
-                case self::prepared_for_use_in_db:
3122
-                    // leave the value alone
3123
-            }
3124
-            // phpcs:enable
3125
-        }
3126
-        return $value;
3127
-    }
3128
-
3129
-
3130
-    /**
3131
-     * Returns the main table on this model
3132
-     *
3133
-     * @return EE_Primary_Table
3134
-     * @throws EE_Error
3135
-     */
3136
-    protected function _get_main_table()
3137
-    {
3138
-        foreach ($this->_tables as $table) {
3139
-            if ($table instanceof EE_Primary_Table) {
3140
-                return $table;
3141
-            }
3142
-        }
3143
-        throw new EE_Error(
3144
-            sprintf(
3145
-                esc_html__(
3146
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3147
-                    'event_espresso'
3148
-                ),
3149
-                get_class($this)
3150
-            )
3151
-        );
3152
-    }
3153
-
3154
-
3155
-    /**
3156
-     * table
3157
-     * returns EE_Primary_Table table name
3158
-     *
3159
-     * @return string
3160
-     * @throws EE_Error
3161
-     */
3162
-    public function table()
3163
-    {
3164
-        return $this->_get_main_table()->get_table_name();
3165
-    }
3166
-
3167
-
3168
-    /**
3169
-     * table
3170
-     * returns first EE_Secondary_Table table name
3171
-     *
3172
-     * @return string
3173
-     */
3174
-    public function second_table()
3175
-    {
3176
-        // grab second table from tables array
3177
-        $second_table = end($this->_tables);
3178
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3179
-    }
3180
-
3181
-
3182
-    /**
3183
-     * get_table_obj_by_alias
3184
-     * returns table name given it's alias
3185
-     *
3186
-     * @param string $table_alias
3187
-     * @return EE_Primary_Table | EE_Secondary_Table
3188
-     */
3189
-    public function get_table_obj_by_alias($table_alias = '')
3190
-    {
3191
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3192
-    }
3193
-
3194
-
3195
-    /**
3196
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3197
-     *
3198
-     * @return EE_Secondary_Table[]
3199
-     */
3200
-    protected function _get_other_tables()
3201
-    {
3202
-        $other_tables = [];
3203
-        foreach ($this->_tables as $table_alias => $table) {
3204
-            if ($table instanceof EE_Secondary_Table) {
3205
-                $other_tables[ $table_alias ] = $table;
3206
-            }
3207
-        }
3208
-        return $other_tables;
3209
-    }
3210
-
3211
-
3212
-    /**
3213
-     * Finds all the fields that correspond to the given table
3214
-     *
3215
-     * @param string $table_alias , array key in EEM_Base::_tables
3216
-     * @return EE_Model_Field_Base[]
3217
-     */
3218
-    public function _get_fields_for_table($table_alias)
3219
-    {
3220
-        return $this->_fields[ $table_alias ];
3221
-    }
3222
-
3223
-
3224
-    /**
3225
-     * Recurses through all the where parameters, and finds all the related models we'll need
3226
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3227
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3228
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3229
-     * related Registration, Transaction, and Payment models.
3230
-     *
3231
-     * @param array $query_params @see
3232
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3233
-     * @return EE_Model_Query_Info_Carrier
3234
-     * @throws EE_Error
3235
-     */
3236
-    public function _extract_related_models_from_query($query_params)
3237
-    {
3238
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3239
-        if (array_key_exists(0, $query_params)) {
3240
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3241
-        }
3242
-        if (array_key_exists('group_by', $query_params)) {
3243
-            if (is_array($query_params['group_by'])) {
3244
-                $this->_extract_related_models_from_sub_params_array_values(
3245
-                    $query_params['group_by'],
3246
-                    $query_info_carrier,
3247
-                    'group_by'
3248
-                );
3249
-            } elseif (! empty($query_params['group_by'])) {
3250
-                $this->_extract_related_model_info_from_query_param(
3251
-                    $query_params['group_by'],
3252
-                    $query_info_carrier,
3253
-                    'group_by'
3254
-                );
3255
-            }
3256
-        }
3257
-        if (array_key_exists('having', $query_params)) {
3258
-            $this->_extract_related_models_from_sub_params_array_keys(
3259
-                $query_params[0],
3260
-                $query_info_carrier,
3261
-                'having'
3262
-            );
3263
-        }
3264
-        if (array_key_exists('order_by', $query_params)) {
3265
-            if (is_array($query_params['order_by'])) {
3266
-                $this->_extract_related_models_from_sub_params_array_keys(
3267
-                    $query_params['order_by'],
3268
-                    $query_info_carrier,
3269
-                    'order_by'
3270
-                );
3271
-            } elseif (! empty($query_params['order_by'])) {
3272
-                $this->_extract_related_model_info_from_query_param(
3273
-                    $query_params['order_by'],
3274
-                    $query_info_carrier,
3275
-                    'order_by'
3276
-                );
3277
-            }
3278
-        }
3279
-        if (array_key_exists('force_join', $query_params)) {
3280
-            $this->_extract_related_models_from_sub_params_array_values(
3281
-                $query_params['force_join'],
3282
-                $query_info_carrier,
3283
-                'force_join'
3284
-            );
3285
-        }
3286
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3287
-        return $query_info_carrier;
3288
-    }
3289
-
3290
-
3291
-    /**
3292
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3293
-     *
3294
-     * @param array                       $sub_query_params @see
3295
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3296
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3297
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3298
-     * @throws EE_Error
3299
-     * @return \EE_Model_Query_Info_Carrier
3300
-     */
3301
-    private function _extract_related_models_from_sub_params_array_keys(
3302
-        $sub_query_params,
3303
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304
-        $query_param_type
3305
-    ) {
3306
-        if (! empty($sub_query_params)) {
3307
-            $sub_query_params = (array) $sub_query_params;
3308
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3310
-                $this->_extract_related_model_info_from_query_param(
3311
-                    $param,
3312
-                    $model_query_info_carrier,
3313
-                    $query_param_type
3314
-                );
3315
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3316
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3317
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3318
-                // of array('Registration.TXN_ID'=>23)
3319
-                $query_param_sans_stars =
3320
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
-                    if (! is_array($possibly_array_of_params)) {
3323
-                        throw new EE_Error(
3324
-                            sprintf(
3325
-                                esc_html__(
3326
-                                    "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'))",
3327
-                                    "event_espresso"
3328
-                                ),
3329
-                                $param,
3330
-                                $possibly_array_of_params
3331
-                            )
3332
-                        );
3333
-                    }
3334
-                    $this->_extract_related_models_from_sub_params_array_keys(
3335
-                        $possibly_array_of_params,
3336
-                        $model_query_info_carrier,
3337
-                        $query_param_type
3338
-                    );
3339
-                } elseif (
3340
-                    $query_param_type === 0 // ie WHERE
3341
-                    && is_array($possibly_array_of_params)
3342
-                    && isset($possibly_array_of_params[2])
3343
-                    && $possibly_array_of_params[2] == true
3344
-                ) {
3345
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3347
-                    // from which we should extract query parameters!
3348
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349
-                        throw new EE_Error(
3350
-                            sprintf(
3351
-                                esc_html__(
3352
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3353
-                                    "event_espresso"
3354
-                                ),
3355
-                                $query_param_type,
3356
-                                implode(",", $possibly_array_of_params)
3357
-                            )
3358
-                        );
3359
-                    }
3360
-                    $this->_extract_related_model_info_from_query_param(
3361
-                        $possibly_array_of_params[1],
3362
-                        $model_query_info_carrier,
3363
-                        $query_param_type
3364
-                    );
3365
-                }
3366
-            }
3367
-        }
3368
-        return $model_query_info_carrier;
3369
-    }
3370
-
3371
-
3372
-    /**
3373
-     * For extracting related models from forced_joins, where the array values contain the info about what
3374
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3375
-     *
3376
-     * @param array                       $sub_query_params @see
3377
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3378
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3379
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3380
-     * @throws EE_Error
3381
-     * @return \EE_Model_Query_Info_Carrier
3382
-     */
3383
-    private function _extract_related_models_from_sub_params_array_values(
3384
-        $sub_query_params,
3385
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386
-        $query_param_type
3387
-    ) {
3388
-        if (! empty($sub_query_params)) {
3389
-            if (! is_array($sub_query_params)) {
3390
-                throw new EE_Error(
3391
-                    sprintf(
3392
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3393
-                        $sub_query_params
3394
-                    )
3395
-                );
3396
-            }
3397
-            foreach ($sub_query_params as $param) {
3398
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3399
-                $this->_extract_related_model_info_from_query_param(
3400
-                    $param,
3401
-                    $model_query_info_carrier,
3402
-                    $query_param_type
3403
-                );
3404
-            }
3405
-        }
3406
-        return $model_query_info_carrier;
3407
-    }
3408
-
3409
-
3410
-    /**
3411
-     * Extract all the query parts from  model query params
3412
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3413
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3414
-     * but use them in a different order. Eg, we need to know what models we are querying
3415
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3416
-     * other models before we can finalize the where clause SQL.
3417
-     *
3418
-     * @param array $query_params @see
3419
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3420
-     * @throws EE_Error
3421
-     * @return EE_Model_Query_Info_Carrier
3422
-     * @throws ModelConfigurationException
3423
-     */
3424
-    public function _create_model_query_info_carrier($query_params)
3425
-    {
3426
-        if (! is_array($query_params)) {
3427
-            EE_Error::doing_it_wrong(
3428
-                'EEM_Base::_create_model_query_info_carrier',
3429
-                sprintf(
3430
-                    esc_html__(
3431
-                        '$query_params should be an array, you passed a variable of type %s',
3432
-                        'event_espresso'
3433
-                    ),
3434
-                    gettype($query_params)
3435
-                ),
3436
-                '4.6.0'
3437
-            );
3438
-            $query_params = [];
3439
-        }
3440
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
-        // first check if we should alter the query to account for caps or not
3442
-        // because the caps might require us to do extra joins
3443
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
-            $query_params[0] = array_replace_recursive(
3445
-                $query_params[0],
3446
-                $this->caps_where_conditions($query_params['caps'])
3447
-            );
3448
-        }
3449
-
3450
-        // check if we should alter the query to remove data related to protected
3451
-        // custom post types
3452
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3453
-            $where_param_key_for_password = $this->modelChainAndPassword();
3454
-            // only include if related to a cpt where no password has been set
3455
-            $query_params[0]['OR*nopassword'] = [
3456
-                $where_param_key_for_password       => '',
3457
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3458
-            ];
3459
-        }
3460
-        $query_object = $this->_extract_related_models_from_query($query_params);
3461
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3462
-        foreach ($query_params[0] as $key => $value) {
3463
-            if (is_int($key)) {
3464
-                throw new EE_Error(
3465
-                    sprintf(
3466
-                        esc_html__(
3467
-                            "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.",
3468
-                            "event_espresso"
3469
-                        ),
3470
-                        $key,
3471
-                        var_export($value, true),
3472
-                        var_export($query_params, true),
3473
-                        get_class($this)
3474
-                    )
3475
-                );
3476
-            }
3477
-        }
3478
-        if (
3479
-            array_key_exists('default_where_conditions', $query_params)
3480
-            && ! empty($query_params['default_where_conditions'])
3481
-        ) {
3482
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3483
-        } else {
3484
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3485
-        }
3486
-        $query_params[0] = array_merge(
3487
-            $this->_get_default_where_conditions_for_models_in_query(
3488
-                $query_object,
3489
-                $use_default_where_conditions,
3490
-                $query_params[0]
3491
-            ),
3492
-            $query_params[0]
3493
-        );
3494
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3495
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3496
-        // So we need to setup a subquery and use that for the main join.
3497
-        // Note for now this only works on the primary table for the model.
3498
-        // So for instance, you could set the limit array like this:
3499
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3500
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3501
-            $query_object->set_main_model_join_sql(
3502
-                $this->_construct_limit_join_select(
3503
-                    $query_params['on_join_limit'][0],
3504
-                    $query_params['on_join_limit'][1]
3505
-                )
3506
-            );
3507
-        }
3508
-        // set limit
3509
-        if (array_key_exists('limit', $query_params)) {
3510
-            if (is_array($query_params['limit'])) {
3511
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3512
-                    $e = sprintf(
3513
-                        esc_html__(
3514
-                            "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)",
3515
-                            "event_espresso"
3516
-                        ),
3517
-                        http_build_query($query_params['limit'])
3518
-                    );
3519
-                    throw new EE_Error($e . "|" . $e);
3520
-                }
3521
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3522
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3523
-            } elseif (! empty($query_params['limit'])) {
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3525
-            }
3526
-        }
3527
-        // set order by
3528
-        if (array_key_exists('order_by', $query_params)) {
3529
-            if (is_array($query_params['order_by'])) {
3530
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3531
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3532
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3533
-                if (array_key_exists('order', $query_params)) {
3534
-                    throw new EE_Error(
3535
-                        sprintf(
3536
-                            esc_html__(
3537
-                                "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 ",
3538
-                                "event_espresso"
3539
-                            ),
3540
-                            get_class($this),
3541
-                            implode(", ", array_keys($query_params['order_by'])),
3542
-                            implode(", ", $query_params['order_by']),
3543
-                            $query_params['order']
3544
-                        )
3545
-                    );
3546
-                }
3547
-                $this->_extract_related_models_from_sub_params_array_keys(
3548
-                    $query_params['order_by'],
3549
-                    $query_object,
3550
-                    'order_by'
3551
-                );
3552
-                // assume it's an array of fields to order by
3553
-                $order_array = [];
3554
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3555
-                    $order         = $this->_extract_order($order);
3556
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3557
-                }
3558
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3559
-            } elseif (! empty($query_params['order_by'])) {
3560
-                $this->_extract_related_model_info_from_query_param(
3561
-                    $query_params['order_by'],
3562
-                    $query_object,
3563
-                    'order',
3564
-                    $query_params['order_by']
3565
-                );
3566
-                $order = isset($query_params['order'])
3567
-                    ? $this->_extract_order($query_params['order'])
3568
-                    : 'DESC';
3569
-                $query_object->set_order_by_sql(
3570
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3571
-                );
3572
-            }
3573
-        }
3574
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3575
-        if (
3576
-            ! array_key_exists('order_by', $query_params)
3577
-            && array_key_exists('order', $query_params)
3578
-            && ! empty($query_params['order'])
3579
-        ) {
3580
-            $pk_field = $this->get_primary_key_field();
3581
-            $order    = $this->_extract_order($query_params['order']);
3582
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3583
-        }
3584
-        // set group by
3585
-        if (array_key_exists('group_by', $query_params)) {
3586
-            if (is_array($query_params['group_by'])) {
3587
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3588
-                $group_by_array = [];
3589
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3590
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3591
-                }
3592
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3593
-            } elseif (! empty($query_params['group_by'])) {
3594
-                $query_object->set_group_by_sql(
3595
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3596
-                );
3597
-            }
3598
-        }
3599
-        // set having
3600
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3601
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3602
-        }
3603
-        // now, just verify they didn't pass anything wack
3604
-        foreach ($query_params as $query_key => $query_value) {
3605
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3606
-                throw new EE_Error(
3607
-                    sprintf(
3608
-                        esc_html__(
3609
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3610
-                            'event_espresso'
3611
-                        ),
3612
-                        $query_key,
3613
-                        get_class($this),
3614
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3615
-                        implode(',', $this->_allowed_query_params)
3616
-                    )
3617
-                );
3618
-            }
3619
-        }
3620
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3621
-        if (empty($main_model_join_sql)) {
3622
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3623
-        }
3624
-        return $query_object;
3625
-    }
3626
-
3627
-
3628
-    /**
3629
-     * Gets the where conditions that should be imposed on the query based on the
3630
-     * context (eg reading frontend, backend, edit or delete).
3631
-     *
3632
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3633
-     * @return array @see
3634
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3635
-     * @throws EE_Error
3636
-     */
3637
-    public function caps_where_conditions($context = self::caps_read)
3638
-    {
3639
-        EEM_Base::verify_is_valid_cap_context($context);
3640
-        $cap_where_conditions = [];
3641
-        $cap_restrictions     = $this->caps_missing($context);
3642
-        /**
3643
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3644
-         */
3645
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3646
-            $cap_where_conditions = array_replace_recursive(
3647
-                $cap_where_conditions,
3648
-                $restriction_if_no_cap->get_default_where_conditions()
3649
-            );
3650
-        }
3651
-        return apply_filters(
3652
-            'FHEE__EEM_Base__caps_where_conditions__return',
3653
-            $cap_where_conditions,
3654
-            $this,
3655
-            $context,
3656
-            $cap_restrictions
3657
-        );
3658
-    }
3659
-
3660
-
3661
-    /**
3662
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3663
-     * otherwise throws an exception
3664
-     *
3665
-     * @param string $should_be_order_string
3666
-     * @return string either ASC, asc, DESC or desc
3667
-     * @throws EE_Error
3668
-     */
3669
-    private function _extract_order($should_be_order_string)
3670
-    {
3671
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3672
-            return $should_be_order_string;
3673
-        }
3674
-        throw new EE_Error(
3675
-            sprintf(
3676
-                esc_html__(
3677
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3678
-                    "event_espresso"
3679
-                ),
3680
-                get_class($this),
3681
-                $should_be_order_string
3682
-            )
3683
-        );
3684
-    }
3685
-
3686
-
3687
-    /**
3688
-     * Looks at all the models which are included in this query, and asks each
3689
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3690
-     * so they can be merged
3691
-     *
3692
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3693
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3694
-     *                                                                  'none' means NO default where conditions will
3695
-     *                                                                  be used AT ALL during this query.
3696
-     *                                                                  'other_models_only' means default where
3697
-     *                                                                  conditions from other models will be used, but
3698
-     *                                                                  not for this primary model. 'all', the default,
3699
-     *                                                                  means default where conditions will apply as
3700
-     *                                                                  normal
3701
-     * @param array                       $where_query_params           @see
3702
-     *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3703
-     * @return array @see
3704
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3705
-     * @throws EE_Error
3706
-     */
3707
-    private function _get_default_where_conditions_for_models_in_query(
3708
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3709
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3710
-        $where_query_params = []
3711
-    ) {
3712
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3713
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3714
-            throw new EE_Error(
3715
-                sprintf(
3716
-                    esc_html__(
3717
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3718
-                        "event_espresso"
3719
-                    ),
3720
-                    $use_default_where_conditions,
3721
-                    implode(", ", $allowed_used_default_where_conditions_values)
3722
-                )
3723
-            );
3724
-        }
3725
-        $universal_query_params = [];
3726
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3727
-            $universal_query_params = $this->_get_default_where_conditions();
3728
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3729
-            $universal_query_params = $this->_get_minimum_where_conditions();
3730
-        }
3731
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3732
-            $related_model = $this->get_related_model_obj($model_name);
3733
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3734
-                $related_model_universal_where_params =
3735
-                    $related_model->_get_default_where_conditions($model_relation_path);
3736
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3737
-                $related_model_universal_where_params =
3738
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3739
-            } else {
3740
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3741
-                continue;
3742
-            }
3743
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3744
-                $related_model_universal_where_params,
3745
-                $where_query_params,
3746
-                $related_model,
3747
-                $model_relation_path
3748
-            );
3749
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3750
-                $universal_query_params,
3751
-                $overrides
3752
-            );
3753
-        }
3754
-        return $universal_query_params;
3755
-    }
3756
-
3757
-
3758
-    /**
3759
-     * Determines whether or not we should use default where conditions for the model in question
3760
-     * (this model, or other related models).
3761
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3762
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3763
-     * We should use default where conditions on related models when they requested to use default where conditions
3764
-     * on all models, or specifically just on other related models
3765
-     *
3766
-     * @param      $default_where_conditions_value
3767
-     * @param bool $for_this_model false means this is for OTHER related models
3768
-     * @return bool
3769
-     */
3770
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3771
-    {
3772
-        return (
3773
-                   $for_this_model
3774
-                   && in_array(
3775
-                       $default_where_conditions_value,
3776
-                       [
3777
-                           EEM_Base::default_where_conditions_all,
3778
-                           EEM_Base::default_where_conditions_this_only,
3779
-                           EEM_Base::default_where_conditions_minimum_others,
3780
-                       ],
3781
-                       true
3782
-                   )
3783
-               )
3784
-               || (
3785
-                   ! $for_this_model
3786
-                   && in_array(
3787
-                       $default_where_conditions_value,
3788
-                       [
3789
-                           EEM_Base::default_where_conditions_all,
3790
-                           EEM_Base::default_where_conditions_others_only,
3791
-                       ],
3792
-                       true
3793
-                   )
3794
-               );
3795
-    }
3796
-
3797
-
3798
-    /**
3799
-     * Determines whether or not we should use default minimum conditions for the model in question
3800
-     * (this model, or other related models).
3801
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3802
-     * where conditions.
3803
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3804
-     * on this model or others
3805
-     *
3806
-     * @param      $default_where_conditions_value
3807
-     * @param bool $for_this_model false means this is for OTHER related models
3808
-     * @return bool
3809
-     */
3810
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
-    {
3812
-        return (
3813
-                   $for_this_model
3814
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
-               )
3816
-               || (
3817
-                   ! $for_this_model
3818
-                   && in_array(
3819
-                       $default_where_conditions_value,
3820
-                       [
3821
-                           EEM_Base::default_where_conditions_minimum_others,
3822
-                           EEM_Base::default_where_conditions_minimum_all,
3823
-                       ],
3824
-                       true
3825
-                   )
3826
-               );
3827
-    }
3828
-
3829
-
3830
-    /**
3831
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
-     * then we also add a special where condition which allows for that model's primary key
3833
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
-     *
3836
-     * @param array    $default_where_conditions
3837
-     * @param array    $provided_where_conditions
3838
-     * @param EEM_Base $model
3839
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3840
-     * @return array @see
3841
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3842
-     * @throws EE_Error
3843
-     */
3844
-    private function _override_defaults_or_make_null_friendly(
3845
-        $default_where_conditions,
3846
-        $provided_where_conditions,
3847
-        $model,
3848
-        $model_relation_path
3849
-    ) {
3850
-        $null_friendly_where_conditions = [];
3851
-        $none_overridden                = true;
3852
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3853
-        foreach ($default_where_conditions as $key => $val) {
3854
-            if (isset($provided_where_conditions[ $key ])) {
3855
-                $none_overridden = false;
3856
-            } else {
3857
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3858
-            }
3859
-        }
3860
-        if ($none_overridden && $default_where_conditions) {
3861
-            if ($model->has_primary_key_field()) {
3862
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3863
-                                                                                   . "."
3864
-                                                                                   . $model->primary_key_name() ] =
3865
-                    ['IS NULL'];
3866
-            }/*else{
1800
+		// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1801
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1802
+		/**
1803
+		 * Action called after a model update call has been made.
1804
+		 *
1805
+		 * @param EEM_Base $model
1806
+		 * @param array    $fields_n_values the updated fields and their new values
1807
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1808
+		 * @param int      $rows_affected
1809
+		 */
1810
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1811
+		return $rows_affected;// how many supposedly got updated
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1817
+	 * are teh values of the field specified (or by default the primary key field)
1818
+	 * that matched the query params. Note that you should pass the name of the
1819
+	 * model FIELD, not the database table's column name.
1820
+	 *
1821
+	 * @param array  $query_params @see
1822
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1823
+	 * @param string $field_to_select
1824
+	 * @return array just like $wpdb->get_col()
1825
+	 * @throws EE_Error
1826
+	 */
1827
+	public function get_col($query_params = [], $field_to_select = null)
1828
+	{
1829
+		if ($field_to_select) {
1830
+			$field = $this->field_settings_for($field_to_select);
1831
+		} elseif ($this->has_primary_key_field()) {
1832
+			$field = $this->get_primary_key_field();
1833
+		} else {
1834
+			// no primary key, just grab the first column
1835
+			$field_settings = $this->field_settings();
1836
+			$field          = reset($field_settings);
1837
+		}
1838
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1839
+		$select_expressions = $field->get_qualified_column();
1840
+		$SQL                =
1841
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1842
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1843
+	}
1844
+
1845
+
1846
+	/**
1847
+	 * Returns a single column value for a single row from the database
1848
+	 *
1849
+	 * @param array  $query_params    @see
1850
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1851
+	 * @param string $field_to_select @see EEM_Base::get_col()
1852
+	 * @return string
1853
+	 * @throws EE_Error
1854
+	 */
1855
+	public function get_var($query_params = [], $field_to_select = null)
1856
+	{
1857
+		$query_params['limit'] = 1;
1858
+		$col                   = $this->get_col($query_params, $field_to_select);
1859
+		if (! empty($col)) {
1860
+			return reset($col);
1861
+		}
1862
+		return null;
1863
+	}
1864
+
1865
+
1866
+	/**
1867
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1868
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1869
+	 * injection, but currently no further filtering is done
1870
+	 *
1871
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1872
+	 *                               be updated to in the DB
1873
+	 * @return string of SQL
1874
+	 * @throws EE_Error
1875
+	 * @global      $wpdb
1876
+	 */
1877
+	public function _construct_update_sql($fields_n_values)
1878
+	{
1879
+		/** @type WPDB $wpdb */
1880
+		global $wpdb;
1881
+		$cols_n_values = [];
1882
+		foreach ($fields_n_values as $field_name => $value) {
1883
+			$field_obj = $this->field_settings_for($field_name);
1884
+			// if the value is NULL, we want to assign the value to that.
1885
+			// wpdb->prepare doesn't really handle that properly
1886
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1887
+			$value_sql       = $prepared_value === null ? 'NULL'
1888
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1889
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1890
+		}
1891
+		return implode(",", $cols_n_values);
1892
+	}
1893
+
1894
+
1895
+	/**
1896
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1897
+	 * Performs a HARD delete, meaning the database row should always be removed,
1898
+	 * not just have a flag field on it switched
1899
+	 * Wrapper for EEM_Base::delete_permanently()
1900
+	 *
1901
+	 * @param mixed   $id
1902
+	 * @param boolean $allow_blocking
1903
+	 * @return int the number of rows deleted
1904
+	 * @throws EE_Error
1905
+	 */
1906
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1907
+	{
1908
+		return $this->delete_permanently(
1909
+			[
1910
+				[$this->get_primary_key_field()->get_name() => $id],
1911
+				'limit' => 1,
1912
+			],
1913
+			$allow_blocking
1914
+		);
1915
+	}
1916
+
1917
+
1918
+	/**
1919
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1920
+	 * Wrapper for EEM_Base::delete()
1921
+	 *
1922
+	 * @param mixed   $id
1923
+	 * @param boolean $allow_blocking
1924
+	 * @return int the number of rows deleted
1925
+	 * @throws EE_Error
1926
+	 */
1927
+	public function delete_by_ID($id, $allow_blocking = true)
1928
+	{
1929
+		return $this->delete(
1930
+			[
1931
+				[$this->get_primary_key_field()->get_name() => $id],
1932
+				'limit' => 1,
1933
+			],
1934
+			$allow_blocking
1935
+		);
1936
+	}
1937
+
1938
+
1939
+	/**
1940
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1941
+	 * meaning if the model has a field that indicates its been "trashed" or
1942
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1943
+	 *
1944
+	 * @param array   $query_params
1945
+	 * @param boolean $allow_blocking
1946
+	 * @return int how many rows got deleted
1947
+	 * @throws EE_Error
1948
+	 * @see EEM_Base::delete_permanently
1949
+	 */
1950
+	public function delete($query_params, $allow_blocking = true)
1951
+	{
1952
+		return $this->delete_permanently($query_params, $allow_blocking);
1953
+	}
1954
+
1955
+
1956
+	/**
1957
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1958
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1959
+	 * as archived, not actually deleted
1960
+	 *
1961
+	 * @param array   $query_params   @see
1962
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1963
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1964
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1965
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1966
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1967
+	 *                                DB
1968
+	 * @return int how many rows got deleted
1969
+	 * @throws EE_Error
1970
+	 */
1971
+	public function delete_permanently($query_params, $allow_blocking = true)
1972
+	{
1973
+		/**
1974
+		 * Action called just before performing a real deletion query. You can use the
1975
+		 * model and its $query_params to find exactly which items will be deleted
1976
+		 *
1977
+		 * @param EEM_Base $model
1978
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1979
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1980
+		 *                                 to block (prevent) this deletion
1981
+		 */
1982
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1983
+		// some MySQL databases may be running safe mode, which may restrict
1984
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1985
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1986
+		// to delete them
1987
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1988
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1989
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1990
+			$columns_and_ids_for_deleting
1991
+		);
1992
+		/**
1993
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1994
+		 *
1995
+		 * @param EEM_Base $this                            The model instance being acted on.
1996
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1997
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1998
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1999
+		 *                                                  derived from the incoming query parameters.
2000
+		 * @see details on the structure of this array in the phpdocs
2001
+		 *                                                  for the `_get_ids_for_delete_method`
2002
+		 *
2003
+		 */
2004
+		do_action(
2005
+			'AHEE__EEM_Base__delete__before_query',
2006
+			$this,
2007
+			$query_params,
2008
+			$allow_blocking,
2009
+			$columns_and_ids_for_deleting
2010
+		);
2011
+		if ($deletion_where_query_part) {
2012
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2013
+			$table_aliases    = array_keys($this->_tables);
2014
+			$SQL              = "DELETE "
2015
+								. implode(", ", $table_aliases)
2016
+								. " FROM "
2017
+								. $model_query_info->get_full_join_sql()
2018
+								. " WHERE "
2019
+								. $deletion_where_query_part;
2020
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2021
+		} else {
2022
+			$rows_deleted = 0;
2023
+		}
2024
+
2025
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2026
+		// there was no error with the delete query.
2027
+		if (
2028
+			$this->has_primary_key_field()
2029
+			&& $rows_deleted !== false
2030
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2031
+		) {
2032
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2033
+			foreach ($ids_for_removal as $id) {
2034
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2035
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2036
+				}
2037
+			}
2038
+
2039
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2040
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2041
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2042
+			// (although it is possible).
2043
+			// Note this can be skipped by using the provided filter and returning false.
2044
+			if (
2045
+				apply_filters(
2046
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2047
+					! $this instanceof EEM_Extra_Meta,
2048
+					$this
2049
+				)
2050
+			) {
2051
+				EEM_Extra_Meta::instance()->delete_permanently([
2052
+																   0 => [
2053
+																	   'EXM_type' => $this->get_this_model_name(),
2054
+																	   'OBJ_ID'   => [
2055
+																		   'IN',
2056
+																		   $ids_for_removal,
2057
+																	   ],
2058
+																   ],
2059
+															   ]);
2060
+			}
2061
+		}
2062
+
2063
+		/**
2064
+		 * Action called just after performing a real deletion query. Although at this point the
2065
+		 * items should have been deleted
2066
+		 *
2067
+		 * @param EEM_Base $model
2068
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2069
+		 * @param int      $rows_deleted
2070
+		 */
2071
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2072
+		return $rows_deleted;// how many supposedly got deleted
2073
+	}
2074
+
2075
+
2076
+	/**
2077
+	 * Checks all the relations that throw error messages when there are blocking related objects
2078
+	 * for related model objects. If there are any related model objects on those relations,
2079
+	 * adds an EE_Error, and return true
2080
+	 *
2081
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2082
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2083
+	 *                                                 should be ignored when determining whether there are related
2084
+	 *                                                 model objects which block this model object's deletion. Useful
2085
+	 *                                                 if you know A is related to B and are considering deleting A,
2086
+	 *                                                 but want to see if A has any other objects blocking its deletion
2087
+	 *                                                 before removing the relation between A and B
2088
+	 * @return boolean
2089
+	 * @throws EE_Error
2090
+	 */
2091
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2092
+	{
2093
+		// first, if $ignore_this_model_obj was supplied, get its model
2094
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2095
+			$ignored_model = $ignore_this_model_obj->get_model();
2096
+		} else {
2097
+			$ignored_model = null;
2098
+		}
2099
+		// now check all the relations of $this_model_obj_or_id and see if there
2100
+		// are any related model objects blocking it?
2101
+		$is_blocked = false;
2102
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2103
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2104
+				// if $ignore_this_model_obj was supplied, then for the query
2105
+				// on that model needs to be told to ignore $ignore_this_model_obj
2106
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2107
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, [
2108
+						[
2109
+							$ignored_model->get_primary_key_field()->get_name() => [
2110
+								'!=',
2111
+								$ignore_this_model_obj->ID(),
2112
+							],
2113
+						],
2114
+					]);
2115
+				} else {
2116
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2117
+				}
2118
+				if ($related_model_objects) {
2119
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2120
+					$is_blocked = true;
2121
+				}
2122
+			}
2123
+		}
2124
+		return $is_blocked;
2125
+	}
2126
+
2127
+
2128
+	/**
2129
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2130
+	 *
2131
+	 * @param array $row_results_for_deleting
2132
+	 * @param bool  $allow_blocking
2133
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2134
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2135
+	 *                              dimension array where the key is the fully qualified primary key column and the
2136
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2137
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2138
+	 *                              be a two dimensional array where each element is a group of columns and values that
2139
+	 *                              get deleted. Example: array(
2140
+	 *                              0 => array(
2141
+	 *                              'Term_Relationship.object_id' => 1
2142
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2143
+	 *                              ),
2144
+	 *                              1 => array(
2145
+	 *                              'Term_Relationship.object_id' => 1
2146
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2147
+	 *                              )
2148
+	 *                              )
2149
+	 * @throws EE_Error
2150
+	 */
2151
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2152
+	{
2153
+		$ids_to_delete_indexed_by_column = [];
2154
+		if ($this->has_primary_key_field()) {
2155
+			$primary_table                   = $this->_get_main_table();
2156
+			$primary_table_pk_field          =
2157
+				$this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2158
+			$other_tables                    = $this->_get_other_tables();
2159
+			$ids_to_delete_indexed_by_column = $query = [];
2160
+			foreach ($row_results_for_deleting as $item_to_delete) {
2161
+				// before we mark this item for deletion,
2162
+				// make sure there's no related entities blocking its deletion (if we're checking)
2163
+				if (
2164
+					$allow_blocking
2165
+					&& $this->delete_is_blocked_by_related_models(
2166
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2167
+					)
2168
+				) {
2169
+					continue;
2170
+				}
2171
+				// primary table deletes
2172
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2173
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2174
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2175
+				}
2176
+			}
2177
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
+			$fields = $this->get_combined_primary_key_fields();
2179
+			foreach ($row_results_for_deleting as $item_to_delete) {
2180
+				$ids_to_delete_indexed_by_column_for_row = [];
2181
+				foreach ($fields as $cpk_field) {
2182
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2183
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2184
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2185
+					}
2186
+				}
2187
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2188
+			}
2189
+		} else {
2190
+			// so there's no primary key and no combined key...
2191
+			// sorry, can't help you
2192
+			throw new EE_Error(
2193
+				sprintf(
2194
+					esc_html__(
2195
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2196
+						"event_espresso"
2197
+					),
2198
+					get_class($this)
2199
+				)
2200
+			);
2201
+		}
2202
+		return $ids_to_delete_indexed_by_column;
2203
+	}
2204
+
2205
+
2206
+	/**
2207
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2208
+	 * the corresponding query_part for the query performing the delete.
2209
+	 *
2210
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2211
+	 * @return string
2212
+	 * @throws EE_Error
2213
+	 */
2214
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2215
+	{
2216
+		$query_part = '';
2217
+		if (empty($ids_to_delete_indexed_by_column)) {
2218
+			return $query_part;
2219
+		} elseif ($this->has_primary_key_field()) {
2220
+			$query = [];
2221
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2222
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2223
+			}
2224
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2225
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2226
+			$ways_to_identify_a_row = [];
2227
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2228
+				$values_for_each_combined_primary_key_for_a_row = [];
2229
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2230
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2231
+				}
2232
+				$ways_to_identify_a_row[] = '('
2233
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2234
+											. ')';
2235
+			}
2236
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2237
+		}
2238
+		return $query_part;
2239
+	}
2240
+
2241
+
2242
+	/**
2243
+	 * Gets the model field by the fully qualified name
2244
+	 *
2245
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2246
+	 * @return EE_Model_Field_Base
2247
+	 */
2248
+	public function get_field_by_column($qualified_column_name)
2249
+	{
2250
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2251
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2252
+				return $field_obj;
2253
+			}
2254
+		}
2255
+		throw new EE_Error(
2256
+			sprintf(
2257
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2258
+				$this->get_this_model_name(),
2259
+				$qualified_column_name
2260
+			)
2261
+		);
2262
+	}
2263
+
2264
+
2265
+	/**
2266
+	 * Count all the rows that match criteria the model query params.
2267
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2268
+	 * column
2269
+	 *
2270
+	 * @param array  $query_params   @see
2271
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
+	 * @param string $field_to_count field on model to count by (not column name)
2273
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2274
+	 *                               that by the setting $distinct to TRUE;
2275
+	 * @return int
2276
+	 * @throws EE_Error
2277
+	 */
2278
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2279
+	{
2280
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2281
+		if ($field_to_count) {
2282
+			$field_obj       = $this->field_settings_for($field_to_count);
2283
+			$column_to_count = $field_obj->get_qualified_column();
2284
+		} elseif ($this->has_primary_key_field()) {
2285
+			$pk_field_obj    = $this->get_primary_key_field();
2286
+			$column_to_count = $pk_field_obj->get_qualified_column();
2287
+		} else {
2288
+			// there's no primary key
2289
+			// if we're counting distinct items, and there's no primary key,
2290
+			// we need to list out the columns for distinction;
2291
+			// otherwise we can just use star
2292
+			if ($distinct) {
2293
+				$columns_to_use = [];
2294
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2295
+					$columns_to_use[] = $field_obj->get_qualified_column();
2296
+				}
2297
+				$column_to_count = implode(',', $columns_to_use);
2298
+			} else {
2299
+				$column_to_count = '*';
2300
+			}
2301
+		}
2302
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2303
+		$SQL             =
2304
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2305
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2306
+	}
2307
+
2308
+
2309
+	/**
2310
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2311
+	 *
2312
+	 * @param array  $query_params @see
2313
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2314
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2315
+	 * @return float
2316
+	 * @throws EE_Error
2317
+	 */
2318
+	public function sum($query_params, $field_to_sum = null)
2319
+	{
2320
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2321
+		if ($field_to_sum) {
2322
+			$field_obj = $this->field_settings_for($field_to_sum);
2323
+		} else {
2324
+			$field_obj = $this->get_primary_key_field();
2325
+		}
2326
+		$column_to_count = $field_obj->get_qualified_column();
2327
+		$SQL             =
2328
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2329
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2330
+		$data_type       = $field_obj->get_wpdb_data_type();
2331
+		if ($data_type === '%d' || $data_type === '%s') {
2332
+			return (float) $return_value;
2333
+		}
2334
+		// must be %f
2335
+		return (float) $return_value;
2336
+	}
2337
+
2338
+
2339
+	/**
2340
+	 * Just calls the specified method on $wpdb with the given arguments
2341
+	 * Consolidates a little extra error handling code
2342
+	 *
2343
+	 * @param string $wpdb_method
2344
+	 * @param array  $arguments_to_provide
2345
+	 * @return mixed
2346
+	 * @throws EE_Error
2347
+	 * @global wpdb  $wpdb
2348
+	 */
2349
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2350
+	{
2351
+		// if we're in maintenance mode level 2, DON'T run any queries
2352
+		// because level 2 indicates the database needs updating and
2353
+		// is probably out of sync with the code
2354
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2355
+			throw new EE_Error(
2356
+				sprintf(
2357
+					esc_html__(
2358
+						"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.",
2359
+						"event_espresso"
2360
+					)
2361
+				)
2362
+			);
2363
+		}
2364
+		/** @type WPDB $wpdb */
2365
+		global $wpdb;
2366
+		if (! method_exists($wpdb, $wpdb_method)) {
2367
+			throw new EE_Error(
2368
+				sprintf(
2369
+					esc_html__(
2370
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2371
+						'event_espresso'
2372
+					),
2373
+					$wpdb_method
2374
+				)
2375
+			);
2376
+		}
2377
+		if (WP_DEBUG) {
2378
+			$old_show_errors_value = $wpdb->show_errors;
2379
+			$wpdb->show_errors(false);
2380
+		}
2381
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2382
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2383
+		if (WP_DEBUG) {
2384
+			$wpdb->show_errors($old_show_errors_value);
2385
+			if (! empty($wpdb->last_error)) {
2386
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2387
+			}
2388
+			if ($result === false) {
2389
+				throw new EE_Error(
2390
+					sprintf(
2391
+						esc_html__(
2392
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2393
+							'event_espresso'
2394
+						),
2395
+						$wpdb_method,
2396
+						var_export($arguments_to_provide, true)
2397
+					)
2398
+				);
2399
+			}
2400
+		} elseif ($result === false) {
2401
+			EE_Error::add_error(
2402
+				sprintf(
2403
+					esc_html__(
2404
+						'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"',
2405
+						'event_espresso'
2406
+					),
2407
+					$wpdb_method,
2408
+					var_export($arguments_to_provide, true),
2409
+					$wpdb->last_error
2410
+				),
2411
+				__FILE__,
2412
+				__FUNCTION__,
2413
+				__LINE__
2414
+			);
2415
+		}
2416
+		return $result;
2417
+	}
2418
+
2419
+
2420
+	/**
2421
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2422
+	 * and if there's an error tries to verify the DB is correct. Uses
2423
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2424
+	 * we should try to fix the EE core db, the addons, or just give up
2425
+	 *
2426
+	 * @param string $wpdb_method
2427
+	 * @param array  $arguments_to_provide
2428
+	 * @return mixed
2429
+	 */
2430
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2431
+	{
2432
+		/** @type WPDB $wpdb */
2433
+		global $wpdb;
2434
+		$wpdb->last_error = null;
2435
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2436
+		// was there an error running the query? but we don't care on new activations
2437
+		// (we're going to setup the DB anyway on new activations)
2438
+		if (
2439
+			($result === false || ! empty($wpdb->last_error))
2440
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2441
+		) {
2442
+			switch (EEM_Base::$_db_verification_level) {
2443
+				case EEM_Base::db_verified_none:
2444
+					// let's double-check core's DB
2445
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2446
+					break;
2447
+				case EEM_Base::db_verified_core:
2448
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2449
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2450
+					break;
2451
+				case EEM_Base::db_verified_addons:
2452
+					// ummmm... you in trouble
2453
+					return $result;
2454
+					break;
2455
+			}
2456
+			if (! empty($error_message)) {
2457
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2458
+				trigger_error($error_message);
2459
+			}
2460
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2461
+		}
2462
+		return $result;
2463
+	}
2464
+
2465
+
2466
+	/**
2467
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2468
+	 * EEM_Base::$_db_verification_level
2469
+	 *
2470
+	 * @param string $wpdb_method
2471
+	 * @param array  $arguments_to_provide
2472
+	 * @return string
2473
+	 */
2474
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2475
+	{
2476
+		/** @type WPDB $wpdb */
2477
+		global $wpdb;
2478
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2479
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2480
+		$error_message                    = sprintf(
2481
+			esc_html__(
2482
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2483
+				'event_espresso'
2484
+			),
2485
+			$wpdb->last_error,
2486
+			$wpdb_method,
2487
+			wp_json_encode($arguments_to_provide)
2488
+		);
2489
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2490
+		return $error_message;
2491
+	}
2492
+
2493
+
2494
+	/**
2495
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2496
+	 * EEM_Base::$_db_verification_level
2497
+	 *
2498
+	 * @param $wpdb_method
2499
+	 * @param $arguments_to_provide
2500
+	 * @return string
2501
+	 */
2502
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2503
+	{
2504
+		/** @type WPDB $wpdb */
2505
+		global $wpdb;
2506
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2507
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2508
+		$error_message                    = sprintf(
2509
+			esc_html__(
2510
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2511
+				'event_espresso'
2512
+			),
2513
+			$wpdb->last_error,
2514
+			$wpdb_method,
2515
+			wp_json_encode($arguments_to_provide)
2516
+		);
2517
+		EE_System::instance()->initialize_addons();
2518
+		return $error_message;
2519
+	}
2520
+
2521
+
2522
+	/**
2523
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2524
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2525
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2526
+	 * ..."
2527
+	 *
2528
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2529
+	 * @return string
2530
+	 */
2531
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2532
+	{
2533
+		return " FROM " . $model_query_info->get_full_join_sql() .
2534
+			   $model_query_info->get_where_sql() .
2535
+			   $model_query_info->get_group_by_sql() .
2536
+			   $model_query_info->get_having_sql() .
2537
+			   $model_query_info->get_order_by_sql() .
2538
+			   $model_query_info->get_limit_sql();
2539
+	}
2540
+
2541
+
2542
+	/**
2543
+	 * Set to easily debug the next X queries ran from this model.
2544
+	 *
2545
+	 * @param int $count
2546
+	 */
2547
+	public function show_next_x_db_queries($count = 1)
2548
+	{
2549
+		$this->_show_next_x_db_queries = $count;
2550
+	}
2551
+
2552
+
2553
+	/**
2554
+	 * @param $sql_query
2555
+	 */
2556
+	public function show_db_query_if_previously_requested($sql_query)
2557
+	{
2558
+		if ($this->_show_next_x_db_queries > 0) {
2559
+			echo esc_html($sql_query);
2560
+			$this->_show_next_x_db_queries--;
2561
+		}
2562
+	}
2563
+
2564
+
2565
+	/**
2566
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
+	 * There are the 3 cases:
2568
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
+	 * $otherModelObject has no ID, it is first saved.
2570
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
+	 * has no ID, it is first saved.
2572
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
+	 * join table
2575
+	 *
2576
+	 * @param EE_Base_Class                     /int $thisModelObject
2577
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
+	 * @param string $relationName                     , key in EEM_Base::_relations
2579
+	 *                                                 an attendee to a group, you also want to specify which role they
2580
+	 *                                                 will have in that group. So you would use this parameter to
2581
+	 *                                                 specify array('role-column-name'=>'role-id')
2582
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
+	 *                                                 to for relation to methods that allow you to further specify
2584
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
+	 *                                                 because these will be inserted in any new rows created as well.
2587
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
+	 * @throws EE_Error
2589
+	 */
2590
+	public function add_relationship_to(
2591
+		$id_or_obj,
2592
+		$other_model_id_or_obj,
2593
+		$relationName,
2594
+		$extra_join_model_fields_n_values = []
2595
+	) {
2596
+		$relation_obj = $this->related_settings_for($relationName);
2597
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
+	}
2599
+
2600
+
2601
+	/**
2602
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2603
+	 * There are the 3 cases:
2604
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2605
+	 * error
2606
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2607
+	 * an error
2608
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2609
+	 *
2610
+	 * @param EE_Base_Class /int $id_or_obj
2611
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2612
+	 * @param string $relationName key in EEM_Base::_relations
2613
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2614
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2615
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2616
+	 *                             because these will be inserted in any new rows created as well.
2617
+	 * @return boolean of success
2618
+	 * @throws EE_Error
2619
+	 */
2620
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2621
+	{
2622
+		$relation_obj = $this->related_settings_for($relationName);
2623
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2624
+	}
2625
+
2626
+
2627
+	/**
2628
+	 * @param mixed  $id_or_obj
2629
+	 * @param string $relationName
2630
+	 * @param array  $where_query_params
2631
+	 * @param EE_Base_Class[] objects to which relations were removed
2632
+	 * @return \EE_Base_Class[]
2633
+	 * @throws EE_Error
2634
+	 */
2635
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2636
+	{
2637
+		$relation_obj = $this->related_settings_for($relationName);
2638
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2639
+	}
2640
+
2641
+
2642
+	/**
2643
+	 * Gets all the related items of the specified $model_name, using $query_params.
2644
+	 * Note: by default, we remove the "default query params"
2645
+	 * because we want to get even deleted items etc.
2646
+	 *
2647
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2648
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2649
+	 * @param array  $query_params @see
2650
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2651
+	 * @return EE_Base_Class[]
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2655
+	{
2656
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2657
+		$relation_settings = $this->related_settings_for($model_name);
2658
+		return $relation_settings->get_all_related($model_obj, $query_params);
2659
+	}
2660
+
2661
+
2662
+	/**
2663
+	 * Deletes all the model objects across the relation indicated by $model_name
2664
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2665
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2666
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2667
+	 *
2668
+	 * @param EE_Base_Class|int|string $id_or_obj
2669
+	 * @param string                   $model_name
2670
+	 * @param array                    $query_params
2671
+	 * @return int how many deleted
2672
+	 * @throws EE_Error
2673
+	 */
2674
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2675
+	{
2676
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2677
+		$relation_settings = $this->related_settings_for($model_name);
2678
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2679
+	}
2680
+
2681
+
2682
+	/**
2683
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2684
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2685
+	 * the model objects can't be hard deleted because of blocking related model objects,
2686
+	 * just does a soft-delete on them instead.
2687
+	 *
2688
+	 * @param EE_Base_Class|int|string $id_or_obj
2689
+	 * @param string                   $model_name
2690
+	 * @param array                    $query_params
2691
+	 * @return int how many deleted
2692
+	 * @throws EE_Error
2693
+	 */
2694
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2695
+	{
2696
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2697
+		$relation_settings = $this->related_settings_for($model_name);
2698
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2699
+	}
2700
+
2701
+
2702
+	/**
2703
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2704
+	 * unless otherwise specified in the $query_params
2705
+	 *
2706
+	 * @param int             /EE_Base_Class $id_or_obj
2707
+	 * @param string $model_name     like 'Event', or 'Registration'
2708
+	 * @param array  $query_params   @see
2709
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2710
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2711
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2712
+	 *                               that by the setting $distinct to TRUE;
2713
+	 * @return int
2714
+	 * @throws EE_Error
2715
+	 */
2716
+	public function count_related(
2717
+		$id_or_obj,
2718
+		$model_name,
2719
+		$query_params = [],
2720
+		$field_to_count = null,
2721
+		$distinct = false
2722
+	) {
2723
+		$related_model = $this->get_related_model_obj($model_name);
2724
+		// we're just going to use the query params on the related model's normal get_all query,
2725
+		// except add a condition to say to match the current mod
2726
+		if (! isset($query_params['default_where_conditions'])) {
2727
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2728
+		}
2729
+		$this_model_name                                                 = $this->get_this_model_name();
2730
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2731
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2732
+		return $related_model->count($query_params, $field_to_count, $distinct);
2733
+	}
2734
+
2735
+
2736
+	/**
2737
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2738
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2739
+	 *
2740
+	 * @param int           /EE_Base_Class $id_or_obj
2741
+	 * @param string $model_name   like 'Event', or 'Registration'
2742
+	 * @param array  $query_params @see
2743
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2744
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2745
+	 * @return float
2746
+	 * @throws EE_Error
2747
+	 */
2748
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2749
+	{
2750
+		$related_model = $this->get_related_model_obj($model_name);
2751
+		if (! is_array($query_params)) {
2752
+			EE_Error::doing_it_wrong(
2753
+				'EEM_Base::sum_related',
2754
+				sprintf(
2755
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2756
+					gettype($query_params)
2757
+				),
2758
+				'4.6.0'
2759
+			);
2760
+			$query_params = [];
2761
+		}
2762
+		// we're just going to use the query params on the related model's normal get_all query,
2763
+		// except add a condition to say to match the current mod
2764
+		if (! isset($query_params['default_where_conditions'])) {
2765
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2766
+		}
2767
+		$this_model_name                                                 = $this->get_this_model_name();
2768
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2769
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2770
+		return $related_model->sum($query_params, $field_to_sum);
2771
+	}
2772
+
2773
+
2774
+	/**
2775
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2776
+	 * $modelObject
2777
+	 *
2778
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2779
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2780
+	 * @param array               $query_params     @see
2781
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2782
+	 * @return EE_Base_Class
2783
+	 * @throws EE_Error
2784
+	 */
2785
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2786
+	{
2787
+		$query_params['limit'] = 1;
2788
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2789
+		if ($results) {
2790
+			return array_shift($results);
2791
+		}
2792
+		return null;
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2798
+	 *
2799
+	 * @return string
2800
+	 */
2801
+	public function get_this_model_name()
2802
+	{
2803
+		return str_replace("EEM_", "", get_class($this));
2804
+	}
2805
+
2806
+
2807
+	/**
2808
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2809
+	 *
2810
+	 * @return EE_Any_Foreign_Model_Name_Field
2811
+	 * @throws EE_Error
2812
+	 */
2813
+	public function get_field_containing_related_model_name()
2814
+	{
2815
+		foreach ($this->field_settings(true) as $field) {
2816
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2817
+				$field_with_model_name = $field;
2818
+			}
2819
+		}
2820
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2821
+			throw new EE_Error(
2822
+				sprintf(
2823
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2824
+					$this->get_this_model_name()
2825
+				)
2826
+			);
2827
+		}
2828
+		return $field_with_model_name;
2829
+	}
2830
+
2831
+
2832
+	/**
2833
+	 * Inserts a new entry into the database, for each table.
2834
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2835
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2836
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2837
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2838
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2839
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2840
+	 *
2841
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2842
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2843
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2844
+	 *                              of EEM_Base)
2845
+	 * @return int|string new primary key on main table that got inserted
2846
+	 * @throws EE_Error
2847
+	 */
2848
+	public function insert($field_n_values)
2849
+	{
2850
+		/**
2851
+		 * Filters the fields and their values before inserting an item using the models
2852
+		 *
2853
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2854
+		 * @param EEM_Base $model           the model used
2855
+		 */
2856
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2857
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2858
+			$main_table = $this->_get_main_table();
2859
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2860
+			if ($new_id !== false) {
2861
+				foreach ($this->_get_other_tables() as $other_table) {
2862
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2863
+				}
2864
+			}
2865
+			/**
2866
+			 * Done just after attempting to insert a new model object
2867
+			 *
2868
+			 * @param EEM_Base $model           used
2869
+			 * @param array    $fields_n_values fields and their values
2870
+			 * @param int|string the              ID of the newly-inserted model object
2871
+			 */
2872
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2873
+			return $new_id;
2874
+		}
2875
+		return false;
2876
+	}
2877
+
2878
+
2879
+	/**
2880
+	 * Checks that the result would satisfy the unique indexes on this model
2881
+	 *
2882
+	 * @param array  $field_n_values
2883
+	 * @param string $action
2884
+	 * @return boolean
2885
+	 * @throws EE_Error
2886
+	 */
2887
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2888
+	{
2889
+		foreach ($this->unique_indexes() as $index_name => $index) {
2890
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2891
+			if ($this->exists([$uniqueness_where_params])) {
2892
+				EE_Error::add_error(
2893
+					sprintf(
2894
+						esc_html__(
2895
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2896
+							"event_espresso"
2897
+						),
2898
+						$action,
2899
+						$this->_get_class_name(),
2900
+						$index_name,
2901
+						implode(",", $index->field_names()),
2902
+						http_build_query($uniqueness_where_params)
2903
+					),
2904
+					__FILE__,
2905
+					__FUNCTION__,
2906
+					__LINE__
2907
+				);
2908
+				return false;
2909
+			}
2910
+		}
2911
+		return true;
2912
+	}
2913
+
2914
+
2915
+	/**
2916
+	 * Checks the database for an item that conflicts (ie, if this item were
2917
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2918
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2919
+	 * can be either an EE_Base_Class or an array of fields n values
2920
+	 *
2921
+	 * @param EE_Base_Class|array $obj_or_fields_array
2922
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2923
+	 *                                                 when looking for conflicts
2924
+	 *                                                 (ie, if false, we ignore the model object's primary key
2925
+	 *                                                 when finding "conflicts". If true, it's also considered).
2926
+	 *                                                 Only works for INT primary key,
2927
+	 *                                                 STRING primary keys cannot be ignored
2928
+	 * @return EE_Base_Class|array
2929
+	 * @throws EE_Error
2930
+	 */
2931
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2932
+	{
2933
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2934
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2935
+		} elseif (is_array($obj_or_fields_array)) {
2936
+			$fields_n_values = $obj_or_fields_array;
2937
+		} else {
2938
+			throw new EE_Error(
2939
+				sprintf(
2940
+					esc_html__(
2941
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2942
+						"event_espresso"
2943
+					),
2944
+					get_class($this),
2945
+					$obj_or_fields_array
2946
+				)
2947
+			);
2948
+		}
2949
+		$query_params = [];
2950
+		if (
2951
+			$this->has_primary_key_field()
2952
+			&& ($include_primary_key
2953
+				|| $this->get_primary_key_field()
2954
+				   instanceof
2955
+				   EE_Primary_Key_String_Field)
2956
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2957
+		) {
2958
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2959
+		}
2960
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2961
+			$uniqueness_where_params                              =
2962
+				array_intersect_key($fields_n_values, $unique_index->fields());
2963
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2964
+		}
2965
+		// if there is nothing to base this search on, then we shouldn't find anything
2966
+		if (empty($query_params)) {
2967
+			return [];
2968
+		}
2969
+		return $this->get_one($query_params);
2970
+	}
2971
+
2972
+
2973
+	/**
2974
+	 * Like count, but is optimized and returns a boolean instead of an int
2975
+	 *
2976
+	 * @param array $query_params
2977
+	 * @return boolean
2978
+	 * @throws EE_Error
2979
+	 */
2980
+	public function exists($query_params)
2981
+	{
2982
+		$query_params['limit'] = 1;
2983
+		return $this->count($query_params) > 0;
2984
+	}
2985
+
2986
+
2987
+	/**
2988
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2989
+	 *
2990
+	 * @param int|string $id
2991
+	 * @return boolean
2992
+	 * @throws EE_Error
2993
+	 */
2994
+	public function exists_by_ID($id)
2995
+	{
2996
+		return $this->exists(
2997
+			[
2998
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2999
+				[
3000
+					$this->primary_key_name() => $id,
3001
+				],
3002
+			]
3003
+		);
3004
+	}
3005
+
3006
+
3007
+	/**
3008
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3009
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3010
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3011
+	 * on the main table)
3012
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3013
+	 * cases where we want to call it directly rather than via insert().
3014
+	 *
3015
+	 * @access   protected
3016
+	 * @param EE_Table_Base $table
3017
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3018
+	 *                                       float
3019
+	 * @param int           $new_id          for now we assume only int keys
3020
+	 * @return int ID of new row inserted, or FALSE on failure
3021
+	 * @throws EE_Error
3022
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3023
+	 */
3024
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3025
+	{
3026
+		global $wpdb;
3027
+		$insertion_col_n_values = [];
3028
+		$format_for_insertion   = [];
3029
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3030
+		foreach ($fields_on_table as $field_name => $field_obj) {
3031
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3032
+			if ($field_obj->is_auto_increment()) {
3033
+				continue;
3034
+			}
3035
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3036
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3037
+			if ($prepared_value !== null) {
3038
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3039
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3040
+			}
3041
+		}
3042
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3043
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3044
+			// so add the fk to the main table as a column
3045
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3046
+			$format_for_insertion[]                              =
3047
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3048
+		}
3049
+
3050
+		// insert the new entry
3051
+		$result = $this->_do_wpdb_query(
3052
+			'insert',
3053
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3054
+		);
3055
+		if ($result === false) {
3056
+			return false;
3057
+		}
3058
+		// ok, now what do we return for the ID of the newly-inserted thing?
3059
+		if ($this->has_primary_key_field()) {
3060
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3061
+				return $wpdb->insert_id;
3062
+			}
3063
+			// it's not an auto-increment primary key, so
3064
+			// it must have been supplied
3065
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3066
+		}
3067
+		// we can't return a  primary key because there is none. instead return
3068
+		// a unique string indicating this model
3069
+		return $this->get_index_primary_key_string($fields_n_values);
3070
+	}
3071
+
3072
+
3073
+	/**
3074
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3075
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3076
+	 * and there is no default, we pass it along. WPDB will take care of it)
3077
+	 *
3078
+	 * @param EE_Model_Field_Base $field_obj
3079
+	 * @param array               $fields_n_values
3080
+	 * @return mixed string|int|float depending on what the table column will be expecting
3081
+	 * @throws EE_Error
3082
+	 */
3083
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3084
+	{
3085
+		$field_name = $field_obj->get_name();
3086
+		// if this field doesn't allow nullable, don't allow it
3087
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3088
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3089
+		}
3090
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3091
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
+	}
3093
+
3094
+
3095
+	/**
3096
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
+	 * the field's prepare_for_set() method.
3099
+	 *
3100
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
+	 *                                   top of file)
3103
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
+	 *                                   $value is a custom selection
3105
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
+	 */
3107
+	private function _prepare_value_for_use_in_db($value, $field)
3108
+	{
3109
+		if ($field instanceof EE_Model_Field_Base) {
3110
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
+			switch ($this->_values_already_prepared_by_model_object) {
3112
+				/** @noinspection PhpMissingBreakStatementInspection */
3113
+				case self::not_prepared_by_model_object:
3114
+					$value = $field->prepare_for_set($value);
3115
+				// purposefully left out "return"
3116
+				// no break
3117
+				case self::prepared_by_model_object:
3118
+					/** @noinspection SuspiciousAssignmentsInspection */
3119
+					$value = $field->prepare_for_use_in_db($value);
3120
+				// no break
3121
+				case self::prepared_for_use_in_db:
3122
+					// leave the value alone
3123
+			}
3124
+			// phpcs:enable
3125
+		}
3126
+		return $value;
3127
+	}
3128
+
3129
+
3130
+	/**
3131
+	 * Returns the main table on this model
3132
+	 *
3133
+	 * @return EE_Primary_Table
3134
+	 * @throws EE_Error
3135
+	 */
3136
+	protected function _get_main_table()
3137
+	{
3138
+		foreach ($this->_tables as $table) {
3139
+			if ($table instanceof EE_Primary_Table) {
3140
+				return $table;
3141
+			}
3142
+		}
3143
+		throw new EE_Error(
3144
+			sprintf(
3145
+				esc_html__(
3146
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3147
+					'event_espresso'
3148
+				),
3149
+				get_class($this)
3150
+			)
3151
+		);
3152
+	}
3153
+
3154
+
3155
+	/**
3156
+	 * table
3157
+	 * returns EE_Primary_Table table name
3158
+	 *
3159
+	 * @return string
3160
+	 * @throws EE_Error
3161
+	 */
3162
+	public function table()
3163
+	{
3164
+		return $this->_get_main_table()->get_table_name();
3165
+	}
3166
+
3167
+
3168
+	/**
3169
+	 * table
3170
+	 * returns first EE_Secondary_Table table name
3171
+	 *
3172
+	 * @return string
3173
+	 */
3174
+	public function second_table()
3175
+	{
3176
+		// grab second table from tables array
3177
+		$second_table = end($this->_tables);
3178
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3179
+	}
3180
+
3181
+
3182
+	/**
3183
+	 * get_table_obj_by_alias
3184
+	 * returns table name given it's alias
3185
+	 *
3186
+	 * @param string $table_alias
3187
+	 * @return EE_Primary_Table | EE_Secondary_Table
3188
+	 */
3189
+	public function get_table_obj_by_alias($table_alias = '')
3190
+	{
3191
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3192
+	}
3193
+
3194
+
3195
+	/**
3196
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3197
+	 *
3198
+	 * @return EE_Secondary_Table[]
3199
+	 */
3200
+	protected function _get_other_tables()
3201
+	{
3202
+		$other_tables = [];
3203
+		foreach ($this->_tables as $table_alias => $table) {
3204
+			if ($table instanceof EE_Secondary_Table) {
3205
+				$other_tables[ $table_alias ] = $table;
3206
+			}
3207
+		}
3208
+		return $other_tables;
3209
+	}
3210
+
3211
+
3212
+	/**
3213
+	 * Finds all the fields that correspond to the given table
3214
+	 *
3215
+	 * @param string $table_alias , array key in EEM_Base::_tables
3216
+	 * @return EE_Model_Field_Base[]
3217
+	 */
3218
+	public function _get_fields_for_table($table_alias)
3219
+	{
3220
+		return $this->_fields[ $table_alias ];
3221
+	}
3222
+
3223
+
3224
+	/**
3225
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3226
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3227
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3228
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3229
+	 * related Registration, Transaction, and Payment models.
3230
+	 *
3231
+	 * @param array $query_params @see
3232
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3233
+	 * @return EE_Model_Query_Info_Carrier
3234
+	 * @throws EE_Error
3235
+	 */
3236
+	public function _extract_related_models_from_query($query_params)
3237
+	{
3238
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3239
+		if (array_key_exists(0, $query_params)) {
3240
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3241
+		}
3242
+		if (array_key_exists('group_by', $query_params)) {
3243
+			if (is_array($query_params['group_by'])) {
3244
+				$this->_extract_related_models_from_sub_params_array_values(
3245
+					$query_params['group_by'],
3246
+					$query_info_carrier,
3247
+					'group_by'
3248
+				);
3249
+			} elseif (! empty($query_params['group_by'])) {
3250
+				$this->_extract_related_model_info_from_query_param(
3251
+					$query_params['group_by'],
3252
+					$query_info_carrier,
3253
+					'group_by'
3254
+				);
3255
+			}
3256
+		}
3257
+		if (array_key_exists('having', $query_params)) {
3258
+			$this->_extract_related_models_from_sub_params_array_keys(
3259
+				$query_params[0],
3260
+				$query_info_carrier,
3261
+				'having'
3262
+			);
3263
+		}
3264
+		if (array_key_exists('order_by', $query_params)) {
3265
+			if (is_array($query_params['order_by'])) {
3266
+				$this->_extract_related_models_from_sub_params_array_keys(
3267
+					$query_params['order_by'],
3268
+					$query_info_carrier,
3269
+					'order_by'
3270
+				);
3271
+			} elseif (! empty($query_params['order_by'])) {
3272
+				$this->_extract_related_model_info_from_query_param(
3273
+					$query_params['order_by'],
3274
+					$query_info_carrier,
3275
+					'order_by'
3276
+				);
3277
+			}
3278
+		}
3279
+		if (array_key_exists('force_join', $query_params)) {
3280
+			$this->_extract_related_models_from_sub_params_array_values(
3281
+				$query_params['force_join'],
3282
+				$query_info_carrier,
3283
+				'force_join'
3284
+			);
3285
+		}
3286
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3287
+		return $query_info_carrier;
3288
+	}
3289
+
3290
+
3291
+	/**
3292
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3293
+	 *
3294
+	 * @param array                       $sub_query_params @see
3295
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3296
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3297
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3298
+	 * @throws EE_Error
3299
+	 * @return \EE_Model_Query_Info_Carrier
3300
+	 */
3301
+	private function _extract_related_models_from_sub_params_array_keys(
3302
+		$sub_query_params,
3303
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304
+		$query_param_type
3305
+	) {
3306
+		if (! empty($sub_query_params)) {
3307
+			$sub_query_params = (array) $sub_query_params;
3308
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3310
+				$this->_extract_related_model_info_from_query_param(
3311
+					$param,
3312
+					$model_query_info_carrier,
3313
+					$query_param_type
3314
+				);
3315
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3316
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3317
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3318
+				// of array('Registration.TXN_ID'=>23)
3319
+				$query_param_sans_stars =
3320
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
+					if (! is_array($possibly_array_of_params)) {
3323
+						throw new EE_Error(
3324
+							sprintf(
3325
+								esc_html__(
3326
+									"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'))",
3327
+									"event_espresso"
3328
+								),
3329
+								$param,
3330
+								$possibly_array_of_params
3331
+							)
3332
+						);
3333
+					}
3334
+					$this->_extract_related_models_from_sub_params_array_keys(
3335
+						$possibly_array_of_params,
3336
+						$model_query_info_carrier,
3337
+						$query_param_type
3338
+					);
3339
+				} elseif (
3340
+					$query_param_type === 0 // ie WHERE
3341
+					&& is_array($possibly_array_of_params)
3342
+					&& isset($possibly_array_of_params[2])
3343
+					&& $possibly_array_of_params[2] == true
3344
+				) {
3345
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346
+					// indicating that $possible_array_of_params[1] is actually a field name,
3347
+					// from which we should extract query parameters!
3348
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349
+						throw new EE_Error(
3350
+							sprintf(
3351
+								esc_html__(
3352
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3353
+									"event_espresso"
3354
+								),
3355
+								$query_param_type,
3356
+								implode(",", $possibly_array_of_params)
3357
+							)
3358
+						);
3359
+					}
3360
+					$this->_extract_related_model_info_from_query_param(
3361
+						$possibly_array_of_params[1],
3362
+						$model_query_info_carrier,
3363
+						$query_param_type
3364
+					);
3365
+				}
3366
+			}
3367
+		}
3368
+		return $model_query_info_carrier;
3369
+	}
3370
+
3371
+
3372
+	/**
3373
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3374
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3375
+	 *
3376
+	 * @param array                       $sub_query_params @see
3377
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3378
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3379
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3380
+	 * @throws EE_Error
3381
+	 * @return \EE_Model_Query_Info_Carrier
3382
+	 */
3383
+	private function _extract_related_models_from_sub_params_array_values(
3384
+		$sub_query_params,
3385
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386
+		$query_param_type
3387
+	) {
3388
+		if (! empty($sub_query_params)) {
3389
+			if (! is_array($sub_query_params)) {
3390
+				throw new EE_Error(
3391
+					sprintf(
3392
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3393
+						$sub_query_params
3394
+					)
3395
+				);
3396
+			}
3397
+			foreach ($sub_query_params as $param) {
3398
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3399
+				$this->_extract_related_model_info_from_query_param(
3400
+					$param,
3401
+					$model_query_info_carrier,
3402
+					$query_param_type
3403
+				);
3404
+			}
3405
+		}
3406
+		return $model_query_info_carrier;
3407
+	}
3408
+
3409
+
3410
+	/**
3411
+	 * Extract all the query parts from  model query params
3412
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3413
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3414
+	 * but use them in a different order. Eg, we need to know what models we are querying
3415
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3416
+	 * other models before we can finalize the where clause SQL.
3417
+	 *
3418
+	 * @param array $query_params @see
3419
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3420
+	 * @throws EE_Error
3421
+	 * @return EE_Model_Query_Info_Carrier
3422
+	 * @throws ModelConfigurationException
3423
+	 */
3424
+	public function _create_model_query_info_carrier($query_params)
3425
+	{
3426
+		if (! is_array($query_params)) {
3427
+			EE_Error::doing_it_wrong(
3428
+				'EEM_Base::_create_model_query_info_carrier',
3429
+				sprintf(
3430
+					esc_html__(
3431
+						'$query_params should be an array, you passed a variable of type %s',
3432
+						'event_espresso'
3433
+					),
3434
+					gettype($query_params)
3435
+				),
3436
+				'4.6.0'
3437
+			);
3438
+			$query_params = [];
3439
+		}
3440
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
+		// first check if we should alter the query to account for caps or not
3442
+		// because the caps might require us to do extra joins
3443
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
+			$query_params[0] = array_replace_recursive(
3445
+				$query_params[0],
3446
+				$this->caps_where_conditions($query_params['caps'])
3447
+			);
3448
+		}
3449
+
3450
+		// check if we should alter the query to remove data related to protected
3451
+		// custom post types
3452
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3453
+			$where_param_key_for_password = $this->modelChainAndPassword();
3454
+			// only include if related to a cpt where no password has been set
3455
+			$query_params[0]['OR*nopassword'] = [
3456
+				$where_param_key_for_password       => '',
3457
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3458
+			];
3459
+		}
3460
+		$query_object = $this->_extract_related_models_from_query($query_params);
3461
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3462
+		foreach ($query_params[0] as $key => $value) {
3463
+			if (is_int($key)) {
3464
+				throw new EE_Error(
3465
+					sprintf(
3466
+						esc_html__(
3467
+							"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.",
3468
+							"event_espresso"
3469
+						),
3470
+						$key,
3471
+						var_export($value, true),
3472
+						var_export($query_params, true),
3473
+						get_class($this)
3474
+					)
3475
+				);
3476
+			}
3477
+		}
3478
+		if (
3479
+			array_key_exists('default_where_conditions', $query_params)
3480
+			&& ! empty($query_params['default_where_conditions'])
3481
+		) {
3482
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3483
+		} else {
3484
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3485
+		}
3486
+		$query_params[0] = array_merge(
3487
+			$this->_get_default_where_conditions_for_models_in_query(
3488
+				$query_object,
3489
+				$use_default_where_conditions,
3490
+				$query_params[0]
3491
+			),
3492
+			$query_params[0]
3493
+		);
3494
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3495
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3496
+		// So we need to setup a subquery and use that for the main join.
3497
+		// Note for now this only works on the primary table for the model.
3498
+		// So for instance, you could set the limit array like this:
3499
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3500
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3501
+			$query_object->set_main_model_join_sql(
3502
+				$this->_construct_limit_join_select(
3503
+					$query_params['on_join_limit'][0],
3504
+					$query_params['on_join_limit'][1]
3505
+				)
3506
+			);
3507
+		}
3508
+		// set limit
3509
+		if (array_key_exists('limit', $query_params)) {
3510
+			if (is_array($query_params['limit'])) {
3511
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3512
+					$e = sprintf(
3513
+						esc_html__(
3514
+							"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)",
3515
+							"event_espresso"
3516
+						),
3517
+						http_build_query($query_params['limit'])
3518
+					);
3519
+					throw new EE_Error($e . "|" . $e);
3520
+				}
3521
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3522
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3523
+			} elseif (! empty($query_params['limit'])) {
3524
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3525
+			}
3526
+		}
3527
+		// set order by
3528
+		if (array_key_exists('order_by', $query_params)) {
3529
+			if (is_array($query_params['order_by'])) {
3530
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3531
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3532
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3533
+				if (array_key_exists('order', $query_params)) {
3534
+					throw new EE_Error(
3535
+						sprintf(
3536
+							esc_html__(
3537
+								"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 ",
3538
+								"event_espresso"
3539
+							),
3540
+							get_class($this),
3541
+							implode(", ", array_keys($query_params['order_by'])),
3542
+							implode(", ", $query_params['order_by']),
3543
+							$query_params['order']
3544
+						)
3545
+					);
3546
+				}
3547
+				$this->_extract_related_models_from_sub_params_array_keys(
3548
+					$query_params['order_by'],
3549
+					$query_object,
3550
+					'order_by'
3551
+				);
3552
+				// assume it's an array of fields to order by
3553
+				$order_array = [];
3554
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3555
+					$order         = $this->_extract_order($order);
3556
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3557
+				}
3558
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3559
+			} elseif (! empty($query_params['order_by'])) {
3560
+				$this->_extract_related_model_info_from_query_param(
3561
+					$query_params['order_by'],
3562
+					$query_object,
3563
+					'order',
3564
+					$query_params['order_by']
3565
+				);
3566
+				$order = isset($query_params['order'])
3567
+					? $this->_extract_order($query_params['order'])
3568
+					: 'DESC';
3569
+				$query_object->set_order_by_sql(
3570
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3571
+				);
3572
+			}
3573
+		}
3574
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3575
+		if (
3576
+			! array_key_exists('order_by', $query_params)
3577
+			&& array_key_exists('order', $query_params)
3578
+			&& ! empty($query_params['order'])
3579
+		) {
3580
+			$pk_field = $this->get_primary_key_field();
3581
+			$order    = $this->_extract_order($query_params['order']);
3582
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3583
+		}
3584
+		// set group by
3585
+		if (array_key_exists('group_by', $query_params)) {
3586
+			if (is_array($query_params['group_by'])) {
3587
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3588
+				$group_by_array = [];
3589
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3590
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3591
+				}
3592
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3593
+			} elseif (! empty($query_params['group_by'])) {
3594
+				$query_object->set_group_by_sql(
3595
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3596
+				);
3597
+			}
3598
+		}
3599
+		// set having
3600
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3601
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3602
+		}
3603
+		// now, just verify they didn't pass anything wack
3604
+		foreach ($query_params as $query_key => $query_value) {
3605
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3606
+				throw new EE_Error(
3607
+					sprintf(
3608
+						esc_html__(
3609
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3610
+							'event_espresso'
3611
+						),
3612
+						$query_key,
3613
+						get_class($this),
3614
+						//                      print_r( $this->_allowed_query_params, TRUE )
3615
+						implode(',', $this->_allowed_query_params)
3616
+					)
3617
+				);
3618
+			}
3619
+		}
3620
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3621
+		if (empty($main_model_join_sql)) {
3622
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3623
+		}
3624
+		return $query_object;
3625
+	}
3626
+
3627
+
3628
+	/**
3629
+	 * Gets the where conditions that should be imposed on the query based on the
3630
+	 * context (eg reading frontend, backend, edit or delete).
3631
+	 *
3632
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3633
+	 * @return array @see
3634
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3635
+	 * @throws EE_Error
3636
+	 */
3637
+	public function caps_where_conditions($context = self::caps_read)
3638
+	{
3639
+		EEM_Base::verify_is_valid_cap_context($context);
3640
+		$cap_where_conditions = [];
3641
+		$cap_restrictions     = $this->caps_missing($context);
3642
+		/**
3643
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3644
+		 */
3645
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3646
+			$cap_where_conditions = array_replace_recursive(
3647
+				$cap_where_conditions,
3648
+				$restriction_if_no_cap->get_default_where_conditions()
3649
+			);
3650
+		}
3651
+		return apply_filters(
3652
+			'FHEE__EEM_Base__caps_where_conditions__return',
3653
+			$cap_where_conditions,
3654
+			$this,
3655
+			$context,
3656
+			$cap_restrictions
3657
+		);
3658
+	}
3659
+
3660
+
3661
+	/**
3662
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3663
+	 * otherwise throws an exception
3664
+	 *
3665
+	 * @param string $should_be_order_string
3666
+	 * @return string either ASC, asc, DESC or desc
3667
+	 * @throws EE_Error
3668
+	 */
3669
+	private function _extract_order($should_be_order_string)
3670
+	{
3671
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3672
+			return $should_be_order_string;
3673
+		}
3674
+		throw new EE_Error(
3675
+			sprintf(
3676
+				esc_html__(
3677
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3678
+					"event_espresso"
3679
+				),
3680
+				get_class($this),
3681
+				$should_be_order_string
3682
+			)
3683
+		);
3684
+	}
3685
+
3686
+
3687
+	/**
3688
+	 * Looks at all the models which are included in this query, and asks each
3689
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3690
+	 * so they can be merged
3691
+	 *
3692
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3693
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3694
+	 *                                                                  'none' means NO default where conditions will
3695
+	 *                                                                  be used AT ALL during this query.
3696
+	 *                                                                  'other_models_only' means default where
3697
+	 *                                                                  conditions from other models will be used, but
3698
+	 *                                                                  not for this primary model. 'all', the default,
3699
+	 *                                                                  means default where conditions will apply as
3700
+	 *                                                                  normal
3701
+	 * @param array                       $where_query_params           @see
3702
+	 *                                                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3703
+	 * @return array @see
3704
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3705
+	 * @throws EE_Error
3706
+	 */
3707
+	private function _get_default_where_conditions_for_models_in_query(
3708
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3709
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3710
+		$where_query_params = []
3711
+	) {
3712
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3713
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3714
+			throw new EE_Error(
3715
+				sprintf(
3716
+					esc_html__(
3717
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3718
+						"event_espresso"
3719
+					),
3720
+					$use_default_where_conditions,
3721
+					implode(", ", $allowed_used_default_where_conditions_values)
3722
+				)
3723
+			);
3724
+		}
3725
+		$universal_query_params = [];
3726
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3727
+			$universal_query_params = $this->_get_default_where_conditions();
3728
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3729
+			$universal_query_params = $this->_get_minimum_where_conditions();
3730
+		}
3731
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3732
+			$related_model = $this->get_related_model_obj($model_name);
3733
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3734
+				$related_model_universal_where_params =
3735
+					$related_model->_get_default_where_conditions($model_relation_path);
3736
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3737
+				$related_model_universal_where_params =
3738
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3739
+			} else {
3740
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3741
+				continue;
3742
+			}
3743
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3744
+				$related_model_universal_where_params,
3745
+				$where_query_params,
3746
+				$related_model,
3747
+				$model_relation_path
3748
+			);
3749
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3750
+				$universal_query_params,
3751
+				$overrides
3752
+			);
3753
+		}
3754
+		return $universal_query_params;
3755
+	}
3756
+
3757
+
3758
+	/**
3759
+	 * Determines whether or not we should use default where conditions for the model in question
3760
+	 * (this model, or other related models).
3761
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3762
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3763
+	 * We should use default where conditions on related models when they requested to use default where conditions
3764
+	 * on all models, or specifically just on other related models
3765
+	 *
3766
+	 * @param      $default_where_conditions_value
3767
+	 * @param bool $for_this_model false means this is for OTHER related models
3768
+	 * @return bool
3769
+	 */
3770
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3771
+	{
3772
+		return (
3773
+				   $for_this_model
3774
+				   && in_array(
3775
+					   $default_where_conditions_value,
3776
+					   [
3777
+						   EEM_Base::default_where_conditions_all,
3778
+						   EEM_Base::default_where_conditions_this_only,
3779
+						   EEM_Base::default_where_conditions_minimum_others,
3780
+					   ],
3781
+					   true
3782
+				   )
3783
+			   )
3784
+			   || (
3785
+				   ! $for_this_model
3786
+				   && in_array(
3787
+					   $default_where_conditions_value,
3788
+					   [
3789
+						   EEM_Base::default_where_conditions_all,
3790
+						   EEM_Base::default_where_conditions_others_only,
3791
+					   ],
3792
+					   true
3793
+				   )
3794
+			   );
3795
+	}
3796
+
3797
+
3798
+	/**
3799
+	 * Determines whether or not we should use default minimum conditions for the model in question
3800
+	 * (this model, or other related models).
3801
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3802
+	 * where conditions.
3803
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3804
+	 * on this model or others
3805
+	 *
3806
+	 * @param      $default_where_conditions_value
3807
+	 * @param bool $for_this_model false means this is for OTHER related models
3808
+	 * @return bool
3809
+	 */
3810
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
+	{
3812
+		return (
3813
+				   $for_this_model
3814
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
+			   )
3816
+			   || (
3817
+				   ! $for_this_model
3818
+				   && in_array(
3819
+					   $default_where_conditions_value,
3820
+					   [
3821
+						   EEM_Base::default_where_conditions_minimum_others,
3822
+						   EEM_Base::default_where_conditions_minimum_all,
3823
+					   ],
3824
+					   true
3825
+				   )
3826
+			   );
3827
+	}
3828
+
3829
+
3830
+	/**
3831
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
+	 * then we also add a special where condition which allows for that model's primary key
3833
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
+	 *
3836
+	 * @param array    $default_where_conditions
3837
+	 * @param array    $provided_where_conditions
3838
+	 * @param EEM_Base $model
3839
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3840
+	 * @return array @see
3841
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3842
+	 * @throws EE_Error
3843
+	 */
3844
+	private function _override_defaults_or_make_null_friendly(
3845
+		$default_where_conditions,
3846
+		$provided_where_conditions,
3847
+		$model,
3848
+		$model_relation_path
3849
+	) {
3850
+		$null_friendly_where_conditions = [];
3851
+		$none_overridden                = true;
3852
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3853
+		foreach ($default_where_conditions as $key => $val) {
3854
+			if (isset($provided_where_conditions[ $key ])) {
3855
+				$none_overridden = false;
3856
+			} else {
3857
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3858
+			}
3859
+		}
3860
+		if ($none_overridden && $default_where_conditions) {
3861
+			if ($model->has_primary_key_field()) {
3862
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3863
+																				   . "."
3864
+																				   . $model->primary_key_name() ] =
3865
+					['IS NULL'];
3866
+			}/*else{
3867 3867
                 //@todo NO PK, use other defaults
3868 3868
             }*/
3869
-        }
3870
-        return $null_friendly_where_conditions;
3871
-    }
3872
-
3873
-
3874
-    /**
3875
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3876
-     * default where conditions on all get_all, update, and delete queries done by this model.
3877
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3878
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3879
-     *
3880
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3881
-     * @return array @see
3882
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3883
-     */
3884
-    private function _get_default_where_conditions($model_relation_path = '')
3885
-    {
3886
-        if ($this->_ignore_where_strategy) {
3887
-            return [];
3888
-        }
3889
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3890
-    }
3891
-
3892
-
3893
-    /**
3894
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3895
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3896
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3897
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3898
-     * Similar to _get_default_where_conditions
3899
-     *
3900
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3901
-     * @return array @see
3902
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
-     */
3904
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3905
-    {
3906
-        if ($this->_ignore_where_strategy) {
3907
-            return [];
3908
-        }
3909
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
-    }
3911
-
3912
-
3913
-    /**
3914
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
-     *
3917
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3918
-     * @return string
3919
-     * @throws EE_Error
3920
-     */
3921
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
-    {
3923
-        $selects = $this->_get_columns_to_select_for_this_model();
3924
-        foreach (
3925
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
-        ) {
3927
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
-            foreach ($other_model_selects as $key => $value) {
3930
-                $selects[] = $value;
3931
-            }
3932
-        }
3933
-        return implode(", ", $selects);
3934
-    }
3935
-
3936
-
3937
-    /**
3938
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
-     * So that's going to be the columns for all the fields on the model
3940
-     *
3941
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
-     */
3944
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
-    {
3946
-        $fields                                       = $this->field_settings();
3947
-        $selects                                      = [];
3948
-        $table_alias_with_model_relation_chain_prefix =
3949
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
-                $model_relation_chain,
3951
-                $this->get_this_model_name()
3952
-            );
3953
-        foreach ($fields as $field_obj) {
3954
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3955
-                         . $field_obj->get_table_alias()
3956
-                         . "."
3957
-                         . $field_obj->get_table_column()
3958
-                         . " AS '"
3959
-                         . $table_alias_with_model_relation_chain_prefix
3960
-                         . $field_obj->get_table_alias()
3961
-                         . "."
3962
-                         . $field_obj->get_table_column()
3963
-                         . "'";
3964
-        }
3965
-        // make sure we are also getting the PKs of each table
3966
-        $tables = $this->get_tables();
3967
-        if (count($tables) > 1) {
3968
-            foreach ($tables as $table_obj) {
3969
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
-                                       . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3972
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
-                }
3974
-            }
3975
-        }
3976
-        return $selects;
3977
-    }
3978
-
3979
-
3980
-    /**
3981
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
-     * SQL for joining, and the data types
3985
-     *
3986
-     * @param null|string                 $original_query_param
3987
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3988
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3990
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3991
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3992
-     *                                                          or 'Registration's
3993
-     * @param string                      $original_query_param what it originally was (eg
3994
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3995
-     *                                                          matches $query_param
3996
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
-     * @throws EE_Error
3998
-     */
3999
-    private function _extract_related_model_info_from_query_param(
4000
-        $query_param,
4001
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4002
-        $query_param_type,
4003
-        $original_query_param = null
4004
-    ) {
4005
-        if ($original_query_param === null) {
4006
-            $original_query_param = $query_param;
4007
-        }
4008
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4009
-        // check to see if we have a field on this model
4010
-        $this_model_fields = $this->field_settings(true);
4011
-        if (array_key_exists($query_param, $this_model_fields)) {
4012
-            $field_is_allowed = in_array(
4013
-                $query_param_type,
4014
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4015
-                true
4016
-            );
4017
-            if ($field_is_allowed) {
4018
-                return;
4019
-            }
4020
-            throw new EE_Error(
4021
-                sprintf(
4022
-                    esc_html__(
4023
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
-                        "event_espresso"
4025
-                    ),
4026
-                    $query_param,
4027
-                    get_class($this),
4028
-                    $query_param_type,
4029
-                    $original_query_param
4030
-                )
4031
-            );
4032
-        }
4033
-        // check if this is a special logic query param
4034
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4036
-            if ($operator_is_allowed) {
4037
-                return;
4038
-            }
4039
-            throw new EE_Error(
4040
-                sprintf(
4041
-                    esc_html__(
4042
-                        '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',
4043
-                        'event_espresso'
4044
-                    ),
4045
-                    implode('", "', $this->_logic_query_param_keys),
4046
-                    $query_param,
4047
-                    get_class($this),
4048
-                    '<br />',
4049
-                    "\t"
4050
-                    . ' $passed_in_query_info = <pre>'
4051
-                    . print_r($passed_in_query_info, true)
4052
-                    . '</pre>'
4053
-                    . "\n\t"
4054
-                    . ' $query_param_type = '
4055
-                    . $query_param_type
4056
-                    . "\n\t"
4057
-                    . ' $original_query_param = '
4058
-                    . $original_query_param
4059
-                )
4060
-            );
4061
-        }
4062
-        // check if it's a custom selection
4063
-        if (
4064
-            $this->_custom_selections instanceof CustomSelects
4065
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
-        ) {
4067
-            return;
4068
-        }
4069
-        // check if has a model name at the beginning
4070
-        // and
4071
-        // check if it's a field on a related model
4072
-        if (
4073
-            $this->extractJoinModelFromQueryParams(
4074
-                $passed_in_query_info,
4075
-                $query_param,
4076
-                $original_query_param,
4077
-                $query_param_type
4078
-            )
4079
-        ) {
4080
-            return;
4081
-        }
4082
-
4083
-        // ok so $query_param didn't start with a model name
4084
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4085
-        // it's wack, that's what it is
4086
-        throw new EE_Error(
4087
-            sprintf(
4088
-                esc_html__(
4089
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
-                    "event_espresso"
4091
-                ),
4092
-                $query_param,
4093
-                get_class($this),
4094
-                $query_param_type,
4095
-                $original_query_param
4096
-            )
4097
-        );
4098
-    }
4099
-
4100
-
4101
-    /**
4102
-     * Extracts any possible join model information from the provided possible_join_string.
4103
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
-     * join
4105
-     * parts that should be added to the query.
4106
-     *
4107
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
-     * @param null|string                 $original_query_param
4110
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
-     *                                                           etc.)
4113
-     * @return bool  returns true if a join was added and false if not.
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractJoinModelFromQueryParams(
4117
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4118
-        $possible_join_string,
4119
-        $original_query_param,
4120
-        $query_parameter_type
4121
-    ) {
4122
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
-                if ($possible_join_string === '') {
4127
-                    // nothing left to $query_param
4128
-                    // we should actually end in a field name, not a model like this!
4129
-                    throw new EE_Error(
4130
-                        sprintf(
4131
-                            esc_html__(
4132
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
-                                "event_espresso"
4134
-                            ),
4135
-                            $possible_join_string,
4136
-                            $query_parameter_type,
4137
-                            get_class($this),
4138
-                            $valid_related_model_name
4139
-                        )
4140
-                    );
4141
-                }
4142
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
-                $related_model_obj->_extract_related_model_info_from_query_param(
4144
-                    $possible_join_string,
4145
-                    $query_info_carrier,
4146
-                    $query_parameter_type,
4147
-                    $original_query_param
4148
-                );
4149
-                return true;
4150
-            }
4151
-            if ($possible_join_string === $valid_related_model_name) {
4152
-                $this->_add_join_to_model(
4153
-                    $valid_related_model_name,
4154
-                    $query_info_carrier,
4155
-                    $original_query_param
4156
-                );
4157
-                return true;
4158
-            }
4159
-        }
4160
-        return false;
4161
-    }
4162
-
4163
-
4164
-    /**
4165
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
-     *
4167
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
-     * @throws EE_Error
4169
-     */
4170
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
-    {
4172
-        if (
4173
-            $this->_custom_selections instanceof CustomSelects
4174
-            && (
4175
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4176
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4177
-            )
4178
-        ) {
4179
-            $original_selects = $this->_custom_selections->originalSelects();
4180
-            foreach ($original_selects as $alias => $select_configuration) {
4181
-                $this->extractJoinModelFromQueryParams(
4182
-                    $query_info_carrier,
4183
-                    $select_configuration[0],
4184
-                    $select_configuration[0],
4185
-                    'custom_selects'
4186
-                );
4187
-            }
4188
-        }
4189
-    }
4190
-
4191
-
4192
-    /**
4193
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4194
-     * and store it on $passed_in_query_info
4195
-     *
4196
-     * @param string                      $model_name
4197
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4198
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4199
-     *                                                          model and $model_name. Eg, if we are querying Event,
4200
-     *                                                          and are adding a join to 'Payment' with the original
4201
-     *                                                          query param key
4202
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4203
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4204
-     *                                                          Payment wants to add default query params so that it
4205
-     *                                                          will know what models to prepend onto its default query
4206
-     *                                                          params or in case it wants to rename tables (in case
4207
-     *                                                          there are multiple joins to the same table)
4208
-     * @return void
4209
-     * @throws EE_Error
4210
-     */
4211
-    private function _add_join_to_model(
4212
-        $model_name,
4213
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4214
-        $original_query_param
4215
-    ) {
4216
-        $relation_obj         = $this->related_settings_for($model_name);
4217
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4218
-        // check if the relation is HABTM, because then we're essentially doing two joins
4219
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4220
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4221
-            $join_model_obj = $relation_obj->get_join_model();
4222
-            // replace the model specified with the join model for this relation chain, whi
4223
-            $relation_chain_to_join_model =
4224
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4225
-                    $model_name,
4226
-                    $join_model_obj->get_this_model_name(),
4227
-                    $model_relation_chain
4228
-                );
4229
-            $passed_in_query_info->merge(
4230
-                new EE_Model_Query_Info_Carrier(
4231
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4232
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4233
-                )
4234
-            );
4235
-        }
4236
-        // now just join to the other table pointed to by the relation object, and add its data types
4237
-        $passed_in_query_info->merge(
4238
-            new EE_Model_Query_Info_Carrier(
4239
-                [$model_relation_chain => $model_name],
4240
-                $relation_obj->get_join_statement($model_relation_chain)
4241
-            )
4242
-        );
4243
-    }
4244
-
4245
-
4246
-    /**
4247
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4248
-     *
4249
-     * @param array $where_params @see
4250
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4251
-     * @return string of SQL
4252
-     * @throws EE_Error
4253
-     */
4254
-    private function _construct_where_clause($where_params)
4255
-    {
4256
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257
-        if ($SQL) {
4258
-            return " WHERE " . $SQL;
4259
-        }
4260
-        return '';
4261
-    }
4262
-
4263
-
4264
-    /**
4265
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4266
-     * and should be passed HAVING parameters, not WHERE parameters
4267
-     *
4268
-     * @param array $having_params
4269
-     * @return string
4270
-     * @throws EE_Error
4271
-     */
4272
-    private function _construct_having_clause($having_params)
4273
-    {
4274
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275
-        if ($SQL) {
4276
-            return " HAVING " . $SQL;
4277
-        }
4278
-        return '';
4279
-    }
4280
-
4281
-
4282
-    /**
4283
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4284
-     * Event_Meta.meta_value = 'foo'))"
4285
-     *
4286
-     * @param array  $where_params @see
4287
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4288
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4289
-     * @throws EE_Error
4290
-     * @return string of SQL
4291
-     */
4292
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4293
-    {
4294
-        $where_clauses = [];
4295
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4296
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4297
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4298
-                switch ($query_param) {
4299
-                    case 'not':
4300
-                    case 'NOT':
4301
-                        $where_clauses[] = "! ("
4302
-                                           . $this->_construct_condition_clause_recursive(
4303
-                                               $op_and_value_or_sub_condition,
4304
-                                               $glue
4305
-                                           )
4306
-                                           . ")";
4307
-                        break;
4308
-                    case 'and':
4309
-                    case 'AND':
4310
-                        $where_clauses[] = " ("
4311
-                                           . $this->_construct_condition_clause_recursive(
4312
-                                               $op_and_value_or_sub_condition,
4313
-                                               ' AND '
4314
-                                           )
4315
-                                           . ")";
4316
-                        break;
4317
-                    case 'or':
4318
-                    case 'OR':
4319
-                        $where_clauses[] = " ("
4320
-                                           . $this->_construct_condition_clause_recursive(
4321
-                                               $op_and_value_or_sub_condition,
4322
-                                               ' OR '
4323
-                                           )
4324
-                                           . ")";
4325
-                        break;
4326
-                }
4327
-            } else {
4328
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4329
-                // if it's not a normal field, maybe it's a custom selection?
4330
-                if (! $field_obj) {
4331
-                    if ($this->_custom_selections instanceof CustomSelects) {
4332
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4333
-                    } else {
4334
-                        throw new EE_Error(
4335
-                            sprintf(
4336
-                                esc_html__(
4337
-                                    "%s is neither a valid model field name, nor a custom selection",
4338
-                                    "event_espresso"
4339
-                                ),
4340
-                                $query_param
4341
-                            )
4342
-                        );
4343
-                    }
4344
-                }
4345
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4346
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4347
-            }
4348
-        }
4349
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4350
-    }
4351
-
4352
-
4353
-    /**
4354
-     * Takes the input parameter and extract the table name (alias) and column name
4355
-     *
4356
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4357
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4358
-     * @throws EE_Error
4359
-     */
4360
-    private function _deduce_column_name_from_query_param($query_param)
4361
-    {
4362
-        $field = $this->_deduce_field_from_query_param($query_param);
4363
-        if ($field) {
4364
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4365
-                $field->get_model_name(),
4366
-                $query_param
4367
-            );
4368
-            return $table_alias_prefix . $field->get_qualified_column();
4369
-        }
4370
-        if (
4371
-            $this->_custom_selections instanceof CustomSelects
4372
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4373
-        ) {
4374
-            // maybe it's custom selection item?
4375
-            // if so, just use it as the "column name"
4376
-            return $query_param;
4377
-        }
4378
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4379
-            ? implode(',', $this->_custom_selections->columnAliases())
4380
-            : '';
4381
-        throw new EE_Error(
4382
-            sprintf(
4383
-                esc_html__(
4384
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4385
-                    "event_espresso"
4386
-                ),
4387
-                $query_param,
4388
-                $custom_select_aliases
4389
-            )
4390
-        );
4391
-    }
4392
-
4393
-
4394
-    /**
4395
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4396
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4397
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4398
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4399
-     *
4400
-     * @param string $condition_query_param_key
4401
-     * @return string
4402
-     */
4403
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4404
-    {
4405
-        $pos_of_star = strpos($condition_query_param_key, '*');
4406
-        if ($pos_of_star === false) {
4407
-            return $condition_query_param_key;
4408
-        }
4409
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4410
-        return $condition_query_param_sans_star;
4411
-    }
4412
-
4413
-
4414
-    /**
4415
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4416
-     *
4417
-     * @param mixed      array | string    $op_and_value
4418
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4419
-     * @return string
4420
-     * @throws EE_Error
4421
-     */
4422
-    private function _construct_op_and_value($op_and_value, $field_obj)
4423
-    {
4424
-        if (is_array($op_and_value)) {
4425
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4426
-            if (! $operator) {
4427
-                $php_array_like_string = [];
4428
-                foreach ($op_and_value as $key => $value) {
4429
-                    $php_array_like_string[] = "$key=>$value";
4430
-                }
4431
-                throw new EE_Error(
4432
-                    sprintf(
4433
-                        esc_html__(
4434
-                            "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))",
4435
-                            "event_espresso"
4436
-                        ),
4437
-                        implode(",", $php_array_like_string)
4438
-                    )
4439
-                );
4440
-            }
4441
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4442
-        } else {
4443
-            $operator = '=';
4444
-            $value    = $op_and_value;
4445
-        }
4446
-        // check to see if the value is actually another field
4447
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4448
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4449
-        }
4450
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
-            // in this case, the value should be an array, or at least a comma-separated list
4452
-            // it will need to handle a little differently
4453
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4454
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4455
-            return $operator . SP . $cleaned_value;
4456
-        }
4457
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4458
-            // the value should be an array with count of two.
4459
-            if (count($value) !== 2) {
4460
-                throw new EE_Error(
4461
-                    sprintf(
4462
-                        esc_html__(
4463
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4464
-                            'event_espresso'
4465
-                        ),
4466
-                        "BETWEEN"
4467
-                    )
4468
-                );
4469
-            }
4470
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4471
-            return $operator . SP . $cleaned_value;
4472
-        }
4473
-        if (in_array($operator, $this->valid_null_style_operators())) {
4474
-            if ($value !== null) {
4475
-                throw new EE_Error(
4476
-                    sprintf(
4477
-                        esc_html__(
4478
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4479
-                            "event_espresso"
4480
-                        ),
4481
-                        $value,
4482
-                        $operator
4483
-                    )
4484
-                );
4485
-            }
4486
-            return $operator;
4487
-        }
4488
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4489
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4490
-            // remove other junk. So just treat it as a string.
4491
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4492
-        }
4493
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4494
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4495
-        }
4496
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4497
-            throw new EE_Error(
4498
-                sprintf(
4499
-                    esc_html__(
4500
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4501
-                        'event_espresso'
4502
-                    ),
4503
-                    $operator,
4504
-                    $operator
4505
-                )
4506
-            );
4507
-        }
4508
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4509
-            throw new EE_Error(
4510
-                sprintf(
4511
-                    esc_html__(
4512
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4513
-                        'event_espresso'
4514
-                    ),
4515
-                    $operator,
4516
-                    $operator
4517
-                )
4518
-            );
4519
-        }
4520
-        throw new EE_Error(
4521
-            sprintf(
4522
-                esc_html__(
4523
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4524
-                    "event_espresso"
4525
-                ),
4526
-                http_build_query($op_and_value)
4527
-            )
4528
-        );
4529
-    }
4530
-
4531
-
4532
-    /**
4533
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4534
-     *
4535
-     * @param array                      $values
4536
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4537
-     *                                              '%s'
4538
-     * @return string
4539
-     * @throws EE_Error
4540
-     */
4541
-    public function _construct_between_value($values, $field_obj)
4542
-    {
4543
-        $cleaned_values = [];
4544
-        foreach ($values as $value) {
4545
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4546
-        }
4547
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4548
-    }
4549
-
4550
-
4551
-    /**
4552
-     * Takes an array or a comma-separated list of $values and cleans them
4553
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4554
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4555
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4556
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4557
-     *
4558
-     * @param mixed                      $values    array or comma-separated string
4559
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4560
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4561
-     * @throws EE_Error
4562
-     */
4563
-    public function _construct_in_value($values, $field_obj)
4564
-    {
4565
-        $prepped = [];
4566
-        // check if the value is a CSV list
4567
-        if (is_string($values)) {
4568
-            // in which case, turn it into an array
4569
-            $values = explode(',', $values);
4570
-        }
4571
-        // make sure we only have one of each value in the list
4572
-        $values = array_unique($values);
4573
-        foreach ($values as $value) {
4574
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4575
-        }
4576
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4577
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4578
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4579
-        if (empty($prepped)) {
4580
-            $all_fields  = $this->field_settings();
4581
-            $first_field = reset($all_fields);
4582
-            $main_table  = $this->_get_main_table();
4583
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4584
-        }
4585
-        return '(' . implode(',', $prepped) . ')';
4586
-    }
4587
-
4588
-
4589
-    /**
4590
-     * @param mixed                      $value
4591
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4592
-     * @return false|null|string
4593
-     * @throws EE_Error
4594
-     */
4595
-    private function _wpdb_prepare_using_field($value, $field_obj)
4596
-    {
4597
-        /** @type WPDB $wpdb */
4598
-        global $wpdb;
4599
-        if ($field_obj instanceof EE_Model_Field_Base) {
4600
-            return $wpdb->prepare(
4601
-                $field_obj->get_wpdb_data_type(),
4602
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4603
-            );
4604
-        } //$field_obj should really just be a data type
4605
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4606
-            throw new EE_Error(
4607
-                sprintf(
4608
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4609
-                    $field_obj,
4610
-                    implode(",", $this->_valid_wpdb_data_types)
4611
-                )
4612
-            );
4613
-        }
4614
-        return $wpdb->prepare($field_obj, $value);
4615
-    }
4616
-
4617
-
4618
-    /**
4619
-     * Takes the input parameter and finds the model field that it indicates.
4620
-     *
4621
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4622
-     * @return EE_Model_Field_Base
4623
-     * @throws EE_Error
4624
-     */
4625
-    protected function _deduce_field_from_query_param($query_param_name)
4626
-    {
4627
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4628
-        // which will help us find the database table and column
4629
-        $query_param_parts = explode(".", $query_param_name);
4630
-        if (empty($query_param_parts)) {
4631
-            throw new EE_Error(
4632
-                sprintf(
4633
-                    esc_html__(
4634
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4635
-                        'event_espresso'
4636
-                    ),
4637
-                    $query_param_name
4638
-                )
4639
-            );
4640
-        }
4641
-        $number_of_parts       = count($query_param_parts);
4642
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4643
-        if ($number_of_parts === 1) {
4644
-            $field_name = $last_query_param_part;
4645
-            $model_obj  = $this;
4646
-        } else {// $number_of_parts >= 2
4647
-            // the last part is the column name, and there are only 2parts. therefore...
4648
-            $field_name = $last_query_param_part;
4649
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4650
-        }
4651
-        try {
4652
-            return $model_obj->field_settings_for($field_name);
4653
-        } catch (EE_Error $e) {
4654
-            return null;
4655
-        }
4656
-    }
4657
-
4658
-
4659
-    /**
4660
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4661
-     * alias and column which corresponds to it
4662
-     *
4663
-     * @param string $field_name
4664
-     * @return string
4665
-     * @throws EE_Error
4666
-     */
4667
-    public function _get_qualified_column_for_field($field_name)
4668
-    {
4669
-        $all_fields = $this->field_settings();
4670
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4671
-        if ($field) {
4672
-            return $field->get_qualified_column();
4673
-        }
4674
-        throw new EE_Error(
4675
-            sprintf(
4676
-                esc_html__(
4677
-                    "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.",
4678
-                    'event_espresso'
4679
-                ),
4680
-                $field_name,
4681
-                get_class($this)
4682
-            )
4683
-        );
4684
-    }
4685
-
4686
-
4687
-    /**
4688
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4689
-     * Example usage:
4690
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4691
-     *      array(),
4692
-     *      ARRAY_A,
4693
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4694
-     *  );
4695
-     * is equivalent to
4696
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4697
-     * and
4698
-     *  EEM_Event::instance()->get_all_wpdb_results(
4699
-     *      array(
4700
-     *          array(
4701
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4702
-     *          ),
4703
-     *          ARRAY_A,
4704
-     *          implode(
4705
-     *              ', ',
4706
-     *              array_merge(
4707
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4708
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4709
-     *              )
4710
-     *          )
4711
-     *      )
4712
-     *  );
4713
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4714
-     *
4715
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4716
-     *                                            and the one whose fields you are selecting for example: when querying
4717
-     *                                            tickets model and selecting fields from the tickets model you would
4718
-     *                                            leave this parameter empty, because no models are needed to join
4719
-     *                                            between the queried model and the selected one. Likewise when
4720
-     *                                            querying the datetime model and selecting fields from the tickets
4721
-     *                                            model, it would also be left empty, because there is a direct
4722
-     *                                            relation from datetimes to tickets, so no model is needed to join
4723
-     *                                            them together. However, when querying from the event model and
4724
-     *                                            selecting fields from the ticket model, you should provide the string
4725
-     *                                            'Datetime', indicating that the event model must first join to the
4726
-     *                                            datetime model in order to find its relation to ticket model.
4727
-     *                                            Also, when querying from the venue model and selecting fields from
4728
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4729
-     *                                            indicating you need to join the venue model to the event model,
4730
-     *                                            to the datetime model, in order to find its relation to the ticket
4731
-     *                                            model. This string is used to deduce the prefix that gets added onto
4732
-     *                                            the models' tables qualified columns
4733
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4734
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4735
-     *                                            qualified column names
4736
-     * @return array|string
4737
-     */
4738
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4739
-    {
4740
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4741
-        $qualified_columns = [];
4742
-        foreach ($this->field_settings() as $field_name => $field) {
4743
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4744
-        }
4745
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4746
-    }
4747
-
4748
-
4749
-    /**
4750
-     * constructs the select use on special limit joins
4751
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4752
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4753
-     * (as that is typically where the limits would be set).
4754
-     *
4755
-     * @param string       $table_alias The table the select is being built for
4756
-     * @param mixed|string $limit       The limit for this select
4757
-     * @return string                The final select join element for the query.
4758
-     */
4759
-    public function _construct_limit_join_select($table_alias, $limit)
4760
-    {
4761
-        $SQL = '';
4762
-        foreach ($this->_tables as $table_obj) {
4763
-            if ($table_obj instanceof EE_Primary_Table) {
4764
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4765
-                    ? $table_obj->get_select_join_limit($limit)
4766
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4767
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4768
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4769
-                    ? $table_obj->get_select_join_limit_join($limit)
4770
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4771
-            }
4772
-        }
4773
-        return $SQL;
4774
-    }
4775
-
4776
-
4777
-    /**
4778
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4779
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4780
-     *
4781
-     * @return string SQL
4782
-     * @throws EE_Error
4783
-     */
4784
-    public function _construct_internal_join()
4785
-    {
4786
-        $SQL = $this->_get_main_table()->get_table_sql();
4787
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4788
-        return $SQL;
4789
-    }
4790
-
4791
-
4792
-    /**
4793
-     * Constructs the SQL for joining all the tables on this model.
4794
-     * Normally $alias should be the primary table's alias, but in cases where
4795
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4796
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4797
-     * alias, this will construct SQL like:
4798
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4799
-     * With $alias being a secondary table's alias, this will construct SQL like:
4800
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4801
-     *
4802
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4803
-     * @return string
4804
-     */
4805
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4806
-    {
4807
-        $SQL               = '';
4808
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4809
-        foreach ($this->_tables as $table_obj) {
4810
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4811
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4812
-                    // so we're joining to this table, meaning the table is already in
4813
-                    // the FROM statement, BUT the primary table isn't. So we want
4814
-                    // to add the inverse join sql
4815
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4816
-                } else {
4817
-                    // just add a regular JOIN to this table from the primary table
4818
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4819
-                }
4820
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4821
-        }
4822
-        return $SQL;
4823
-    }
4824
-
4825
-
4826
-    /**
4827
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
-     * their data type (eg, '%s', '%d', etc)
4830
-     *
4831
-     * @return array
4832
-     */
4833
-    public function _get_data_types()
4834
-    {
4835
-        $data_types = [];
4836
-        foreach ($this->field_settings() as $field_obj) {
4837
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
-            /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
-        }
4841
-        return $data_types;
4842
-    }
4843
-
4844
-
4845
-    /**
4846
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4847
-     *
4848
-     * @param string $model_name
4849
-     * @return EEM_Base
4850
-     * @throws EE_Error
4851
-     */
4852
-    public function get_related_model_obj($model_name)
4853
-    {
4854
-        $model_classname = "EEM_" . $model_name;
4855
-        if (! class_exists($model_classname)) {
4856
-            throw new EE_Error(
4857
-                sprintf(
4858
-                    esc_html__(
4859
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4860
-                        'event_espresso'
4861
-                    ),
4862
-                    $model_name,
4863
-                    $model_classname
4864
-                )
4865
-            );
4866
-        }
4867
-        return call_user_func($model_classname . "::instance");
4868
-    }
4869
-
4870
-
4871
-    /**
4872
-     * Returns the array of EE_ModelRelations for this model.
4873
-     *
4874
-     * @return EE_Model_Relation_Base[]
4875
-     */
4876
-    public function relation_settings()
4877
-    {
4878
-        return $this->_model_relations;
4879
-    }
4880
-
4881
-
4882
-    /**
4883
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4884
-     * because without THOSE models, this model probably doesn't have much purpose.
4885
-     * (Eg, without an event, datetimes have little purpose.)
4886
-     *
4887
-     * @return EE_Belongs_To_Relation[]
4888
-     */
4889
-    public function belongs_to_relations()
4890
-    {
4891
-        $belongs_to_relations = [];
4892
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4893
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4894
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4895
-            }
4896
-        }
4897
-        return $belongs_to_relations;
4898
-    }
4899
-
4900
-
4901
-    /**
4902
-     * Returns the specified EE_Model_Relation, or throws an exception
4903
-     *
4904
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4905
-     * @return EE_Model_Relation_Base
4906
-     * @throws EE_Error
4907
-     */
4908
-    public function related_settings_for($relation_name)
4909
-    {
4910
-        $relatedModels = $this->relation_settings();
4911
-        if (! array_key_exists($relation_name, $relatedModels)) {
4912
-            throw new EE_Error(
4913
-                sprintf(
4914
-                    esc_html__(
4915
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4916
-                        'event_espresso'
4917
-                    ),
4918
-                    $relation_name,
4919
-                    $this->_get_class_name(),
4920
-                    implode(', ', array_keys($relatedModels))
4921
-                )
4922
-            );
4923
-        }
4924
-        return $relatedModels[ $relation_name ];
4925
-    }
4926
-
4927
-
4928
-    /**
4929
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4930
-     * fields
4931
-     *
4932
-     * @param string  $fieldName
4933
-     * @param boolean $include_db_only_fields
4934
-     * @return EE_Model_Field_Base
4935
-     * @throws EE_Error
4936
-     */
4937
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4938
-    {
4939
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4940
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4941
-            throw new EE_Error(
4942
-                sprintf(
4943
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4944
-                    $fieldName,
4945
-                    get_class($this)
4946
-                )
4947
-            );
4948
-        }
4949
-        return $fieldSettings[ $fieldName ];
4950
-    }
4951
-
4952
-
4953
-    /**
4954
-     * Checks if this field exists on this model
4955
-     *
4956
-     * @param string $fieldName a key in the model's _field_settings array
4957
-     * @return boolean
4958
-     */
4959
-    public function has_field($fieldName)
4960
-    {
4961
-        $fieldSettings = $this->field_settings(true);
4962
-        if (isset($fieldSettings[ $fieldName ])) {
4963
-            return true;
4964
-        }
4965
-        return false;
4966
-    }
4967
-
4968
-
4969
-    /**
4970
-     * Returns whether or not this model has a relation to the specified model
4971
-     *
4972
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4973
-     * @return boolean
4974
-     */
4975
-    public function has_relation($relation_name)
4976
-    {
4977
-        $relations = $this->relation_settings();
4978
-        if (isset($relations[ $relation_name ])) {
4979
-            return true;
4980
-        }
4981
-        return false;
4982
-    }
4983
-
4984
-
4985
-    /**
4986
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
-     * Eg, on EE_Answer that would be ANS_ID field object
4988
-     *
4989
-     * @param $field_obj
4990
-     * @return boolean
4991
-     */
4992
-    public function is_primary_key_field($field_obj)
4993
-    {
4994
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
-    }
4996
-
4997
-
4998
-    /**
4999
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5000
-     * Eg, on EE_Answer that would be ANS_ID field object
5001
-     *
5002
-     * @return EE_Primary_Key_Field_Base
5003
-     * @throws EE_Error
5004
-     */
5005
-    public function get_primary_key_field()
5006
-    {
5007
-        if ($this->_primary_key_field === null) {
5008
-            foreach ($this->field_settings(true) as $field_obj) {
5009
-                if ($this->is_primary_key_field($field_obj)) {
5010
-                    $this->_primary_key_field = $field_obj;
5011
-                    break;
5012
-                }
5013
-            }
5014
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5015
-                throw new EE_Error(
5016
-                    sprintf(
5017
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5018
-                        get_class($this)
5019
-                    )
5020
-                );
5021
-            }
5022
-        }
5023
-        return $this->_primary_key_field;
5024
-    }
5025
-
5026
-
5027
-    /**
5028
-     * Returns whether or not not there is a primary key on this model.
5029
-     * Internally does some caching.
5030
-     *
5031
-     * @return boolean
5032
-     */
5033
-    public function has_primary_key_field()
5034
-    {
5035
-        if ($this->_has_primary_key_field === null) {
5036
-            try {
5037
-                $this->get_primary_key_field();
5038
-                $this->_has_primary_key_field = true;
5039
-            } catch (EE_Error $e) {
5040
-                $this->_has_primary_key_field = false;
5041
-            }
5042
-        }
5043
-        return $this->_has_primary_key_field;
5044
-    }
5045
-
5046
-
5047
-    /**
5048
-     * Finds the first field of type $field_class_name.
5049
-     *
5050
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5051
-     *                                 EE_Foreign_Key_Field, etc
5052
-     * @return EE_Model_Field_Base or null if none is found
5053
-     */
5054
-    public function get_a_field_of_type($field_class_name)
5055
-    {
5056
-        foreach ($this->field_settings() as $field) {
5057
-            if ($field instanceof $field_class_name) {
5058
-                return $field;
5059
-            }
5060
-        }
5061
-        return null;
5062
-    }
5063
-
5064
-
5065
-    /**
5066
-     * Gets a foreign key field pointing to model.
5067
-     *
5068
-     * @param string $model_name eg Event, Registration, not EEM_Event
5069
-     * @return EE_Foreign_Key_Field_Base
5070
-     * @throws EE_Error
5071
-     */
5072
-    public function get_foreign_key_to($model_name)
5073
-    {
5074
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5075
-            foreach ($this->field_settings() as $field) {
5076
-                if (
5077
-                    $field instanceof EE_Foreign_Key_Field_Base
5078
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5079
-                ) {
5080
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5081
-                    break;
5082
-                }
5083
-            }
5084
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5085
-                throw new EE_Error(
5086
-                    sprintf(
5087
-                        esc_html__(
5088
-                            "There is no foreign key field pointing to model %s on model %s",
5089
-                            'event_espresso'
5090
-                        ),
5091
-                        $model_name,
5092
-                        get_class($this)
5093
-                    )
5094
-                );
5095
-            }
5096
-        }
5097
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5098
-    }
5099
-
5100
-
5101
-    /**
5102
-     * Gets the table name (including $wpdb->prefix) for the table alias
5103
-     *
5104
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5105
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5106
-     *                            Either one works
5107
-     * @return string
5108
-     */
5109
-    public function get_table_for_alias($table_alias)
5110
-    {
5111
-        $table_alias_sans_model_relation_chain_prefix =
5112
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5113
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5114
-    }
5115
-
5116
-
5117
-    /**
5118
-     * Returns a flat array of all field son this model, instead of organizing them
5119
-     * by table_alias as they are in the constructor.
5120
-     *
5121
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5122
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5123
-     */
5124
-    public function field_settings($include_db_only_fields = false)
5125
-    {
5126
-        if ($include_db_only_fields) {
5127
-            if ($this->_cached_fields === null) {
5128
-                $this->_cached_fields = [];
5129
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5130
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5131
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5132
-                    }
5133
-                }
5134
-            }
5135
-            return $this->_cached_fields;
5136
-        }
5137
-        if ($this->_cached_fields_non_db_only === null) {
5138
-            $this->_cached_fields_non_db_only = [];
5139
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5140
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5141
-                    /** @var $field_obj EE_Model_Field_Base */
5142
-                    if (! $field_obj->is_db_only_field()) {
5143
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5144
-                    }
5145
-                }
5146
-            }
5147
-        }
5148
-        return $this->_cached_fields_non_db_only;
5149
-    }
5150
-
5151
-
5152
-    /**
5153
-     *        cycle though array of attendees and create objects out of each item
5154
-     *
5155
-     * @access        private
5156
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5157
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5158
-     *                           numerically indexed)
5159
-     * @throws EE_Error
5160
-     */
5161
-    protected function _create_objects($rows = [])
5162
-    {
5163
-        $array_of_objects = [];
5164
-        if (empty($rows)) {
5165
-            return [];
5166
-        }
5167
-        $count_if_model_has_no_primary_key = 0;
5168
-        $has_primary_key                   = $this->has_primary_key_field();
5169
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5170
-        foreach ((array) $rows as $row) {
5171
-            if (empty($row)) {
5172
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5173
-                return [];
5174
-            }
5175
-            // check if we've already set this object in the results array,
5176
-            // in which case there's no need to process it further (again)
5177
-            if ($has_primary_key) {
5178
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5179
-                    $row,
5180
-                    $primary_key_field->get_qualified_column(),
5181
-                    $primary_key_field->get_table_column()
5182
-                );
5183
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5184
-                    continue;
5185
-                }
5186
-            }
5187
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5188
-            if (! $classInstance) {
5189
-                throw new EE_Error(
5190
-                    sprintf(
5191
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5192
-                        $this->get_this_model_name(),
5193
-                        http_build_query($row)
5194
-                    )
5195
-                );
5196
-            }
5197
-            // set the timezone on the instantiated objects
5198
-            $classInstance->set_timezone($this->_timezone);
5199
-            // make sure if there is any timezone setting present that we set the timezone for the object
5200
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5201
-            $array_of_objects[ $key ] = $classInstance;
5202
-            // also, for all the relations of type BelongsTo, see if we can cache
5203
-            // those related models
5204
-            // (we could do this for other relations too, but if there are conditions
5205
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5206
-            // so it requires a little more thought than just caching them immediately...)
5207
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5208
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5209
-                    // check if this model's INFO is present. If so, cache it on the model
5210
-                    $other_model           = $relation_obj->get_other_model();
5211
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5212
-                    // if we managed to make a model object from the results, cache it on the main model object
5213
-                    if ($other_model_obj_maybe) {
5214
-                        // set timezone on these other model objects if they are present
5215
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5216
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5217
-                    }
5218
-                }
5219
-            }
5220
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5221
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5222
-            // the field in the CustomSelects object
5223
-            if ($this->_custom_selections instanceof CustomSelects) {
5224
-                $classInstance->setCustomSelectsValues(
5225
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5226
-                );
5227
-            }
5228
-        }
5229
-        return $array_of_objects;
5230
-    }
5231
-
5232
-
5233
-    /**
5234
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5235
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5236
-     *
5237
-     * @param array $db_results_row
5238
-     * @return array
5239
-     */
5240
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5241
-    {
5242
-        $results = [];
5243
-        if ($this->_custom_selections instanceof CustomSelects) {
5244
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5245
-                if (isset($db_results_row[ $alias ])) {
5246
-                    $results[ $alias ] = $this->convertValueToDataType(
5247
-                        $db_results_row[ $alias ],
5248
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5249
-                    );
5250
-                }
5251
-            }
5252
-        }
5253
-        return $results;
5254
-    }
5255
-
5256
-
5257
-    /**
5258
-     * This will set the value for the given alias
5259
-     *
5260
-     * @param string $value
5261
-     * @param string $datatype (one of %d, %s, %f)
5262
-     * @return int|string|float (int for %d, string for %s, float for %f)
5263
-     */
5264
-    protected function convertValueToDataType($value, $datatype)
5265
-    {
5266
-        switch ($datatype) {
5267
-            case '%f':
5268
-                return (float) $value;
5269
-            case '%d':
5270
-                return (int) $value;
5271
-            default:
5272
-                return (string) $value;
5273
-        }
5274
-    }
5275
-
5276
-
5277
-    /**
5278
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5279
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5280
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5281
-     * object (as set in the model_field!).
5282
-     *
5283
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5284
-     * @throws EE_Error
5285
-     * @throws ReflectionException
5286
-     */
5287
-    public function create_default_object()
5288
-    {
5289
-        $this_model_fields_and_values = [];
5290
-        // setup the row using default values;
5291
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5292
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5293
-        }
5294
-        $className     = $this->_get_class_name();
5295
-        return EE_Registry::instance()->load_class(
5296
-            $className,
5297
-            [$this_model_fields_and_values],
5298
-            false,
5299
-            false
5300
-        );
5301
-    }
5302
-
5303
-
5304
-    /**
5305
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5306
-     *                             or an stdClass where each property is the name of a column,
5307
-     * @return EE_Base_Class
5308
-     * @throws EE_Error
5309
-     */
5310
-    public function instantiate_class_from_array_or_object($cols_n_values)
5311
-    {
5312
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5313
-            $cols_n_values = get_object_vars($cols_n_values);
5314
-        }
5315
-        $primary_key = null;
5316
-        // make sure the array only has keys that are fields/columns on this model
5317
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5318
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5320
-        }
5321
-        $className = $this->_get_class_name();
5322
-        // check we actually found results that we can use to build our model object
5323
-        // if not, return null
5324
-        if ($this->has_primary_key_field()) {
5325
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5326
-                return null;
5327
-            }
5328
-        } elseif ($this->unique_indexes()) {
5329
-            $first_column = reset($this_model_fields_n_values);
5330
-            if (empty($first_column)) {
5331
-                return null;
5332
-            }
5333
-        }
5334
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5335
-        if ($primary_key) {
5336
-            $classInstance = $this->get_from_entity_map($primary_key);
5337
-            if (! $classInstance) {
5338
-                $classInstance = EE_Registry::instance()
5339
-                                            ->load_class(
5340
-                                                $className,
5341
-                                                [$this_model_fields_n_values, $this->_timezone],
5342
-                                                true,
5343
-                                                false
5344
-                                            );
5345
-                // add this new object to the entity map
5346
-                $classInstance = $this->add_to_entity_map($classInstance);
5347
-            }
5348
-        } else {
5349
-            $classInstance = EE_Registry::instance()
5350
-                                        ->load_class(
5351
-                                            $className,
5352
-                                            [$this_model_fields_n_values, $this->_timezone],
5353
-                                            true,
5354
-                                            false
5355
-                                        );
5356
-        }
5357
-        return $classInstance;
5358
-    }
5359
-
5360
-
5361
-    /**
5362
-     * Gets the model object from the  entity map if it exists
5363
-     *
5364
-     * @param int|string $id the ID of the model object
5365
-     * @return EE_Base_Class
5366
-     */
5367
-    public function get_from_entity_map($id)
5368
-    {
5369
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5370
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5371
-    }
5372
-
5373
-
5374
-    /**
5375
-     * add_to_entity_map
5376
-     * Adds the object to the model's entity mappings
5377
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5378
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5379
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5380
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5381
-     *        then this method should be called immediately after the update query
5382
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5383
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5384
-     *
5385
-     * @param EE_Base_Class $object
5386
-     * @return \EE_Base_Class
5387
-     * @throws EE_Error
5388
-     */
5389
-    public function add_to_entity_map(EE_Base_Class $object)
5390
-    {
5391
-        $className = $this->_get_class_name();
5392
-        if (! $object instanceof $className) {
5393
-            throw new EE_Error(
5394
-                sprintf(
5395
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5396
-                    is_object($object) ? get_class($object) : $object,
5397
-                    $className
5398
-                )
5399
-            );
5400
-        }
5401
-        /** @var $object EE_Base_Class */
5402
-        if (! $object->ID()) {
5403
-            throw new EE_Error(
5404
-                sprintf(
5405
-                    esc_html__(
5406
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5407
-                        "event_espresso"
5408
-                    ),
5409
-                    get_class($this)
5410
-                )
5411
-            );
5412
-        }
5413
-        // double check it's not already there
5414
-        $classInstance = $this->get_from_entity_map($object->ID());
5415
-        if ($classInstance) {
5416
-            return $classInstance;
5417
-        }
5418
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5419
-        return $object;
5420
-    }
5421
-
5422
-
5423
-    /**
5424
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5425
-     * if no identifier is provided, then the entire entity map is emptied
5426
-     *
5427
-     * @param int|string $id the ID of the model object
5428
-     * @return boolean
5429
-     */
5430
-    public function clear_entity_map($id = null)
5431
-    {
5432
-        if (empty($id)) {
5433
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5434
-            return true;
5435
-        }
5436
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5437
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5438
-            return true;
5439
-        }
5440
-        return false;
5441
-    }
5442
-
5443
-
5444
-    /**
5445
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5446
-     * Given an array where keys are column (or column alias) names and values,
5447
-     * returns an array of their corresponding field names and database values
5448
-     *
5449
-     * @param array $cols_n_values
5450
-     * @return array
5451
-     * @throws EE_Error
5452
-     * @throws ReflectionException
5453
-     */
5454
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5455
-    {
5456
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5457
-    }
5458
-
5459
-
5460
-    /**
5461
-     * _deduce_fields_n_values_from_cols_n_values
5462
-     * Given an array where keys are column (or column alias) names and values,
5463
-     * returns an array of their corresponding field names and database values
5464
-     *
5465
-     * @param array $cols_n_values
5466
-     * @return array
5467
-     * @throws EE_Error
5468
-     * @throws ReflectionException
5469
-     */
5470
-    protected function _deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5471
-    {
5472
-        $this_model_fields_n_values = [];
5473
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
-                $cols_n_values,
5476
-                $table_obj->get_fully_qualified_pk_column(),
5477
-                $table_obj->get_pk_column()
5478
-            );
5479
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5480
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5483
-                        // prepare field as if its coming from db
5484
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5485
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5486
-                    }
5487
-                }
5488
-            } else {
5489
-                // the table's rows existed. Use their values
5490
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5491
-                    if (! $field_obj->is_db_only_field()) {
5492
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5493
-                            $cols_n_values,
5494
-                            $field_obj->get_qualified_column(),
5495
-                            $field_obj->get_table_column()
5496
-                        );
5497
-                    }
5498
-                }
5499
-            }
5500
-        }
5501
-        return $this_model_fields_n_values;
5502
-    }
5503
-
5504
-
5505
-    /**
5506
-     * @param array $cols_n_values
5507
-     * @param $qualified_column
5508
-     * @param $regular_column
5509
-     * @return null
5510
-     * @throws EE_Error
5511
-     * @throws ReflectionException
5512
-     */
5513
-    protected function _get_column_value_with_table_alias_or_not(array $cols_n_values, $qualified_column, $regular_column)
5514
-    {
5515
-        $value = null;
5516
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517
-        // does the field on the model relate to this column retrieved from the db?
5518
-        // or is it a db-only field? (not relating to the model)
5519
-        if (isset($cols_n_values[ $qualified_column ])) {
5520
-            $value = $cols_n_values[ $qualified_column ];
5521
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5522
-            $value = $cols_n_values[ $regular_column ];
5523
-        } elseif (! empty($this->foreign_key_aliases)) {
5524
-            // no PK?  ok check if there is a foreign key alias set for this table
5525
-            // then check if that alias exists in the incoming data
5526
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
-                    $value = $cols_n_values[ $FK_alias ];
5530
-                    [$pk_class] = explode('.', $PK_column);
5531
-                    $pk_model_name = "EEM_{$pk_class}";
5532
-                    /** @var EEM_Base $pk_model */
5533
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5534
-                    if ($pk_model instanceof EEM_Base) {
5535
-                        // make sure object is pulled from db and added to entity map
5536
-                        $pk_model->get_one_by_ID($value);
5537
-                    }
5538
-                    break;
5539
-                }
5540
-            }
5541
-        }
5542
-        return $value;
5543
-    }
5544
-
5545
-
5546
-    /**
5547
-     * refresh_entity_map_from_db
5548
-     * Makes sure the model object in the entity map at $id assumes the values
5549
-     * of the database (opposite of EE_base_Class::save())
5550
-     *
5551
-     * @param int|string $id
5552
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5553
-     * @throws EE_Error
5554
-     * @throws ReflectionException
5555
-     */
5556
-    public function refresh_entity_map_from_db($id)
5557
-    {
5558
-        $obj_in_map = $this->get_from_entity_map($id);
5559
-        if ($obj_in_map) {
5560
-            $wpdb_results = $this->_get_all_wpdb_results(
5561
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5562
-            );
5563
-            if ($wpdb_results && is_array($wpdb_results)) {
5564
-                $one_row = reset($wpdb_results);
5565
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5566
-                    $obj_in_map->set_from_db($field_name, $db_value);
5567
-                }
5568
-                // clear the cache of related model objects
5569
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5570
-                    $obj_in_map->clear_cache($relation_name, null, true);
5571
-                }
5572
-            }
5573
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5574
-            return $obj_in_map;
5575
-        }
5576
-        return $this->get_one_by_ID($id);
5577
-    }
5578
-
5579
-
5580
-    /**
5581
-     * refresh_entity_map_with
5582
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5583
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5584
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5585
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5586
-     *
5587
-     * @param int|string    $id
5588
-     * @param EE_Base_Class $replacing_model_obj
5589
-     * @return \EE_Base_Class
5590
-     * @throws EE_Error
5591
-     */
5592
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5593
-    {
5594
-        $obj_in_map = $this->get_from_entity_map($id);
5595
-        if ($obj_in_map) {
5596
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5597
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5598
-                    $obj_in_map->set($field_name, $value);
5599
-                }
5600
-                // make the model object in the entity map's cache match the $replacing_model_obj
5601
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
-                    $obj_in_map->clear_cache($relation_name, null, true);
5603
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5604
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5605
-                    }
5606
-                }
5607
-            }
5608
-            return $obj_in_map;
5609
-        }
5610
-        $this->add_to_entity_map($replacing_model_obj);
5611
-        return $replacing_model_obj;
5612
-    }
5613
-
5614
-
5615
-    /**
5616
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5617
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5618
-     * require_once($this->_getClassName().".class.php");
5619
-     *
5620
-     * @return string
5621
-     */
5622
-    private function _get_class_name()
5623
-    {
5624
-        return "EE_" . $this->get_this_model_name();
5625
-    }
5626
-
5627
-
5628
-    /**
5629
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5630
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5631
-     * it would be 'Events'.
5632
-     *
5633
-     * @param int|float|null $quantity
5634
-     * @return string
5635
-     */
5636
-    public function item_name($quantity = 1): string
5637
-    {
5638
-        $quantity = floor($quantity);
5639
-        return apply_filters(
5640
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5641
-            $quantity > 1 ? $this->plural_item : $this->singular_item,
5642
-            $quantity,
5643
-            $this->plural_item,
5644
-            $this->singular_item
5645
-        );
5646
-    }
5647
-
5648
-
5649
-    /**
5650
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5651
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5652
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5653
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5654
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5655
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5656
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5657
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5658
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5659
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5660
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5661
-     *        return $previousReturnValue.$returnString;
5662
-     * }
5663
-     * require('EEM_Answer.model.php');
5664
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5665
-     * // will output "you called my_callback! and passed args:monkeys,100"
5666
-     *
5667
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5668
-     * @param array  $args       array of original arguments passed to the function
5669
-     * @return mixed whatever the plugin which calls add_filter decides
5670
-     * @throws EE_Error
5671
-     */
5672
-    public function __call($methodName, $args)
5673
-    {
5674
-        $className = get_class($this);
5675
-        $tagName   = "FHEE__{$className}__{$methodName}";
5676
-        if (! has_filter($tagName)) {
5677
-            throw new EE_Error(
5678
-                sprintf(
5679
-                    esc_html__(
5680
-                        '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 );',
5681
-                        'event_espresso'
5682
-                    ),
5683
-                    $methodName,
5684
-                    $className,
5685
-                    $tagName,
5686
-                    '<br />'
5687
-                )
5688
-            );
5689
-        }
5690
-        return apply_filters($tagName, null, $this, $args);
5691
-    }
5692
-
5693
-
5694
-    /**
5695
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5696
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5697
-     *
5698
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5699
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5700
-     *                                                       the object's class name
5701
-     *                                                       or object's ID
5702
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5703
-     *                                                       exists in the database. If it does not, we add it
5704
-     * @return EE_Base_Class
5705
-     * @throws EE_Error
5706
-     */
5707
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5708
-    {
5709
-        $className = $this->_get_class_name();
5710
-        if ($base_class_obj_or_id instanceof $className) {
5711
-            $model_object = $base_class_obj_or_id;
5712
-        } else {
5713
-            $primary_key_field = $this->get_primary_key_field();
5714
-            if (
5715
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5716
-                && (
5717
-                    is_int($base_class_obj_or_id)
5718
-                    || is_string($base_class_obj_or_id)
5719
-                )
5720
-            ) {
5721
-                // assume it's an ID.
5722
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5723
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5724
-            } elseif (
5725
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5726
-                && is_string($base_class_obj_or_id)
5727
-            ) {
5728
-                // assume its a string representation of the object
5729
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5730
-            } else {
5731
-                throw new EE_Error(
5732
-                    sprintf(
5733
-                        esc_html__(
5734
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5735
-                            'event_espresso'
5736
-                        ),
5737
-                        $base_class_obj_or_id,
5738
-                        $this->_get_class_name(),
5739
-                        print_r($base_class_obj_or_id, true)
5740
-                    )
5741
-                );
5742
-            }
5743
-        }
5744
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5745
-            $model_object->save();
5746
-        }
5747
-        return $model_object;
5748
-    }
5749
-
5750
-
5751
-    /**
5752
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5753
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5754
-     * returns it ID.
5755
-     *
5756
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5757
-     * @return int|string depending on the type of this model object's ID
5758
-     * @throws EE_Error
5759
-     */
5760
-    public function ensure_is_ID($base_class_obj_or_id)
5761
-    {
5762
-        $className = $this->_get_class_name();
5763
-        if ($base_class_obj_or_id instanceof $className) {
5764
-            /** @var $base_class_obj_or_id EE_Base_Class */
5765
-            $id = $base_class_obj_or_id->ID();
5766
-        } elseif (is_int($base_class_obj_or_id)) {
5767
-            // assume it's an ID
5768
-            $id = $base_class_obj_or_id;
5769
-        } elseif (is_string($base_class_obj_or_id)) {
5770
-            // assume its a string representation of the object
5771
-            $id = $base_class_obj_or_id;
5772
-        } else {
5773
-            throw new EE_Error(
5774
-                sprintf(
5775
-                    esc_html__(
5776
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5777
-                        'event_espresso'
5778
-                    ),
5779
-                    $base_class_obj_or_id,
5780
-                    $this->_get_class_name(),
5781
-                    print_r($base_class_obj_or_id, true)
5782
-                )
5783
-            );
5784
-        }
5785
-        return $id;
5786
-    }
5787
-
5788
-
5789
-    /**
5790
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5791
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5792
-     * been sanitized and converted into the appropriate domain.
5793
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5794
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5795
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5796
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5797
-     * $EVT = EEM_Event::instance(); $old_setting =
5798
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5799
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5800
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5801
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5802
-     *
5803
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5804
-     * @return void
5805
-     */
5806
-    public function assume_values_already_prepared_by_model_object(
5807
-        $values_already_prepared = self::not_prepared_by_model_object
5808
-    ) {
5809
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5810
-    }
5811
-
5812
-
5813
-    /**
5814
-     * Read comments for assume_values_already_prepared_by_model_object()
5815
-     *
5816
-     * @return int
5817
-     */
5818
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5819
-    {
5820
-        return $this->_values_already_prepared_by_model_object;
5821
-    }
5822
-
5823
-
5824
-    /**
5825
-     * Gets all the indexes on this model
5826
-     *
5827
-     * @return EE_Index[]
5828
-     */
5829
-    public function indexes()
5830
-    {
5831
-        return $this->_indexes;
5832
-    }
5833
-
5834
-
5835
-    /**
5836
-     * Gets all the Unique Indexes on this model
5837
-     *
5838
-     * @return EE_Unique_Index[]
5839
-     */
5840
-    public function unique_indexes()
5841
-    {
5842
-        $unique_indexes = [];
5843
-        foreach ($this->_indexes as $name => $index) {
5844
-            if ($index instanceof EE_Unique_Index) {
5845
-                $unique_indexes [ $name ] = $index;
5846
-            }
5847
-        }
5848
-        return $unique_indexes;
5849
-    }
5850
-
5851
-
5852
-    /**
5853
-     * Gets all the fields which, when combined, make the primary key.
5854
-     * This is usually just an array with 1 element (the primary key), but in cases
5855
-     * where there is no primary key, it's a combination of fields as defined
5856
-     * on a primary index
5857
-     *
5858
-     * @return EE_Model_Field_Base[] indexed by the field's name
5859
-     * @throws EE_Error
5860
-     */
5861
-    public function get_combined_primary_key_fields()
5862
-    {
5863
-        foreach ($this->indexes() as $index) {
5864
-            if ($index instanceof EE_Primary_Key_Index) {
5865
-                return $index->fields();
5866
-            }
5867
-        }
5868
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5869
-    }
5870
-
5871
-
5872
-    /**
5873
-     * Used to build a primary key string (when the model has no primary key),
5874
-     * which can be used a unique string to identify this model object.
5875
-     *
5876
-     * @param array $fields_n_values keys are field names, values are their values.
5877
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5878
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5879
-     *                               before passing it to this function (that will convert it from columns-n-values
5880
-     *                               to field-names-n-values).
5881
-     * @return string
5882
-     * @throws EE_Error
5883
-     */
5884
-    public function get_index_primary_key_string($fields_n_values)
5885
-    {
5886
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5887
-            $fields_n_values,
5888
-            $this->get_combined_primary_key_fields()
5889
-        );
5890
-        return http_build_query($cols_n_values_for_primary_key_index);
5891
-    }
5892
-
5893
-
5894
-    /**
5895
-     * Gets the field values from the primary key string
5896
-     *
5897
-     * @param string $index_primary_key_string
5898
-     * @return null|array
5899
-     * @throws EE_Error
5900
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5901
-     */
5902
-    public function parse_index_primary_key_string($index_primary_key_string)
5903
-    {
5904
-        $key_fields = $this->get_combined_primary_key_fields();
5905
-        // check all of them are in the $id
5906
-        $key_vals_in_combined_pk = [];
5907
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5908
-        foreach ($key_fields as $key_field_name => $field_obj) {
5909
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5910
-                return null;
5911
-            }
5912
-        }
5913
-        return $key_vals_in_combined_pk;
5914
-    }
5915
-
5916
-
5917
-    /**
5918
-     * verifies that an array of key-value pairs for model fields has a key
5919
-     * for each field comprising the primary key index
5920
-     *
5921
-     * @param array $key_vals
5922
-     * @return boolean
5923
-     * @throws EE_Error
5924
-     */
5925
-    public function has_all_combined_primary_key_fields($key_vals)
5926
-    {
5927
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5928
-        foreach ($keys_it_should_have as $key) {
5929
-            if (! isset($key_vals[ $key ])) {
5930
-                return false;
5931
-            }
5932
-        }
5933
-        return true;
5934
-    }
5935
-
5936
-
5937
-    /**
5938
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5939
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5940
-     *
5941
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5942
-     * @param array               $query_params                     @see
5943
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5944
-     * @throws EE_Error
5945
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5946
-     *                                                              indexed)
5947
-     */
5948
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5949
-    {
5950
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5951
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5952
-        } elseif (is_array($model_object_or_attributes_array)) {
5953
-            $attributes_array = $model_object_or_attributes_array;
5954
-        } else {
5955
-            throw new EE_Error(
5956
-                sprintf(
5957
-                    esc_html__(
5958
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5959
-                        "event_espresso"
5960
-                    ),
5961
-                    $model_object_or_attributes_array
5962
-                )
5963
-            );
5964
-        }
5965
-        // even copies obviously won't have the same ID, so remove the primary key
5966
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5967
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5968
-            unset($attributes_array[ $this->primary_key_name() ]);
5969
-        }
5970
-        if (isset($query_params[0])) {
5971
-            $query_params[0] = array_merge($attributes_array, $query_params);
5972
-        } else {
5973
-            $query_params[0] = $attributes_array;
5974
-        }
5975
-        return $this->get_all($query_params);
5976
-    }
5977
-
5978
-
5979
-    /**
5980
-     * Gets the first copy we find. See get_all_copies for more details
5981
-     *
5982
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5983
-     * @param array $query_params
5984
-     * @return EE_Base_Class
5985
-     * @throws EE_Error
5986
-     */
5987
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5988
-    {
5989
-        if (! is_array($query_params)) {
5990
-            EE_Error::doing_it_wrong(
5991
-                'EEM_Base::get_one_copy',
5992
-                sprintf(
5993
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5994
-                    gettype($query_params)
5995
-                ),
5996
-                '4.6.0'
5997
-            );
5998
-            $query_params = [];
5999
-        }
6000
-        $query_params['limit'] = 1;
6001
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6002
-        if (is_array($copies)) {
6003
-            return array_shift($copies);
6004
-        }
6005
-        return null;
6006
-    }
6007
-
6008
-
6009
-    /**
6010
-     * Updates the item with the specified id. Ignores default query parameters because
6011
-     * we have specified the ID, and its assumed we KNOW what we're doing
6012
-     *
6013
-     * @param array      $fields_n_values keys are field names, values are their new values
6014
-     * @param int|string $id              the value of the primary key to update
6015
-     * @return int number of rows updated
6016
-     * @throws EE_Error
6017
-     */
6018
-    public function update_by_ID($fields_n_values, $id)
6019
-    {
6020
-        $query_params = [
6021
-            [
6022
-                $this->get_primary_key_field()->get_name() => $id
6023
-            ],
6024
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6025
-        ];
6026
-        return $this->update($fields_n_values, $query_params);
6027
-    }
6028
-
6029
-
6030
-    /**
6031
-     * Changes an operator which was supplied to the models into one usable in SQL
6032
-     *
6033
-     * @param string $operator_supplied
6034
-     * @return string an operator which can be used in SQL
6035
-     * @throws EE_Error
6036
-     */
6037
-    private function _prepare_operator_for_sql($operator_supplied)
6038
-    {
6039
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6040
-        if ($sql_operator) {
6041
-            return $sql_operator;
6042
-        }
6043
-        throw new EE_Error(
6044
-            sprintf(
6045
-                esc_html__(
6046
-                    "The operator '%s' is not in the list of valid operators: %s",
6047
-                    "event_espresso"
6048
-                ),
6049
-                $operator_supplied,
6050
-                implode(",", array_keys($this->_valid_operators))
6051
-            )
6052
-        );
6053
-    }
6054
-
6055
-
6056
-    /**
6057
-     * Gets the valid operators
6058
-     *
6059
-     * @return array keys are accepted strings, values are the SQL they are converted to
6060
-     */
6061
-    public function valid_operators()
6062
-    {
6063
-        return $this->_valid_operators;
6064
-    }
6065
-
6066
-
6067
-    /**
6068
-     * Gets the between-style operators (take 2 arguments).
6069
-     *
6070
-     * @return array keys are accepted strings, values are the SQL they are converted to
6071
-     */
6072
-    public function valid_between_style_operators()
6073
-    {
6074
-        return array_intersect(
6075
-            $this->valid_operators(),
6076
-            $this->_between_style_operators
6077
-        );
6078
-    }
6079
-
6080
-
6081
-    /**
6082
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6083
-     *
6084
-     * @return array keys are accepted strings, values are the SQL they are converted to
6085
-     */
6086
-    public function valid_like_style_operators()
6087
-    {
6088
-        return array_intersect(
6089
-            $this->valid_operators(),
6090
-            $this->_like_style_operators
6091
-        );
6092
-    }
6093
-
6094
-
6095
-    /**
6096
-     * Gets the "in"-style operators
6097
-     *
6098
-     * @return array keys are accepted strings, values are the SQL they are converted to
6099
-     */
6100
-    public function valid_in_style_operators()
6101
-    {
6102
-        return array_intersect(
6103
-            $this->valid_operators(),
6104
-            $this->_in_style_operators
6105
-        );
6106
-    }
6107
-
6108
-
6109
-    /**
6110
-     * Gets the "null"-style operators (accept no arguments)
6111
-     *
6112
-     * @return array keys are accepted strings, values are the SQL they are converted to
6113
-     */
6114
-    public function valid_null_style_operators()
6115
-    {
6116
-        return array_intersect(
6117
-            $this->valid_operators(),
6118
-            $this->_null_style_operators
6119
-        );
6120
-    }
6121
-
6122
-
6123
-    /**
6124
-     * Gets an array where keys are the primary keys and values are their 'names'
6125
-     * (as determined by the model object's name() function, which is often overridden)
6126
-     *
6127
-     * @param array $query_params like get_all's
6128
-     * @return string[]
6129
-     * @throws EE_Error
6130
-     */
6131
-    public function get_all_names($query_params = [])
6132
-    {
6133
-        $objs  = $this->get_all($query_params);
6134
-        $names = [];
6135
-        foreach ($objs as $obj) {
6136
-            $names[ $obj->ID() ] = $obj->name();
6137
-        }
6138
-        return $names;
6139
-    }
6140
-
6141
-
6142
-    /**
6143
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6144
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6145
-     * this is duplicated effort and reduces efficiency) you would be better to use
6146
-     * array_keys() on $model_objects.
6147
-     *
6148
-     * @param \EE_Base_Class[] $model_objects
6149
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6150
-     *                                               in the returned array
6151
-     * @return array
6152
-     * @throws EE_Error
6153
-     */
6154
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6155
-    {
6156
-        if (! $this->has_primary_key_field()) {
6157
-            if (WP_DEBUG) {
6158
-                EE_Error::add_error(
6159
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6160
-                    __FILE__,
6161
-                    __FUNCTION__,
6162
-                    __LINE__
6163
-                );
6164
-            }
6165
-        }
6166
-        $IDs = [];
6167
-        foreach ($model_objects as $model_object) {
6168
-            $id = $model_object->ID();
6169
-            if (! $id) {
6170
-                if ($filter_out_empty_ids) {
6171
-                    continue;
6172
-                }
6173
-                if (WP_DEBUG) {
6174
-                    EE_Error::add_error(
6175
-                        esc_html__(
6176
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6177
-                            'event_espresso'
6178
-                        ),
6179
-                        __FILE__,
6180
-                        __FUNCTION__,
6181
-                        __LINE__
6182
-                    );
6183
-                }
6184
-            }
6185
-            $IDs[] = $id;
6186
-        }
6187
-        return $IDs;
6188
-    }
6189
-
6190
-
6191
-    /**
6192
-     * Returns the string used in capabilities relating to this model. If there
6193
-     * are no capabilities that relate to this model returns false
6194
-     *
6195
-     * @return string|false
6196
-     */
6197
-    public function cap_slug()
6198
-    {
6199
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6200
-    }
6201
-
6202
-
6203
-    /**
6204
-     * Returns the capability-restrictions array (@param string $context
6205
-     *
6206
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6207
-     * @throws EE_Error
6208
-     * @see EEM_Base::_cap_restrictions).
6209
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6210
-     *      only returns the cap restrictions array in that context (ie, the array
6211
-     *      at that key)
6212
-     *
6213
-     */
6214
-    public function cap_restrictions($context = EEM_Base::caps_read)
6215
-    {
6216
-        EEM_Base::verify_is_valid_cap_context($context);
6217
-        // check if we ought to run the restriction generator first
6218
-        if (
6219
-            isset($this->_cap_restriction_generators[ $context ])
6220
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6221
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6222
-        ) {
6223
-            $this->_cap_restrictions[ $context ] = array_merge(
6224
-                $this->_cap_restrictions[ $context ],
6225
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6226
-            );
6227
-        }
6228
-        // and make sure we've finalized the construction of each restriction
6229
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6230
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6231
-                $where_conditions_obj->_finalize_construct($this);
6232
-            }
6233
-        }
6234
-        return $this->_cap_restrictions[ $context ];
6235
-    }
6236
-
6237
-
6238
-    /**
6239
-     * Indicating whether or not this model thinks its a wp core model
6240
-     *
6241
-     * @return boolean
6242
-     */
6243
-    public function is_wp_core_model()
6244
-    {
6245
-        return $this->_wp_core_model;
6246
-    }
6247
-
6248
-
6249
-    /**
6250
-     * Gets all the caps that are missing which impose a restriction on
6251
-     * queries made in this context
6252
-     *
6253
-     * @param string $context one of EEM_Base::caps_ constants
6254
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6255
-     * @throws EE_Error
6256
-     */
6257
-    public function caps_missing($context = EEM_Base::caps_read)
6258
-    {
6259
-        $missing_caps     = [];
6260
-        $cap_restrictions = $this->cap_restrictions($context);
6261
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6262
-            if (
6263
-                ! EE_Capabilities::instance()
6264
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6265
-            ) {
6266
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6267
-            }
6268
-        }
6269
-        return $missing_caps;
6270
-    }
6271
-
6272
-
6273
-    /**
6274
-     * Gets the mapping from capability contexts to action strings used in capability names
6275
-     *
6276
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6277
-     * one of 'read', 'edit', or 'delete'
6278
-     */
6279
-    public function cap_contexts_to_cap_action_map()
6280
-    {
6281
-        return apply_filters(
6282
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6283
-            $this->_cap_contexts_to_cap_action_map,
6284
-            $this
6285
-        );
6286
-    }
6287
-
6288
-
6289
-    /**
6290
-     * Gets the action string for the specified capability context
6291
-     *
6292
-     * @param string $context
6293
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6294
-     * @throws EE_Error
6295
-     */
6296
-    public function cap_action_for_context($context)
6297
-    {
6298
-        $mapping = $this->cap_contexts_to_cap_action_map();
6299
-        if (isset($mapping[ $context ])) {
6300
-            return $mapping[ $context ];
6301
-        }
6302
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6303
-            return $action;
6304
-        }
6305
-        throw new EE_Error(
6306
-            sprintf(
6307
-                esc_html__(
6308
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6309
-                    'event_espresso'
6310
-                ),
6311
-                $context,
6312
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6313
-            )
6314
-        );
6315
-    }
6316
-
6317
-
6318
-    /**
6319
-     * Returns all the capability contexts which are valid when querying models
6320
-     *
6321
-     * @return array
6322
-     */
6323
-    public static function valid_cap_contexts()
6324
-    {
6325
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6326
-            self::caps_read,
6327
-            self::caps_read_admin,
6328
-            self::caps_edit,
6329
-            self::caps_delete,
6330
-        ]);
6331
-    }
6332
-
6333
-
6334
-    /**
6335
-     * Returns all valid options for 'default_where_conditions'
6336
-     *
6337
-     * @return array
6338
-     */
6339
-    public static function valid_default_where_conditions()
6340
-    {
6341
-        return [
6342
-            EEM_Base::default_where_conditions_all,
6343
-            EEM_Base::default_where_conditions_this_only,
6344
-            EEM_Base::default_where_conditions_others_only,
6345
-            EEM_Base::default_where_conditions_minimum_all,
6346
-            EEM_Base::default_where_conditions_minimum_others,
6347
-            EEM_Base::default_where_conditions_none,
6348
-        ];
6349
-    }
6350
-
6351
-    // public static function default_where_conditions_full
6352
-
6353
-
6354
-    /**
6355
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6356
-     *
6357
-     * @param string $context
6358
-     * @return bool
6359
-     * @throws EE_Error
6360
-     */
6361
-    public static function verify_is_valid_cap_context($context)
6362
-    {
6363
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6364
-        if (in_array($context, $valid_cap_contexts)) {
6365
-            return true;
6366
-        }
6367
-        throw new EE_Error(
6368
-            sprintf(
6369
-                esc_html__(
6370
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6371
-                    'event_espresso'
6372
-                ),
6373
-                $context,
6374
-                'EEM_Base',
6375
-                implode(',', $valid_cap_contexts)
6376
-            )
6377
-        );
6378
-    }
6379
-
6380
-
6381
-    /**
6382
-     * Clears all the models field caches. This is only useful when a sub-class
6383
-     * might have added a field or something and these caches might be invalidated
6384
-     */
6385
-    protected function _invalidate_field_caches()
6386
-    {
6387
-        $this->_cache_foreign_key_to_fields = [];
6388
-        $this->_cached_fields               = null;
6389
-        $this->_cached_fields_non_db_only   = null;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6395
-     * (eg "and", "or", "not").
6396
-     *
6397
-     * @return array
6398
-     */
6399
-    public function logic_query_param_keys()
6400
-    {
6401
-        return $this->_logic_query_param_keys;
6402
-    }
6403
-
6404
-
6405
-    /**
6406
-     * Determines whether or not the where query param array key is for a logic query param.
6407
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6408
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6409
-     *
6410
-     * @param $query_param_key
6411
-     * @return bool
6412
-     */
6413
-    public function is_logic_query_param_key($query_param_key)
6414
-    {
6415
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6416
-            if (
6417
-                $query_param_key === $logic_query_param_key
6418
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6419
-            ) {
6420
-                return true;
6421
-            }
6422
-        }
6423
-        return false;
6424
-    }
6425
-
6426
-
6427
-    /**
6428
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6429
-     *
6430
-     * @return boolean
6431
-     * @since 4.9.74.p
6432
-     */
6433
-    public function hasPassword()
6434
-    {
6435
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6436
-        if ($this->has_password_field === null) {
6437
-            $password_field           = $this->getPasswordField();
6438
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6439
-        }
6440
-        return $this->has_password_field;
6441
-    }
6442
-
6443
-
6444
-    /**
6445
-     * Returns the password field on this model, if there is one
6446
-     *
6447
-     * @return EE_Password_Field|null
6448
-     * @since 4.9.74.p
6449
-     */
6450
-    public function getPasswordField()
6451
-    {
6452
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6453
-        // there's no need to search for it. If we don't know yet, then find out
6454
-        if ($this->has_password_field === null && $this->password_field === null) {
6455
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6456
-        }
6457
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6458
-        return $this->password_field;
6459
-    }
6460
-
6461
-
6462
-    /**
6463
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6464
-     *
6465
-     * @return EE_Model_Field_Base[]
6466
-     * @throws EE_Error
6467
-     * @since 4.9.74.p
6468
-     */
6469
-    public function getPasswordProtectedFields()
6470
-    {
6471
-        $password_field = $this->getPasswordField();
6472
-        $fields         = [];
6473
-        if ($password_field instanceof EE_Password_Field) {
6474
-            $field_names = $password_field->protectedFields();
6475
-            foreach ($field_names as $field_name) {
6476
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6477
-            }
6478
-        }
6479
-        return $fields;
6480
-    }
6481
-
6482
-
6483
-    /**
6484
-     * Checks if the current user can perform the requested action on this model
6485
-     *
6486
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6487
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6488
-     * @return bool
6489
-     * @throws EE_Error
6490
-     * @throws InvalidArgumentException
6491
-     * @throws InvalidDataTypeException
6492
-     * @throws InvalidInterfaceException
6493
-     * @throws ReflectionException
6494
-     * @throws UnexpectedEntityException
6495
-     * @since 4.9.74.p
6496
-     */
6497
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6498
-    {
6499
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6500
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6501
-        }
6502
-        if (! is_array($model_obj_or_fields_n_values)) {
6503
-            throw new UnexpectedEntityException(
6504
-                $model_obj_or_fields_n_values,
6505
-                'EE_Base_Class',
6506
-                sprintf(
6507
-                    esc_html__(
6508
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6509
-                        'event_espresso'
6510
-                    ),
6511
-                    __FUNCTION__
6512
-                )
6513
-            );
6514
-        }
6515
-        return $this->exists(
6516
-            $this->alter_query_params_to_restrict_by_ID(
6517
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6518
-                [
6519
-                    'default_where_conditions' => 'none',
6520
-                    'caps'                     => $cap_to_check,
6521
-                ]
6522
-            )
6523
-        );
6524
-    }
6525
-
6526
-
6527
-    /**
6528
-     * Returns the query param where conditions key to the password affecting this model.
6529
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6530
-     *
6531
-     * @return null|string
6532
-     * @throws EE_Error
6533
-     * @throws InvalidArgumentException
6534
-     * @throws InvalidDataTypeException
6535
-     * @throws InvalidInterfaceException
6536
-     * @throws ModelConfigurationException
6537
-     * @throws ReflectionException
6538
-     * @since 4.9.74.p
6539
-     */
6540
-    public function modelChainAndPassword()
6541
-    {
6542
-        if ($this->model_chain_to_password === null) {
6543
-            throw new ModelConfigurationException(
6544
-                $this,
6545
-                esc_html_x(
6546
-                // @codingStandardsIgnoreStart
6547
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6548
-                    // @codingStandardsIgnoreEnd
6549
-                    '1: model name',
6550
-                    'event_espresso'
6551
-                )
6552
-            );
6553
-        }
6554
-        if ($this->model_chain_to_password === '') {
6555
-            $model_with_password = $this;
6556
-        } else {
6557
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6558
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6559
-            } else {
6560
-                $last_model_in_chain = $this->model_chain_to_password;
6561
-            }
6562
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6563
-        }
6564
-
6565
-        $password_field = $model_with_password->getPasswordField();
6566
-        if ($password_field instanceof EE_Password_Field) {
6567
-            $password_field_name = $password_field->get_name();
6568
-        } else {
6569
-            throw new ModelConfigurationException(
6570
-                $this,
6571
-                sprintf(
6572
-                    esc_html_x(
6573
-                        '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"',
6574
-                        '1: model name, 2: special string',
6575
-                        'event_espresso'
6576
-                    ),
6577
-                    $model_with_password->get_this_model_name(),
6578
-                    $this->model_chain_to_password
6579
-                )
6580
-            );
6581
-        }
6582
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6583
-    }
6584
-
6585
-
6586
-    /**
6587
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6588
-     * or if this model itself has a password affecting access to some of its other fields.
6589
-     *
6590
-     * @return boolean
6591
-     * @since 4.9.74.p
6592
-     */
6593
-    public function restrictedByRelatedModelPassword()
6594
-    {
6595
-        return $this->model_chain_to_password !== null;
6596
-    }
3869
+		}
3870
+		return $null_friendly_where_conditions;
3871
+	}
3872
+
3873
+
3874
+	/**
3875
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3876
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3877
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3878
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3879
+	 *
3880
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3881
+	 * @return array @see
3882
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3883
+	 */
3884
+	private function _get_default_where_conditions($model_relation_path = '')
3885
+	{
3886
+		if ($this->_ignore_where_strategy) {
3887
+			return [];
3888
+		}
3889
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3890
+	}
3891
+
3892
+
3893
+	/**
3894
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3895
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3896
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3897
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3898
+	 * Similar to _get_default_where_conditions
3899
+	 *
3900
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3901
+	 * @return array @see
3902
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
+	 */
3904
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3905
+	{
3906
+		if ($this->_ignore_where_strategy) {
3907
+			return [];
3908
+		}
3909
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
+	}
3911
+
3912
+
3913
+	/**
3914
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
+	 *
3917
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3918
+	 * @return string
3919
+	 * @throws EE_Error
3920
+	 */
3921
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
+	{
3923
+		$selects = $this->_get_columns_to_select_for_this_model();
3924
+		foreach (
3925
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
+		) {
3927
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
+			foreach ($other_model_selects as $key => $value) {
3930
+				$selects[] = $value;
3931
+			}
3932
+		}
3933
+		return implode(", ", $selects);
3934
+	}
3935
+
3936
+
3937
+	/**
3938
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
+	 * So that's going to be the columns for all the fields on the model
3940
+	 *
3941
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
+	 */
3944
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
+	{
3946
+		$fields                                       = $this->field_settings();
3947
+		$selects                                      = [];
3948
+		$table_alias_with_model_relation_chain_prefix =
3949
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
+				$model_relation_chain,
3951
+				$this->get_this_model_name()
3952
+			);
3953
+		foreach ($fields as $field_obj) {
3954
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3955
+						 . $field_obj->get_table_alias()
3956
+						 . "."
3957
+						 . $field_obj->get_table_column()
3958
+						 . " AS '"
3959
+						 . $table_alias_with_model_relation_chain_prefix
3960
+						 . $field_obj->get_table_alias()
3961
+						 . "."
3962
+						 . $field_obj->get_table_column()
3963
+						 . "'";
3964
+		}
3965
+		// make sure we are also getting the PKs of each table
3966
+		$tables = $this->get_tables();
3967
+		if (count($tables) > 1) {
3968
+			foreach ($tables as $table_obj) {
3969
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
+									   . $table_obj->get_fully_qualified_pk_column();
3971
+				if (! in_array($qualified_pk_column, $selects)) {
3972
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
+				}
3974
+			}
3975
+		}
3976
+		return $selects;
3977
+	}
3978
+
3979
+
3980
+	/**
3981
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
+	 * SQL for joining, and the data types
3985
+	 *
3986
+	 * @param null|string                 $original_query_param
3987
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3988
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3990
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3991
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3992
+	 *                                                          or 'Registration's
3993
+	 * @param string                      $original_query_param what it originally was (eg
3994
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3995
+	 *                                                          matches $query_param
3996
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3997
+	 * @throws EE_Error
3998
+	 */
3999
+	private function _extract_related_model_info_from_query_param(
4000
+		$query_param,
4001
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4002
+		$query_param_type,
4003
+		$original_query_param = null
4004
+	) {
4005
+		if ($original_query_param === null) {
4006
+			$original_query_param = $query_param;
4007
+		}
4008
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4009
+		// check to see if we have a field on this model
4010
+		$this_model_fields = $this->field_settings(true);
4011
+		if (array_key_exists($query_param, $this_model_fields)) {
4012
+			$field_is_allowed = in_array(
4013
+				$query_param_type,
4014
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4015
+				true
4016
+			);
4017
+			if ($field_is_allowed) {
4018
+				return;
4019
+			}
4020
+			throw new EE_Error(
4021
+				sprintf(
4022
+					esc_html__(
4023
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
+						"event_espresso"
4025
+					),
4026
+					$query_param,
4027
+					get_class($this),
4028
+					$query_param_type,
4029
+					$original_query_param
4030
+				)
4031
+			);
4032
+		}
4033
+		// check if this is a special logic query param
4034
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4036
+			if ($operator_is_allowed) {
4037
+				return;
4038
+			}
4039
+			throw new EE_Error(
4040
+				sprintf(
4041
+					esc_html__(
4042
+						'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',
4043
+						'event_espresso'
4044
+					),
4045
+					implode('", "', $this->_logic_query_param_keys),
4046
+					$query_param,
4047
+					get_class($this),
4048
+					'<br />',
4049
+					"\t"
4050
+					. ' $passed_in_query_info = <pre>'
4051
+					. print_r($passed_in_query_info, true)
4052
+					. '</pre>'
4053
+					. "\n\t"
4054
+					. ' $query_param_type = '
4055
+					. $query_param_type
4056
+					. "\n\t"
4057
+					. ' $original_query_param = '
4058
+					. $original_query_param
4059
+				)
4060
+			);
4061
+		}
4062
+		// check if it's a custom selection
4063
+		if (
4064
+			$this->_custom_selections instanceof CustomSelects
4065
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
+		) {
4067
+			return;
4068
+		}
4069
+		// check if has a model name at the beginning
4070
+		// and
4071
+		// check if it's a field on a related model
4072
+		if (
4073
+			$this->extractJoinModelFromQueryParams(
4074
+				$passed_in_query_info,
4075
+				$query_param,
4076
+				$original_query_param,
4077
+				$query_param_type
4078
+			)
4079
+		) {
4080
+			return;
4081
+		}
4082
+
4083
+		// ok so $query_param didn't start with a model name
4084
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4085
+		// it's wack, that's what it is
4086
+		throw new EE_Error(
4087
+			sprintf(
4088
+				esc_html__(
4089
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
+					"event_espresso"
4091
+				),
4092
+				$query_param,
4093
+				get_class($this),
4094
+				$query_param_type,
4095
+				$original_query_param
4096
+			)
4097
+		);
4098
+	}
4099
+
4100
+
4101
+	/**
4102
+	 * Extracts any possible join model information from the provided possible_join_string.
4103
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
+	 * join
4105
+	 * parts that should be added to the query.
4106
+	 *
4107
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
+	 * @param null|string                 $original_query_param
4110
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
+	 *                                                           etc.)
4113
+	 * @return bool  returns true if a join was added and false if not.
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractJoinModelFromQueryParams(
4117
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4118
+		$possible_join_string,
4119
+		$original_query_param,
4120
+		$query_parameter_type
4121
+	) {
4122
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
+				if ($possible_join_string === '') {
4127
+					// nothing left to $query_param
4128
+					// we should actually end in a field name, not a model like this!
4129
+					throw new EE_Error(
4130
+						sprintf(
4131
+							esc_html__(
4132
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
+								"event_espresso"
4134
+							),
4135
+							$possible_join_string,
4136
+							$query_parameter_type,
4137
+							get_class($this),
4138
+							$valid_related_model_name
4139
+						)
4140
+					);
4141
+				}
4142
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
+				$related_model_obj->_extract_related_model_info_from_query_param(
4144
+					$possible_join_string,
4145
+					$query_info_carrier,
4146
+					$query_parameter_type,
4147
+					$original_query_param
4148
+				);
4149
+				return true;
4150
+			}
4151
+			if ($possible_join_string === $valid_related_model_name) {
4152
+				$this->_add_join_to_model(
4153
+					$valid_related_model_name,
4154
+					$query_info_carrier,
4155
+					$original_query_param
4156
+				);
4157
+				return true;
4158
+			}
4159
+		}
4160
+		return false;
4161
+	}
4162
+
4163
+
4164
+	/**
4165
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
+	 *
4167
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
+	 * @throws EE_Error
4169
+	 */
4170
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
+	{
4172
+		if (
4173
+			$this->_custom_selections instanceof CustomSelects
4174
+			&& (
4175
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4176
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4177
+			)
4178
+		) {
4179
+			$original_selects = $this->_custom_selections->originalSelects();
4180
+			foreach ($original_selects as $alias => $select_configuration) {
4181
+				$this->extractJoinModelFromQueryParams(
4182
+					$query_info_carrier,
4183
+					$select_configuration[0],
4184
+					$select_configuration[0],
4185
+					'custom_selects'
4186
+				);
4187
+			}
4188
+		}
4189
+	}
4190
+
4191
+
4192
+	/**
4193
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4194
+	 * and store it on $passed_in_query_info
4195
+	 *
4196
+	 * @param string                      $model_name
4197
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4198
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4199
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4200
+	 *                                                          and are adding a join to 'Payment' with the original
4201
+	 *                                                          query param key
4202
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4203
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4204
+	 *                                                          Payment wants to add default query params so that it
4205
+	 *                                                          will know what models to prepend onto its default query
4206
+	 *                                                          params or in case it wants to rename tables (in case
4207
+	 *                                                          there are multiple joins to the same table)
4208
+	 * @return void
4209
+	 * @throws EE_Error
4210
+	 */
4211
+	private function _add_join_to_model(
4212
+		$model_name,
4213
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4214
+		$original_query_param
4215
+	) {
4216
+		$relation_obj         = $this->related_settings_for($model_name);
4217
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4218
+		// check if the relation is HABTM, because then we're essentially doing two joins
4219
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4220
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4221
+			$join_model_obj = $relation_obj->get_join_model();
4222
+			// replace the model specified with the join model for this relation chain, whi
4223
+			$relation_chain_to_join_model =
4224
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4225
+					$model_name,
4226
+					$join_model_obj->get_this_model_name(),
4227
+					$model_relation_chain
4228
+				);
4229
+			$passed_in_query_info->merge(
4230
+				new EE_Model_Query_Info_Carrier(
4231
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4232
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4233
+				)
4234
+			);
4235
+		}
4236
+		// now just join to the other table pointed to by the relation object, and add its data types
4237
+		$passed_in_query_info->merge(
4238
+			new EE_Model_Query_Info_Carrier(
4239
+				[$model_relation_chain => $model_name],
4240
+				$relation_obj->get_join_statement($model_relation_chain)
4241
+			)
4242
+		);
4243
+	}
4244
+
4245
+
4246
+	/**
4247
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4248
+	 *
4249
+	 * @param array $where_params @see
4250
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4251
+	 * @return string of SQL
4252
+	 * @throws EE_Error
4253
+	 */
4254
+	private function _construct_where_clause($where_params)
4255
+	{
4256
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257
+		if ($SQL) {
4258
+			return " WHERE " . $SQL;
4259
+		}
4260
+		return '';
4261
+	}
4262
+
4263
+
4264
+	/**
4265
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4266
+	 * and should be passed HAVING parameters, not WHERE parameters
4267
+	 *
4268
+	 * @param array $having_params
4269
+	 * @return string
4270
+	 * @throws EE_Error
4271
+	 */
4272
+	private function _construct_having_clause($having_params)
4273
+	{
4274
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275
+		if ($SQL) {
4276
+			return " HAVING " . $SQL;
4277
+		}
4278
+		return '';
4279
+	}
4280
+
4281
+
4282
+	/**
4283
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4284
+	 * Event_Meta.meta_value = 'foo'))"
4285
+	 *
4286
+	 * @param array  $where_params @see
4287
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4288
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4289
+	 * @throws EE_Error
4290
+	 * @return string of SQL
4291
+	 */
4292
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4293
+	{
4294
+		$where_clauses = [];
4295
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4296
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4297
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4298
+				switch ($query_param) {
4299
+					case 'not':
4300
+					case 'NOT':
4301
+						$where_clauses[] = "! ("
4302
+										   . $this->_construct_condition_clause_recursive(
4303
+											   $op_and_value_or_sub_condition,
4304
+											   $glue
4305
+										   )
4306
+										   . ")";
4307
+						break;
4308
+					case 'and':
4309
+					case 'AND':
4310
+						$where_clauses[] = " ("
4311
+										   . $this->_construct_condition_clause_recursive(
4312
+											   $op_and_value_or_sub_condition,
4313
+											   ' AND '
4314
+										   )
4315
+										   . ")";
4316
+						break;
4317
+					case 'or':
4318
+					case 'OR':
4319
+						$where_clauses[] = " ("
4320
+										   . $this->_construct_condition_clause_recursive(
4321
+											   $op_and_value_or_sub_condition,
4322
+											   ' OR '
4323
+										   )
4324
+										   . ")";
4325
+						break;
4326
+				}
4327
+			} else {
4328
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4329
+				// if it's not a normal field, maybe it's a custom selection?
4330
+				if (! $field_obj) {
4331
+					if ($this->_custom_selections instanceof CustomSelects) {
4332
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4333
+					} else {
4334
+						throw new EE_Error(
4335
+							sprintf(
4336
+								esc_html__(
4337
+									"%s is neither a valid model field name, nor a custom selection",
4338
+									"event_espresso"
4339
+								),
4340
+								$query_param
4341
+							)
4342
+						);
4343
+					}
4344
+				}
4345
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4346
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4347
+			}
4348
+		}
4349
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4350
+	}
4351
+
4352
+
4353
+	/**
4354
+	 * Takes the input parameter and extract the table name (alias) and column name
4355
+	 *
4356
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4357
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4358
+	 * @throws EE_Error
4359
+	 */
4360
+	private function _deduce_column_name_from_query_param($query_param)
4361
+	{
4362
+		$field = $this->_deduce_field_from_query_param($query_param);
4363
+		if ($field) {
4364
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4365
+				$field->get_model_name(),
4366
+				$query_param
4367
+			);
4368
+			return $table_alias_prefix . $field->get_qualified_column();
4369
+		}
4370
+		if (
4371
+			$this->_custom_selections instanceof CustomSelects
4372
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4373
+		) {
4374
+			// maybe it's custom selection item?
4375
+			// if so, just use it as the "column name"
4376
+			return $query_param;
4377
+		}
4378
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4379
+			? implode(',', $this->_custom_selections->columnAliases())
4380
+			: '';
4381
+		throw new EE_Error(
4382
+			sprintf(
4383
+				esc_html__(
4384
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4385
+					"event_espresso"
4386
+				),
4387
+				$query_param,
4388
+				$custom_select_aliases
4389
+			)
4390
+		);
4391
+	}
4392
+
4393
+
4394
+	/**
4395
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4396
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4397
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4398
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4399
+	 *
4400
+	 * @param string $condition_query_param_key
4401
+	 * @return string
4402
+	 */
4403
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4404
+	{
4405
+		$pos_of_star = strpos($condition_query_param_key, '*');
4406
+		if ($pos_of_star === false) {
4407
+			return $condition_query_param_key;
4408
+		}
4409
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4410
+		return $condition_query_param_sans_star;
4411
+	}
4412
+
4413
+
4414
+	/**
4415
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4416
+	 *
4417
+	 * @param mixed      array | string    $op_and_value
4418
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4419
+	 * @return string
4420
+	 * @throws EE_Error
4421
+	 */
4422
+	private function _construct_op_and_value($op_and_value, $field_obj)
4423
+	{
4424
+		if (is_array($op_and_value)) {
4425
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4426
+			if (! $operator) {
4427
+				$php_array_like_string = [];
4428
+				foreach ($op_and_value as $key => $value) {
4429
+					$php_array_like_string[] = "$key=>$value";
4430
+				}
4431
+				throw new EE_Error(
4432
+					sprintf(
4433
+						esc_html__(
4434
+							"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))",
4435
+							"event_espresso"
4436
+						),
4437
+						implode(",", $php_array_like_string)
4438
+					)
4439
+				);
4440
+			}
4441
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4442
+		} else {
4443
+			$operator = '=';
4444
+			$value    = $op_and_value;
4445
+		}
4446
+		// check to see if the value is actually another field
4447
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4448
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4449
+		}
4450
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+			// in this case, the value should be an array, or at least a comma-separated list
4452
+			// it will need to handle a little differently
4453
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4454
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4455
+			return $operator . SP . $cleaned_value;
4456
+		}
4457
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4458
+			// the value should be an array with count of two.
4459
+			if (count($value) !== 2) {
4460
+				throw new EE_Error(
4461
+					sprintf(
4462
+						esc_html__(
4463
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4464
+							'event_espresso'
4465
+						),
4466
+						"BETWEEN"
4467
+					)
4468
+				);
4469
+			}
4470
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4471
+			return $operator . SP . $cleaned_value;
4472
+		}
4473
+		if (in_array($operator, $this->valid_null_style_operators())) {
4474
+			if ($value !== null) {
4475
+				throw new EE_Error(
4476
+					sprintf(
4477
+						esc_html__(
4478
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4479
+							"event_espresso"
4480
+						),
4481
+						$value,
4482
+						$operator
4483
+					)
4484
+				);
4485
+			}
4486
+			return $operator;
4487
+		}
4488
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4489
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4490
+			// remove other junk. So just treat it as a string.
4491
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4492
+		}
4493
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4494
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4495
+		}
4496
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4497
+			throw new EE_Error(
4498
+				sprintf(
4499
+					esc_html__(
4500
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4501
+						'event_espresso'
4502
+					),
4503
+					$operator,
4504
+					$operator
4505
+				)
4506
+			);
4507
+		}
4508
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4509
+			throw new EE_Error(
4510
+				sprintf(
4511
+					esc_html__(
4512
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4513
+						'event_espresso'
4514
+					),
4515
+					$operator,
4516
+					$operator
4517
+				)
4518
+			);
4519
+		}
4520
+		throw new EE_Error(
4521
+			sprintf(
4522
+				esc_html__(
4523
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4524
+					"event_espresso"
4525
+				),
4526
+				http_build_query($op_and_value)
4527
+			)
4528
+		);
4529
+	}
4530
+
4531
+
4532
+	/**
4533
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4534
+	 *
4535
+	 * @param array                      $values
4536
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4537
+	 *                                              '%s'
4538
+	 * @return string
4539
+	 * @throws EE_Error
4540
+	 */
4541
+	public function _construct_between_value($values, $field_obj)
4542
+	{
4543
+		$cleaned_values = [];
4544
+		foreach ($values as $value) {
4545
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4546
+		}
4547
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4548
+	}
4549
+
4550
+
4551
+	/**
4552
+	 * Takes an array or a comma-separated list of $values and cleans them
4553
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4554
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4555
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4556
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4557
+	 *
4558
+	 * @param mixed                      $values    array or comma-separated string
4559
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4560
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4561
+	 * @throws EE_Error
4562
+	 */
4563
+	public function _construct_in_value($values, $field_obj)
4564
+	{
4565
+		$prepped = [];
4566
+		// check if the value is a CSV list
4567
+		if (is_string($values)) {
4568
+			// in which case, turn it into an array
4569
+			$values = explode(',', $values);
4570
+		}
4571
+		// make sure we only have one of each value in the list
4572
+		$values = array_unique($values);
4573
+		foreach ($values as $value) {
4574
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4575
+		}
4576
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4577
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4578
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4579
+		if (empty($prepped)) {
4580
+			$all_fields  = $this->field_settings();
4581
+			$first_field = reset($all_fields);
4582
+			$main_table  = $this->_get_main_table();
4583
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4584
+		}
4585
+		return '(' . implode(',', $prepped) . ')';
4586
+	}
4587
+
4588
+
4589
+	/**
4590
+	 * @param mixed                      $value
4591
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4592
+	 * @return false|null|string
4593
+	 * @throws EE_Error
4594
+	 */
4595
+	private function _wpdb_prepare_using_field($value, $field_obj)
4596
+	{
4597
+		/** @type WPDB $wpdb */
4598
+		global $wpdb;
4599
+		if ($field_obj instanceof EE_Model_Field_Base) {
4600
+			return $wpdb->prepare(
4601
+				$field_obj->get_wpdb_data_type(),
4602
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4603
+			);
4604
+		} //$field_obj should really just be a data type
4605
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4606
+			throw new EE_Error(
4607
+				sprintf(
4608
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4609
+					$field_obj,
4610
+					implode(",", $this->_valid_wpdb_data_types)
4611
+				)
4612
+			);
4613
+		}
4614
+		return $wpdb->prepare($field_obj, $value);
4615
+	}
4616
+
4617
+
4618
+	/**
4619
+	 * Takes the input parameter and finds the model field that it indicates.
4620
+	 *
4621
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4622
+	 * @return EE_Model_Field_Base
4623
+	 * @throws EE_Error
4624
+	 */
4625
+	protected function _deduce_field_from_query_param($query_param_name)
4626
+	{
4627
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4628
+		// which will help us find the database table and column
4629
+		$query_param_parts = explode(".", $query_param_name);
4630
+		if (empty($query_param_parts)) {
4631
+			throw new EE_Error(
4632
+				sprintf(
4633
+					esc_html__(
4634
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4635
+						'event_espresso'
4636
+					),
4637
+					$query_param_name
4638
+				)
4639
+			);
4640
+		}
4641
+		$number_of_parts       = count($query_param_parts);
4642
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4643
+		if ($number_of_parts === 1) {
4644
+			$field_name = $last_query_param_part;
4645
+			$model_obj  = $this;
4646
+		} else {// $number_of_parts >= 2
4647
+			// the last part is the column name, and there are only 2parts. therefore...
4648
+			$field_name = $last_query_param_part;
4649
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4650
+		}
4651
+		try {
4652
+			return $model_obj->field_settings_for($field_name);
4653
+		} catch (EE_Error $e) {
4654
+			return null;
4655
+		}
4656
+	}
4657
+
4658
+
4659
+	/**
4660
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4661
+	 * alias and column which corresponds to it
4662
+	 *
4663
+	 * @param string $field_name
4664
+	 * @return string
4665
+	 * @throws EE_Error
4666
+	 */
4667
+	public function _get_qualified_column_for_field($field_name)
4668
+	{
4669
+		$all_fields = $this->field_settings();
4670
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4671
+		if ($field) {
4672
+			return $field->get_qualified_column();
4673
+		}
4674
+		throw new EE_Error(
4675
+			sprintf(
4676
+				esc_html__(
4677
+					"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.",
4678
+					'event_espresso'
4679
+				),
4680
+				$field_name,
4681
+				get_class($this)
4682
+			)
4683
+		);
4684
+	}
4685
+
4686
+
4687
+	/**
4688
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4689
+	 * Example usage:
4690
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4691
+	 *      array(),
4692
+	 *      ARRAY_A,
4693
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4694
+	 *  );
4695
+	 * is equivalent to
4696
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4697
+	 * and
4698
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4699
+	 *      array(
4700
+	 *          array(
4701
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4702
+	 *          ),
4703
+	 *          ARRAY_A,
4704
+	 *          implode(
4705
+	 *              ', ',
4706
+	 *              array_merge(
4707
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4708
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4709
+	 *              )
4710
+	 *          )
4711
+	 *      )
4712
+	 *  );
4713
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4714
+	 *
4715
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4716
+	 *                                            and the one whose fields you are selecting for example: when querying
4717
+	 *                                            tickets model and selecting fields from the tickets model you would
4718
+	 *                                            leave this parameter empty, because no models are needed to join
4719
+	 *                                            between the queried model and the selected one. Likewise when
4720
+	 *                                            querying the datetime model and selecting fields from the tickets
4721
+	 *                                            model, it would also be left empty, because there is a direct
4722
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4723
+	 *                                            them together. However, when querying from the event model and
4724
+	 *                                            selecting fields from the ticket model, you should provide the string
4725
+	 *                                            'Datetime', indicating that the event model must first join to the
4726
+	 *                                            datetime model in order to find its relation to ticket model.
4727
+	 *                                            Also, when querying from the venue model and selecting fields from
4728
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4729
+	 *                                            indicating you need to join the venue model to the event model,
4730
+	 *                                            to the datetime model, in order to find its relation to the ticket
4731
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4732
+	 *                                            the models' tables qualified columns
4733
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4734
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4735
+	 *                                            qualified column names
4736
+	 * @return array|string
4737
+	 */
4738
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4739
+	{
4740
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4741
+		$qualified_columns = [];
4742
+		foreach ($this->field_settings() as $field_name => $field) {
4743
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4744
+		}
4745
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4746
+	}
4747
+
4748
+
4749
+	/**
4750
+	 * constructs the select use on special limit joins
4751
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4752
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4753
+	 * (as that is typically where the limits would be set).
4754
+	 *
4755
+	 * @param string       $table_alias The table the select is being built for
4756
+	 * @param mixed|string $limit       The limit for this select
4757
+	 * @return string                The final select join element for the query.
4758
+	 */
4759
+	public function _construct_limit_join_select($table_alias, $limit)
4760
+	{
4761
+		$SQL = '';
4762
+		foreach ($this->_tables as $table_obj) {
4763
+			if ($table_obj instanceof EE_Primary_Table) {
4764
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4765
+					? $table_obj->get_select_join_limit($limit)
4766
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4767
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4768
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4769
+					? $table_obj->get_select_join_limit_join($limit)
4770
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4771
+			}
4772
+		}
4773
+		return $SQL;
4774
+	}
4775
+
4776
+
4777
+	/**
4778
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4779
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4780
+	 *
4781
+	 * @return string SQL
4782
+	 * @throws EE_Error
4783
+	 */
4784
+	public function _construct_internal_join()
4785
+	{
4786
+		$SQL = $this->_get_main_table()->get_table_sql();
4787
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4788
+		return $SQL;
4789
+	}
4790
+
4791
+
4792
+	/**
4793
+	 * Constructs the SQL for joining all the tables on this model.
4794
+	 * Normally $alias should be the primary table's alias, but in cases where
4795
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4796
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4797
+	 * alias, this will construct SQL like:
4798
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4799
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4800
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4801
+	 *
4802
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4803
+	 * @return string
4804
+	 */
4805
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4806
+	{
4807
+		$SQL               = '';
4808
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4809
+		foreach ($this->_tables as $table_obj) {
4810
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4811
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4812
+					// so we're joining to this table, meaning the table is already in
4813
+					// the FROM statement, BUT the primary table isn't. So we want
4814
+					// to add the inverse join sql
4815
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4816
+				} else {
4817
+					// just add a regular JOIN to this table from the primary table
4818
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4819
+				}
4820
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4821
+		}
4822
+		return $SQL;
4823
+	}
4824
+
4825
+
4826
+	/**
4827
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
+	 * their data type (eg, '%s', '%d', etc)
4830
+	 *
4831
+	 * @return array
4832
+	 */
4833
+	public function _get_data_types()
4834
+	{
4835
+		$data_types = [];
4836
+		foreach ($this->field_settings() as $field_obj) {
4837
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
+			/** @var $field_obj EE_Model_Field_Base */
4839
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
+		}
4841
+		return $data_types;
4842
+	}
4843
+
4844
+
4845
+	/**
4846
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4847
+	 *
4848
+	 * @param string $model_name
4849
+	 * @return EEM_Base
4850
+	 * @throws EE_Error
4851
+	 */
4852
+	public function get_related_model_obj($model_name)
4853
+	{
4854
+		$model_classname = "EEM_" . $model_name;
4855
+		if (! class_exists($model_classname)) {
4856
+			throw new EE_Error(
4857
+				sprintf(
4858
+					esc_html__(
4859
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4860
+						'event_espresso'
4861
+					),
4862
+					$model_name,
4863
+					$model_classname
4864
+				)
4865
+			);
4866
+		}
4867
+		return call_user_func($model_classname . "::instance");
4868
+	}
4869
+
4870
+
4871
+	/**
4872
+	 * Returns the array of EE_ModelRelations for this model.
4873
+	 *
4874
+	 * @return EE_Model_Relation_Base[]
4875
+	 */
4876
+	public function relation_settings()
4877
+	{
4878
+		return $this->_model_relations;
4879
+	}
4880
+
4881
+
4882
+	/**
4883
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4884
+	 * because without THOSE models, this model probably doesn't have much purpose.
4885
+	 * (Eg, without an event, datetimes have little purpose.)
4886
+	 *
4887
+	 * @return EE_Belongs_To_Relation[]
4888
+	 */
4889
+	public function belongs_to_relations()
4890
+	{
4891
+		$belongs_to_relations = [];
4892
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4893
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4894
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4895
+			}
4896
+		}
4897
+		return $belongs_to_relations;
4898
+	}
4899
+
4900
+
4901
+	/**
4902
+	 * Returns the specified EE_Model_Relation, or throws an exception
4903
+	 *
4904
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4905
+	 * @return EE_Model_Relation_Base
4906
+	 * @throws EE_Error
4907
+	 */
4908
+	public function related_settings_for($relation_name)
4909
+	{
4910
+		$relatedModels = $this->relation_settings();
4911
+		if (! array_key_exists($relation_name, $relatedModels)) {
4912
+			throw new EE_Error(
4913
+				sprintf(
4914
+					esc_html__(
4915
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4916
+						'event_espresso'
4917
+					),
4918
+					$relation_name,
4919
+					$this->_get_class_name(),
4920
+					implode(', ', array_keys($relatedModels))
4921
+				)
4922
+			);
4923
+		}
4924
+		return $relatedModels[ $relation_name ];
4925
+	}
4926
+
4927
+
4928
+	/**
4929
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4930
+	 * fields
4931
+	 *
4932
+	 * @param string  $fieldName
4933
+	 * @param boolean $include_db_only_fields
4934
+	 * @return EE_Model_Field_Base
4935
+	 * @throws EE_Error
4936
+	 */
4937
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4938
+	{
4939
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4940
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4941
+			throw new EE_Error(
4942
+				sprintf(
4943
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4944
+					$fieldName,
4945
+					get_class($this)
4946
+				)
4947
+			);
4948
+		}
4949
+		return $fieldSettings[ $fieldName ];
4950
+	}
4951
+
4952
+
4953
+	/**
4954
+	 * Checks if this field exists on this model
4955
+	 *
4956
+	 * @param string $fieldName a key in the model's _field_settings array
4957
+	 * @return boolean
4958
+	 */
4959
+	public function has_field($fieldName)
4960
+	{
4961
+		$fieldSettings = $this->field_settings(true);
4962
+		if (isset($fieldSettings[ $fieldName ])) {
4963
+			return true;
4964
+		}
4965
+		return false;
4966
+	}
4967
+
4968
+
4969
+	/**
4970
+	 * Returns whether or not this model has a relation to the specified model
4971
+	 *
4972
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4973
+	 * @return boolean
4974
+	 */
4975
+	public function has_relation($relation_name)
4976
+	{
4977
+		$relations = $this->relation_settings();
4978
+		if (isset($relations[ $relation_name ])) {
4979
+			return true;
4980
+		}
4981
+		return false;
4982
+	}
4983
+
4984
+
4985
+	/**
4986
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
+	 * Eg, on EE_Answer that would be ANS_ID field object
4988
+	 *
4989
+	 * @param $field_obj
4990
+	 * @return boolean
4991
+	 */
4992
+	public function is_primary_key_field($field_obj)
4993
+	{
4994
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
+	}
4996
+
4997
+
4998
+	/**
4999
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5000
+	 * Eg, on EE_Answer that would be ANS_ID field object
5001
+	 *
5002
+	 * @return EE_Primary_Key_Field_Base
5003
+	 * @throws EE_Error
5004
+	 */
5005
+	public function get_primary_key_field()
5006
+	{
5007
+		if ($this->_primary_key_field === null) {
5008
+			foreach ($this->field_settings(true) as $field_obj) {
5009
+				if ($this->is_primary_key_field($field_obj)) {
5010
+					$this->_primary_key_field = $field_obj;
5011
+					break;
5012
+				}
5013
+			}
5014
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5015
+				throw new EE_Error(
5016
+					sprintf(
5017
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5018
+						get_class($this)
5019
+					)
5020
+				);
5021
+			}
5022
+		}
5023
+		return $this->_primary_key_field;
5024
+	}
5025
+
5026
+
5027
+	/**
5028
+	 * Returns whether or not not there is a primary key on this model.
5029
+	 * Internally does some caching.
5030
+	 *
5031
+	 * @return boolean
5032
+	 */
5033
+	public function has_primary_key_field()
5034
+	{
5035
+		if ($this->_has_primary_key_field === null) {
5036
+			try {
5037
+				$this->get_primary_key_field();
5038
+				$this->_has_primary_key_field = true;
5039
+			} catch (EE_Error $e) {
5040
+				$this->_has_primary_key_field = false;
5041
+			}
5042
+		}
5043
+		return $this->_has_primary_key_field;
5044
+	}
5045
+
5046
+
5047
+	/**
5048
+	 * Finds the first field of type $field_class_name.
5049
+	 *
5050
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5051
+	 *                                 EE_Foreign_Key_Field, etc
5052
+	 * @return EE_Model_Field_Base or null if none is found
5053
+	 */
5054
+	public function get_a_field_of_type($field_class_name)
5055
+	{
5056
+		foreach ($this->field_settings() as $field) {
5057
+			if ($field instanceof $field_class_name) {
5058
+				return $field;
5059
+			}
5060
+		}
5061
+		return null;
5062
+	}
5063
+
5064
+
5065
+	/**
5066
+	 * Gets a foreign key field pointing to model.
5067
+	 *
5068
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5069
+	 * @return EE_Foreign_Key_Field_Base
5070
+	 * @throws EE_Error
5071
+	 */
5072
+	public function get_foreign_key_to($model_name)
5073
+	{
5074
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5075
+			foreach ($this->field_settings() as $field) {
5076
+				if (
5077
+					$field instanceof EE_Foreign_Key_Field_Base
5078
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5079
+				) {
5080
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5081
+					break;
5082
+				}
5083
+			}
5084
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5085
+				throw new EE_Error(
5086
+					sprintf(
5087
+						esc_html__(
5088
+							"There is no foreign key field pointing to model %s on model %s",
5089
+							'event_espresso'
5090
+						),
5091
+						$model_name,
5092
+						get_class($this)
5093
+					)
5094
+				);
5095
+			}
5096
+		}
5097
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5098
+	}
5099
+
5100
+
5101
+	/**
5102
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5103
+	 *
5104
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5105
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5106
+	 *                            Either one works
5107
+	 * @return string
5108
+	 */
5109
+	public function get_table_for_alias($table_alias)
5110
+	{
5111
+		$table_alias_sans_model_relation_chain_prefix =
5112
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5113
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5114
+	}
5115
+
5116
+
5117
+	/**
5118
+	 * Returns a flat array of all field son this model, instead of organizing them
5119
+	 * by table_alias as they are in the constructor.
5120
+	 *
5121
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5122
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5123
+	 */
5124
+	public function field_settings($include_db_only_fields = false)
5125
+	{
5126
+		if ($include_db_only_fields) {
5127
+			if ($this->_cached_fields === null) {
5128
+				$this->_cached_fields = [];
5129
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5130
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5131
+						$this->_cached_fields[ $field_name ] = $field_obj;
5132
+					}
5133
+				}
5134
+			}
5135
+			return $this->_cached_fields;
5136
+		}
5137
+		if ($this->_cached_fields_non_db_only === null) {
5138
+			$this->_cached_fields_non_db_only = [];
5139
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5140
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5141
+					/** @var $field_obj EE_Model_Field_Base */
5142
+					if (! $field_obj->is_db_only_field()) {
5143
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5144
+					}
5145
+				}
5146
+			}
5147
+		}
5148
+		return $this->_cached_fields_non_db_only;
5149
+	}
5150
+
5151
+
5152
+	/**
5153
+	 *        cycle though array of attendees and create objects out of each item
5154
+	 *
5155
+	 * @access        private
5156
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5157
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5158
+	 *                           numerically indexed)
5159
+	 * @throws EE_Error
5160
+	 */
5161
+	protected function _create_objects($rows = [])
5162
+	{
5163
+		$array_of_objects = [];
5164
+		if (empty($rows)) {
5165
+			return [];
5166
+		}
5167
+		$count_if_model_has_no_primary_key = 0;
5168
+		$has_primary_key                   = $this->has_primary_key_field();
5169
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5170
+		foreach ((array) $rows as $row) {
5171
+			if (empty($row)) {
5172
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5173
+				return [];
5174
+			}
5175
+			// check if we've already set this object in the results array,
5176
+			// in which case there's no need to process it further (again)
5177
+			if ($has_primary_key) {
5178
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5179
+					$row,
5180
+					$primary_key_field->get_qualified_column(),
5181
+					$primary_key_field->get_table_column()
5182
+				);
5183
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5184
+					continue;
5185
+				}
5186
+			}
5187
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5188
+			if (! $classInstance) {
5189
+				throw new EE_Error(
5190
+					sprintf(
5191
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5192
+						$this->get_this_model_name(),
5193
+						http_build_query($row)
5194
+					)
5195
+				);
5196
+			}
5197
+			// set the timezone on the instantiated objects
5198
+			$classInstance->set_timezone($this->_timezone);
5199
+			// make sure if there is any timezone setting present that we set the timezone for the object
5200
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5201
+			$array_of_objects[ $key ] = $classInstance;
5202
+			// also, for all the relations of type BelongsTo, see if we can cache
5203
+			// those related models
5204
+			// (we could do this for other relations too, but if there are conditions
5205
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5206
+			// so it requires a little more thought than just caching them immediately...)
5207
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5208
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5209
+					// check if this model's INFO is present. If so, cache it on the model
5210
+					$other_model           = $relation_obj->get_other_model();
5211
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5212
+					// if we managed to make a model object from the results, cache it on the main model object
5213
+					if ($other_model_obj_maybe) {
5214
+						// set timezone on these other model objects if they are present
5215
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5216
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5217
+					}
5218
+				}
5219
+			}
5220
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5221
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5222
+			// the field in the CustomSelects object
5223
+			if ($this->_custom_selections instanceof CustomSelects) {
5224
+				$classInstance->setCustomSelectsValues(
5225
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5226
+				);
5227
+			}
5228
+		}
5229
+		return $array_of_objects;
5230
+	}
5231
+
5232
+
5233
+	/**
5234
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5235
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5236
+	 *
5237
+	 * @param array $db_results_row
5238
+	 * @return array
5239
+	 */
5240
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5241
+	{
5242
+		$results = [];
5243
+		if ($this->_custom_selections instanceof CustomSelects) {
5244
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5245
+				if (isset($db_results_row[ $alias ])) {
5246
+					$results[ $alias ] = $this->convertValueToDataType(
5247
+						$db_results_row[ $alias ],
5248
+						$this->_custom_selections->getDataTypeForAlias($alias)
5249
+					);
5250
+				}
5251
+			}
5252
+		}
5253
+		return $results;
5254
+	}
5255
+
5256
+
5257
+	/**
5258
+	 * This will set the value for the given alias
5259
+	 *
5260
+	 * @param string $value
5261
+	 * @param string $datatype (one of %d, %s, %f)
5262
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5263
+	 */
5264
+	protected function convertValueToDataType($value, $datatype)
5265
+	{
5266
+		switch ($datatype) {
5267
+			case '%f':
5268
+				return (float) $value;
5269
+			case '%d':
5270
+				return (int) $value;
5271
+			default:
5272
+				return (string) $value;
5273
+		}
5274
+	}
5275
+
5276
+
5277
+	/**
5278
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5279
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5280
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5281
+	 * object (as set in the model_field!).
5282
+	 *
5283
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5284
+	 * @throws EE_Error
5285
+	 * @throws ReflectionException
5286
+	 */
5287
+	public function create_default_object()
5288
+	{
5289
+		$this_model_fields_and_values = [];
5290
+		// setup the row using default values;
5291
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5292
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5293
+		}
5294
+		$className     = $this->_get_class_name();
5295
+		return EE_Registry::instance()->load_class(
5296
+			$className,
5297
+			[$this_model_fields_and_values],
5298
+			false,
5299
+			false
5300
+		);
5301
+	}
5302
+
5303
+
5304
+	/**
5305
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5306
+	 *                             or an stdClass where each property is the name of a column,
5307
+	 * @return EE_Base_Class
5308
+	 * @throws EE_Error
5309
+	 */
5310
+	public function instantiate_class_from_array_or_object($cols_n_values)
5311
+	{
5312
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5313
+			$cols_n_values = get_object_vars($cols_n_values);
5314
+		}
5315
+		$primary_key = null;
5316
+		// make sure the array only has keys that are fields/columns on this model
5317
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5318
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5320
+		}
5321
+		$className = $this->_get_class_name();
5322
+		// check we actually found results that we can use to build our model object
5323
+		// if not, return null
5324
+		if ($this->has_primary_key_field()) {
5325
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5326
+				return null;
5327
+			}
5328
+		} elseif ($this->unique_indexes()) {
5329
+			$first_column = reset($this_model_fields_n_values);
5330
+			if (empty($first_column)) {
5331
+				return null;
5332
+			}
5333
+		}
5334
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5335
+		if ($primary_key) {
5336
+			$classInstance = $this->get_from_entity_map($primary_key);
5337
+			if (! $classInstance) {
5338
+				$classInstance = EE_Registry::instance()
5339
+											->load_class(
5340
+												$className,
5341
+												[$this_model_fields_n_values, $this->_timezone],
5342
+												true,
5343
+												false
5344
+											);
5345
+				// add this new object to the entity map
5346
+				$classInstance = $this->add_to_entity_map($classInstance);
5347
+			}
5348
+		} else {
5349
+			$classInstance = EE_Registry::instance()
5350
+										->load_class(
5351
+											$className,
5352
+											[$this_model_fields_n_values, $this->_timezone],
5353
+											true,
5354
+											false
5355
+										);
5356
+		}
5357
+		return $classInstance;
5358
+	}
5359
+
5360
+
5361
+	/**
5362
+	 * Gets the model object from the  entity map if it exists
5363
+	 *
5364
+	 * @param int|string $id the ID of the model object
5365
+	 * @return EE_Base_Class
5366
+	 */
5367
+	public function get_from_entity_map($id)
5368
+	{
5369
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5370
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5371
+	}
5372
+
5373
+
5374
+	/**
5375
+	 * add_to_entity_map
5376
+	 * Adds the object to the model's entity mappings
5377
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5378
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5379
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5380
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5381
+	 *        then this method should be called immediately after the update query
5382
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5383
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5384
+	 *
5385
+	 * @param EE_Base_Class $object
5386
+	 * @return \EE_Base_Class
5387
+	 * @throws EE_Error
5388
+	 */
5389
+	public function add_to_entity_map(EE_Base_Class $object)
5390
+	{
5391
+		$className = $this->_get_class_name();
5392
+		if (! $object instanceof $className) {
5393
+			throw new EE_Error(
5394
+				sprintf(
5395
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5396
+					is_object($object) ? get_class($object) : $object,
5397
+					$className
5398
+				)
5399
+			);
5400
+		}
5401
+		/** @var $object EE_Base_Class */
5402
+		if (! $object->ID()) {
5403
+			throw new EE_Error(
5404
+				sprintf(
5405
+					esc_html__(
5406
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5407
+						"event_espresso"
5408
+					),
5409
+					get_class($this)
5410
+				)
5411
+			);
5412
+		}
5413
+		// double check it's not already there
5414
+		$classInstance = $this->get_from_entity_map($object->ID());
5415
+		if ($classInstance) {
5416
+			return $classInstance;
5417
+		}
5418
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5419
+		return $object;
5420
+	}
5421
+
5422
+
5423
+	/**
5424
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5425
+	 * if no identifier is provided, then the entire entity map is emptied
5426
+	 *
5427
+	 * @param int|string $id the ID of the model object
5428
+	 * @return boolean
5429
+	 */
5430
+	public function clear_entity_map($id = null)
5431
+	{
5432
+		if (empty($id)) {
5433
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5434
+			return true;
5435
+		}
5436
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5437
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5438
+			return true;
5439
+		}
5440
+		return false;
5441
+	}
5442
+
5443
+
5444
+	/**
5445
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5446
+	 * Given an array where keys are column (or column alias) names and values,
5447
+	 * returns an array of their corresponding field names and database values
5448
+	 *
5449
+	 * @param array $cols_n_values
5450
+	 * @return array
5451
+	 * @throws EE_Error
5452
+	 * @throws ReflectionException
5453
+	 */
5454
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5455
+	{
5456
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5457
+	}
5458
+
5459
+
5460
+	/**
5461
+	 * _deduce_fields_n_values_from_cols_n_values
5462
+	 * Given an array where keys are column (or column alias) names and values,
5463
+	 * returns an array of their corresponding field names and database values
5464
+	 *
5465
+	 * @param array $cols_n_values
5466
+	 * @return array
5467
+	 * @throws EE_Error
5468
+	 * @throws ReflectionException
5469
+	 */
5470
+	protected function _deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5471
+	{
5472
+		$this_model_fields_n_values = [];
5473
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
+				$cols_n_values,
5476
+				$table_obj->get_fully_qualified_pk_column(),
5477
+				$table_obj->get_pk_column()
5478
+			);
5479
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5480
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
+					if (! $field_obj->is_db_only_field()) {
5483
+						// prepare field as if its coming from db
5484
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5485
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5486
+					}
5487
+				}
5488
+			} else {
5489
+				// the table's rows existed. Use their values
5490
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5491
+					if (! $field_obj->is_db_only_field()) {
5492
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5493
+							$cols_n_values,
5494
+							$field_obj->get_qualified_column(),
5495
+							$field_obj->get_table_column()
5496
+						);
5497
+					}
5498
+				}
5499
+			}
5500
+		}
5501
+		return $this_model_fields_n_values;
5502
+	}
5503
+
5504
+
5505
+	/**
5506
+	 * @param array $cols_n_values
5507
+	 * @param $qualified_column
5508
+	 * @param $regular_column
5509
+	 * @return null
5510
+	 * @throws EE_Error
5511
+	 * @throws ReflectionException
5512
+	 */
5513
+	protected function _get_column_value_with_table_alias_or_not(array $cols_n_values, $qualified_column, $regular_column)
5514
+	{
5515
+		$value = null;
5516
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517
+		// does the field on the model relate to this column retrieved from the db?
5518
+		// or is it a db-only field? (not relating to the model)
5519
+		if (isset($cols_n_values[ $qualified_column ])) {
5520
+			$value = $cols_n_values[ $qualified_column ];
5521
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5522
+			$value = $cols_n_values[ $regular_column ];
5523
+		} elseif (! empty($this->foreign_key_aliases)) {
5524
+			// no PK?  ok check if there is a foreign key alias set for this table
5525
+			// then check if that alias exists in the incoming data
5526
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
+					$value = $cols_n_values[ $FK_alias ];
5530
+					[$pk_class] = explode('.', $PK_column);
5531
+					$pk_model_name = "EEM_{$pk_class}";
5532
+					/** @var EEM_Base $pk_model */
5533
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5534
+					if ($pk_model instanceof EEM_Base) {
5535
+						// make sure object is pulled from db and added to entity map
5536
+						$pk_model->get_one_by_ID($value);
5537
+					}
5538
+					break;
5539
+				}
5540
+			}
5541
+		}
5542
+		return $value;
5543
+	}
5544
+
5545
+
5546
+	/**
5547
+	 * refresh_entity_map_from_db
5548
+	 * Makes sure the model object in the entity map at $id assumes the values
5549
+	 * of the database (opposite of EE_base_Class::save())
5550
+	 *
5551
+	 * @param int|string $id
5552
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5553
+	 * @throws EE_Error
5554
+	 * @throws ReflectionException
5555
+	 */
5556
+	public function refresh_entity_map_from_db($id)
5557
+	{
5558
+		$obj_in_map = $this->get_from_entity_map($id);
5559
+		if ($obj_in_map) {
5560
+			$wpdb_results = $this->_get_all_wpdb_results(
5561
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5562
+			);
5563
+			if ($wpdb_results && is_array($wpdb_results)) {
5564
+				$one_row = reset($wpdb_results);
5565
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5566
+					$obj_in_map->set_from_db($field_name, $db_value);
5567
+				}
5568
+				// clear the cache of related model objects
5569
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5570
+					$obj_in_map->clear_cache($relation_name, null, true);
5571
+				}
5572
+			}
5573
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5574
+			return $obj_in_map;
5575
+		}
5576
+		return $this->get_one_by_ID($id);
5577
+	}
5578
+
5579
+
5580
+	/**
5581
+	 * refresh_entity_map_with
5582
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5583
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5584
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5585
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5586
+	 *
5587
+	 * @param int|string    $id
5588
+	 * @param EE_Base_Class $replacing_model_obj
5589
+	 * @return \EE_Base_Class
5590
+	 * @throws EE_Error
5591
+	 */
5592
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5593
+	{
5594
+		$obj_in_map = $this->get_from_entity_map($id);
5595
+		if ($obj_in_map) {
5596
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5597
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5598
+					$obj_in_map->set($field_name, $value);
5599
+				}
5600
+				// make the model object in the entity map's cache match the $replacing_model_obj
5601
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5602
+					$obj_in_map->clear_cache($relation_name, null, true);
5603
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5604
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5605
+					}
5606
+				}
5607
+			}
5608
+			return $obj_in_map;
5609
+		}
5610
+		$this->add_to_entity_map($replacing_model_obj);
5611
+		return $replacing_model_obj;
5612
+	}
5613
+
5614
+
5615
+	/**
5616
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5617
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5618
+	 * require_once($this->_getClassName().".class.php");
5619
+	 *
5620
+	 * @return string
5621
+	 */
5622
+	private function _get_class_name()
5623
+	{
5624
+		return "EE_" . $this->get_this_model_name();
5625
+	}
5626
+
5627
+
5628
+	/**
5629
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5630
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5631
+	 * it would be 'Events'.
5632
+	 *
5633
+	 * @param int|float|null $quantity
5634
+	 * @return string
5635
+	 */
5636
+	public function item_name($quantity = 1): string
5637
+	{
5638
+		$quantity = floor($quantity);
5639
+		return apply_filters(
5640
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5641
+			$quantity > 1 ? $this->plural_item : $this->singular_item,
5642
+			$quantity,
5643
+			$this->plural_item,
5644
+			$this->singular_item
5645
+		);
5646
+	}
5647
+
5648
+
5649
+	/**
5650
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5651
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5652
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5653
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5654
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5655
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5656
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5657
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5658
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5659
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5660
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5661
+	 *        return $previousReturnValue.$returnString;
5662
+	 * }
5663
+	 * require('EEM_Answer.model.php');
5664
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5665
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5666
+	 *
5667
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5668
+	 * @param array  $args       array of original arguments passed to the function
5669
+	 * @return mixed whatever the plugin which calls add_filter decides
5670
+	 * @throws EE_Error
5671
+	 */
5672
+	public function __call($methodName, $args)
5673
+	{
5674
+		$className = get_class($this);
5675
+		$tagName   = "FHEE__{$className}__{$methodName}";
5676
+		if (! has_filter($tagName)) {
5677
+			throw new EE_Error(
5678
+				sprintf(
5679
+					esc_html__(
5680
+						'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 );',
5681
+						'event_espresso'
5682
+					),
5683
+					$methodName,
5684
+					$className,
5685
+					$tagName,
5686
+					'<br />'
5687
+				)
5688
+			);
5689
+		}
5690
+		return apply_filters($tagName, null, $this, $args);
5691
+	}
5692
+
5693
+
5694
+	/**
5695
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5696
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5697
+	 *
5698
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5699
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5700
+	 *                                                       the object's class name
5701
+	 *                                                       or object's ID
5702
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5703
+	 *                                                       exists in the database. If it does not, we add it
5704
+	 * @return EE_Base_Class
5705
+	 * @throws EE_Error
5706
+	 */
5707
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5708
+	{
5709
+		$className = $this->_get_class_name();
5710
+		if ($base_class_obj_or_id instanceof $className) {
5711
+			$model_object = $base_class_obj_or_id;
5712
+		} else {
5713
+			$primary_key_field = $this->get_primary_key_field();
5714
+			if (
5715
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5716
+				&& (
5717
+					is_int($base_class_obj_or_id)
5718
+					|| is_string($base_class_obj_or_id)
5719
+				)
5720
+			) {
5721
+				// assume it's an ID.
5722
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5723
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5724
+			} elseif (
5725
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5726
+				&& is_string($base_class_obj_or_id)
5727
+			) {
5728
+				// assume its a string representation of the object
5729
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5730
+			} else {
5731
+				throw new EE_Error(
5732
+					sprintf(
5733
+						esc_html__(
5734
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5735
+							'event_espresso'
5736
+						),
5737
+						$base_class_obj_or_id,
5738
+						$this->_get_class_name(),
5739
+						print_r($base_class_obj_or_id, true)
5740
+					)
5741
+				);
5742
+			}
5743
+		}
5744
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5745
+			$model_object->save();
5746
+		}
5747
+		return $model_object;
5748
+	}
5749
+
5750
+
5751
+	/**
5752
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5753
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5754
+	 * returns it ID.
5755
+	 *
5756
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5757
+	 * @return int|string depending on the type of this model object's ID
5758
+	 * @throws EE_Error
5759
+	 */
5760
+	public function ensure_is_ID($base_class_obj_or_id)
5761
+	{
5762
+		$className = $this->_get_class_name();
5763
+		if ($base_class_obj_or_id instanceof $className) {
5764
+			/** @var $base_class_obj_or_id EE_Base_Class */
5765
+			$id = $base_class_obj_or_id->ID();
5766
+		} elseif (is_int($base_class_obj_or_id)) {
5767
+			// assume it's an ID
5768
+			$id = $base_class_obj_or_id;
5769
+		} elseif (is_string($base_class_obj_or_id)) {
5770
+			// assume its a string representation of the object
5771
+			$id = $base_class_obj_or_id;
5772
+		} else {
5773
+			throw new EE_Error(
5774
+				sprintf(
5775
+					esc_html__(
5776
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5777
+						'event_espresso'
5778
+					),
5779
+					$base_class_obj_or_id,
5780
+					$this->_get_class_name(),
5781
+					print_r($base_class_obj_or_id, true)
5782
+				)
5783
+			);
5784
+		}
5785
+		return $id;
5786
+	}
5787
+
5788
+
5789
+	/**
5790
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5791
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5792
+	 * been sanitized and converted into the appropriate domain.
5793
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5794
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5795
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5796
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5797
+	 * $EVT = EEM_Event::instance(); $old_setting =
5798
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5799
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5800
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5801
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5802
+	 *
5803
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5804
+	 * @return void
5805
+	 */
5806
+	public function assume_values_already_prepared_by_model_object(
5807
+		$values_already_prepared = self::not_prepared_by_model_object
5808
+	) {
5809
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5810
+	}
5811
+
5812
+
5813
+	/**
5814
+	 * Read comments for assume_values_already_prepared_by_model_object()
5815
+	 *
5816
+	 * @return int
5817
+	 */
5818
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5819
+	{
5820
+		return $this->_values_already_prepared_by_model_object;
5821
+	}
5822
+
5823
+
5824
+	/**
5825
+	 * Gets all the indexes on this model
5826
+	 *
5827
+	 * @return EE_Index[]
5828
+	 */
5829
+	public function indexes()
5830
+	{
5831
+		return $this->_indexes;
5832
+	}
5833
+
5834
+
5835
+	/**
5836
+	 * Gets all the Unique Indexes on this model
5837
+	 *
5838
+	 * @return EE_Unique_Index[]
5839
+	 */
5840
+	public function unique_indexes()
5841
+	{
5842
+		$unique_indexes = [];
5843
+		foreach ($this->_indexes as $name => $index) {
5844
+			if ($index instanceof EE_Unique_Index) {
5845
+				$unique_indexes [ $name ] = $index;
5846
+			}
5847
+		}
5848
+		return $unique_indexes;
5849
+	}
5850
+
5851
+
5852
+	/**
5853
+	 * Gets all the fields which, when combined, make the primary key.
5854
+	 * This is usually just an array with 1 element (the primary key), but in cases
5855
+	 * where there is no primary key, it's a combination of fields as defined
5856
+	 * on a primary index
5857
+	 *
5858
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5859
+	 * @throws EE_Error
5860
+	 */
5861
+	public function get_combined_primary_key_fields()
5862
+	{
5863
+		foreach ($this->indexes() as $index) {
5864
+			if ($index instanceof EE_Primary_Key_Index) {
5865
+				return $index->fields();
5866
+			}
5867
+		}
5868
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5869
+	}
5870
+
5871
+
5872
+	/**
5873
+	 * Used to build a primary key string (when the model has no primary key),
5874
+	 * which can be used a unique string to identify this model object.
5875
+	 *
5876
+	 * @param array $fields_n_values keys are field names, values are their values.
5877
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5878
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5879
+	 *                               before passing it to this function (that will convert it from columns-n-values
5880
+	 *                               to field-names-n-values).
5881
+	 * @return string
5882
+	 * @throws EE_Error
5883
+	 */
5884
+	public function get_index_primary_key_string($fields_n_values)
5885
+	{
5886
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5887
+			$fields_n_values,
5888
+			$this->get_combined_primary_key_fields()
5889
+		);
5890
+		return http_build_query($cols_n_values_for_primary_key_index);
5891
+	}
5892
+
5893
+
5894
+	/**
5895
+	 * Gets the field values from the primary key string
5896
+	 *
5897
+	 * @param string $index_primary_key_string
5898
+	 * @return null|array
5899
+	 * @throws EE_Error
5900
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5901
+	 */
5902
+	public function parse_index_primary_key_string($index_primary_key_string)
5903
+	{
5904
+		$key_fields = $this->get_combined_primary_key_fields();
5905
+		// check all of them are in the $id
5906
+		$key_vals_in_combined_pk = [];
5907
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5908
+		foreach ($key_fields as $key_field_name => $field_obj) {
5909
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5910
+				return null;
5911
+			}
5912
+		}
5913
+		return $key_vals_in_combined_pk;
5914
+	}
5915
+
5916
+
5917
+	/**
5918
+	 * verifies that an array of key-value pairs for model fields has a key
5919
+	 * for each field comprising the primary key index
5920
+	 *
5921
+	 * @param array $key_vals
5922
+	 * @return boolean
5923
+	 * @throws EE_Error
5924
+	 */
5925
+	public function has_all_combined_primary_key_fields($key_vals)
5926
+	{
5927
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5928
+		foreach ($keys_it_should_have as $key) {
5929
+			if (! isset($key_vals[ $key ])) {
5930
+				return false;
5931
+			}
5932
+		}
5933
+		return true;
5934
+	}
5935
+
5936
+
5937
+	/**
5938
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5939
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5940
+	 *
5941
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5942
+	 * @param array               $query_params                     @see
5943
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5944
+	 * @throws EE_Error
5945
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5946
+	 *                                                              indexed)
5947
+	 */
5948
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5949
+	{
5950
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5951
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5952
+		} elseif (is_array($model_object_or_attributes_array)) {
5953
+			$attributes_array = $model_object_or_attributes_array;
5954
+		} else {
5955
+			throw new EE_Error(
5956
+				sprintf(
5957
+					esc_html__(
5958
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5959
+						"event_espresso"
5960
+					),
5961
+					$model_object_or_attributes_array
5962
+				)
5963
+			);
5964
+		}
5965
+		// even copies obviously won't have the same ID, so remove the primary key
5966
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5967
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5968
+			unset($attributes_array[ $this->primary_key_name() ]);
5969
+		}
5970
+		if (isset($query_params[0])) {
5971
+			$query_params[0] = array_merge($attributes_array, $query_params);
5972
+		} else {
5973
+			$query_params[0] = $attributes_array;
5974
+		}
5975
+		return $this->get_all($query_params);
5976
+	}
5977
+
5978
+
5979
+	/**
5980
+	 * Gets the first copy we find. See get_all_copies for more details
5981
+	 *
5982
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5983
+	 * @param array $query_params
5984
+	 * @return EE_Base_Class
5985
+	 * @throws EE_Error
5986
+	 */
5987
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5988
+	{
5989
+		if (! is_array($query_params)) {
5990
+			EE_Error::doing_it_wrong(
5991
+				'EEM_Base::get_one_copy',
5992
+				sprintf(
5993
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5994
+					gettype($query_params)
5995
+				),
5996
+				'4.6.0'
5997
+			);
5998
+			$query_params = [];
5999
+		}
6000
+		$query_params['limit'] = 1;
6001
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6002
+		if (is_array($copies)) {
6003
+			return array_shift($copies);
6004
+		}
6005
+		return null;
6006
+	}
6007
+
6008
+
6009
+	/**
6010
+	 * Updates the item with the specified id. Ignores default query parameters because
6011
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6012
+	 *
6013
+	 * @param array      $fields_n_values keys are field names, values are their new values
6014
+	 * @param int|string $id              the value of the primary key to update
6015
+	 * @return int number of rows updated
6016
+	 * @throws EE_Error
6017
+	 */
6018
+	public function update_by_ID($fields_n_values, $id)
6019
+	{
6020
+		$query_params = [
6021
+			[
6022
+				$this->get_primary_key_field()->get_name() => $id
6023
+			],
6024
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6025
+		];
6026
+		return $this->update($fields_n_values, $query_params);
6027
+	}
6028
+
6029
+
6030
+	/**
6031
+	 * Changes an operator which was supplied to the models into one usable in SQL
6032
+	 *
6033
+	 * @param string $operator_supplied
6034
+	 * @return string an operator which can be used in SQL
6035
+	 * @throws EE_Error
6036
+	 */
6037
+	private function _prepare_operator_for_sql($operator_supplied)
6038
+	{
6039
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6040
+		if ($sql_operator) {
6041
+			return $sql_operator;
6042
+		}
6043
+		throw new EE_Error(
6044
+			sprintf(
6045
+				esc_html__(
6046
+					"The operator '%s' is not in the list of valid operators: %s",
6047
+					"event_espresso"
6048
+				),
6049
+				$operator_supplied,
6050
+				implode(",", array_keys($this->_valid_operators))
6051
+			)
6052
+		);
6053
+	}
6054
+
6055
+
6056
+	/**
6057
+	 * Gets the valid operators
6058
+	 *
6059
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6060
+	 */
6061
+	public function valid_operators()
6062
+	{
6063
+		return $this->_valid_operators;
6064
+	}
6065
+
6066
+
6067
+	/**
6068
+	 * Gets the between-style operators (take 2 arguments).
6069
+	 *
6070
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6071
+	 */
6072
+	public function valid_between_style_operators()
6073
+	{
6074
+		return array_intersect(
6075
+			$this->valid_operators(),
6076
+			$this->_between_style_operators
6077
+		);
6078
+	}
6079
+
6080
+
6081
+	/**
6082
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6083
+	 *
6084
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6085
+	 */
6086
+	public function valid_like_style_operators()
6087
+	{
6088
+		return array_intersect(
6089
+			$this->valid_operators(),
6090
+			$this->_like_style_operators
6091
+		);
6092
+	}
6093
+
6094
+
6095
+	/**
6096
+	 * Gets the "in"-style operators
6097
+	 *
6098
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6099
+	 */
6100
+	public function valid_in_style_operators()
6101
+	{
6102
+		return array_intersect(
6103
+			$this->valid_operators(),
6104
+			$this->_in_style_operators
6105
+		);
6106
+	}
6107
+
6108
+
6109
+	/**
6110
+	 * Gets the "null"-style operators (accept no arguments)
6111
+	 *
6112
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6113
+	 */
6114
+	public function valid_null_style_operators()
6115
+	{
6116
+		return array_intersect(
6117
+			$this->valid_operators(),
6118
+			$this->_null_style_operators
6119
+		);
6120
+	}
6121
+
6122
+
6123
+	/**
6124
+	 * Gets an array where keys are the primary keys and values are their 'names'
6125
+	 * (as determined by the model object's name() function, which is often overridden)
6126
+	 *
6127
+	 * @param array $query_params like get_all's
6128
+	 * @return string[]
6129
+	 * @throws EE_Error
6130
+	 */
6131
+	public function get_all_names($query_params = [])
6132
+	{
6133
+		$objs  = $this->get_all($query_params);
6134
+		$names = [];
6135
+		foreach ($objs as $obj) {
6136
+			$names[ $obj->ID() ] = $obj->name();
6137
+		}
6138
+		return $names;
6139
+	}
6140
+
6141
+
6142
+	/**
6143
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6144
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6145
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6146
+	 * array_keys() on $model_objects.
6147
+	 *
6148
+	 * @param \EE_Base_Class[] $model_objects
6149
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6150
+	 *                                               in the returned array
6151
+	 * @return array
6152
+	 * @throws EE_Error
6153
+	 */
6154
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6155
+	{
6156
+		if (! $this->has_primary_key_field()) {
6157
+			if (WP_DEBUG) {
6158
+				EE_Error::add_error(
6159
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6160
+					__FILE__,
6161
+					__FUNCTION__,
6162
+					__LINE__
6163
+				);
6164
+			}
6165
+		}
6166
+		$IDs = [];
6167
+		foreach ($model_objects as $model_object) {
6168
+			$id = $model_object->ID();
6169
+			if (! $id) {
6170
+				if ($filter_out_empty_ids) {
6171
+					continue;
6172
+				}
6173
+				if (WP_DEBUG) {
6174
+					EE_Error::add_error(
6175
+						esc_html__(
6176
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6177
+							'event_espresso'
6178
+						),
6179
+						__FILE__,
6180
+						__FUNCTION__,
6181
+						__LINE__
6182
+					);
6183
+				}
6184
+			}
6185
+			$IDs[] = $id;
6186
+		}
6187
+		return $IDs;
6188
+	}
6189
+
6190
+
6191
+	/**
6192
+	 * Returns the string used in capabilities relating to this model. If there
6193
+	 * are no capabilities that relate to this model returns false
6194
+	 *
6195
+	 * @return string|false
6196
+	 */
6197
+	public function cap_slug()
6198
+	{
6199
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6200
+	}
6201
+
6202
+
6203
+	/**
6204
+	 * Returns the capability-restrictions array (@param string $context
6205
+	 *
6206
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6207
+	 * @throws EE_Error
6208
+	 * @see EEM_Base::_cap_restrictions).
6209
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6210
+	 *      only returns the cap restrictions array in that context (ie, the array
6211
+	 *      at that key)
6212
+	 *
6213
+	 */
6214
+	public function cap_restrictions($context = EEM_Base::caps_read)
6215
+	{
6216
+		EEM_Base::verify_is_valid_cap_context($context);
6217
+		// check if we ought to run the restriction generator first
6218
+		if (
6219
+			isset($this->_cap_restriction_generators[ $context ])
6220
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6221
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6222
+		) {
6223
+			$this->_cap_restrictions[ $context ] = array_merge(
6224
+				$this->_cap_restrictions[ $context ],
6225
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6226
+			);
6227
+		}
6228
+		// and make sure we've finalized the construction of each restriction
6229
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6230
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6231
+				$where_conditions_obj->_finalize_construct($this);
6232
+			}
6233
+		}
6234
+		return $this->_cap_restrictions[ $context ];
6235
+	}
6236
+
6237
+
6238
+	/**
6239
+	 * Indicating whether or not this model thinks its a wp core model
6240
+	 *
6241
+	 * @return boolean
6242
+	 */
6243
+	public function is_wp_core_model()
6244
+	{
6245
+		return $this->_wp_core_model;
6246
+	}
6247
+
6248
+
6249
+	/**
6250
+	 * Gets all the caps that are missing which impose a restriction on
6251
+	 * queries made in this context
6252
+	 *
6253
+	 * @param string $context one of EEM_Base::caps_ constants
6254
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6255
+	 * @throws EE_Error
6256
+	 */
6257
+	public function caps_missing($context = EEM_Base::caps_read)
6258
+	{
6259
+		$missing_caps     = [];
6260
+		$cap_restrictions = $this->cap_restrictions($context);
6261
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6262
+			if (
6263
+				! EE_Capabilities::instance()
6264
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6265
+			) {
6266
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6267
+			}
6268
+		}
6269
+		return $missing_caps;
6270
+	}
6271
+
6272
+
6273
+	/**
6274
+	 * Gets the mapping from capability contexts to action strings used in capability names
6275
+	 *
6276
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6277
+	 * one of 'read', 'edit', or 'delete'
6278
+	 */
6279
+	public function cap_contexts_to_cap_action_map()
6280
+	{
6281
+		return apply_filters(
6282
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6283
+			$this->_cap_contexts_to_cap_action_map,
6284
+			$this
6285
+		);
6286
+	}
6287
+
6288
+
6289
+	/**
6290
+	 * Gets the action string for the specified capability context
6291
+	 *
6292
+	 * @param string $context
6293
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6294
+	 * @throws EE_Error
6295
+	 */
6296
+	public function cap_action_for_context($context)
6297
+	{
6298
+		$mapping = $this->cap_contexts_to_cap_action_map();
6299
+		if (isset($mapping[ $context ])) {
6300
+			return $mapping[ $context ];
6301
+		}
6302
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6303
+			return $action;
6304
+		}
6305
+		throw new EE_Error(
6306
+			sprintf(
6307
+				esc_html__(
6308
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6309
+					'event_espresso'
6310
+				),
6311
+				$context,
6312
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6313
+			)
6314
+		);
6315
+	}
6316
+
6317
+
6318
+	/**
6319
+	 * Returns all the capability contexts which are valid when querying models
6320
+	 *
6321
+	 * @return array
6322
+	 */
6323
+	public static function valid_cap_contexts()
6324
+	{
6325
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', [
6326
+			self::caps_read,
6327
+			self::caps_read_admin,
6328
+			self::caps_edit,
6329
+			self::caps_delete,
6330
+		]);
6331
+	}
6332
+
6333
+
6334
+	/**
6335
+	 * Returns all valid options for 'default_where_conditions'
6336
+	 *
6337
+	 * @return array
6338
+	 */
6339
+	public static function valid_default_where_conditions()
6340
+	{
6341
+		return [
6342
+			EEM_Base::default_where_conditions_all,
6343
+			EEM_Base::default_where_conditions_this_only,
6344
+			EEM_Base::default_where_conditions_others_only,
6345
+			EEM_Base::default_where_conditions_minimum_all,
6346
+			EEM_Base::default_where_conditions_minimum_others,
6347
+			EEM_Base::default_where_conditions_none,
6348
+		];
6349
+	}
6350
+
6351
+	// public static function default_where_conditions_full
6352
+
6353
+
6354
+	/**
6355
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6356
+	 *
6357
+	 * @param string $context
6358
+	 * @return bool
6359
+	 * @throws EE_Error
6360
+	 */
6361
+	public static function verify_is_valid_cap_context($context)
6362
+	{
6363
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6364
+		if (in_array($context, $valid_cap_contexts)) {
6365
+			return true;
6366
+		}
6367
+		throw new EE_Error(
6368
+			sprintf(
6369
+				esc_html__(
6370
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6371
+					'event_espresso'
6372
+				),
6373
+				$context,
6374
+				'EEM_Base',
6375
+				implode(',', $valid_cap_contexts)
6376
+			)
6377
+		);
6378
+	}
6379
+
6380
+
6381
+	/**
6382
+	 * Clears all the models field caches. This is only useful when a sub-class
6383
+	 * might have added a field or something and these caches might be invalidated
6384
+	 */
6385
+	protected function _invalidate_field_caches()
6386
+	{
6387
+		$this->_cache_foreign_key_to_fields = [];
6388
+		$this->_cached_fields               = null;
6389
+		$this->_cached_fields_non_db_only   = null;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6395
+	 * (eg "and", "or", "not").
6396
+	 *
6397
+	 * @return array
6398
+	 */
6399
+	public function logic_query_param_keys()
6400
+	{
6401
+		return $this->_logic_query_param_keys;
6402
+	}
6403
+
6404
+
6405
+	/**
6406
+	 * Determines whether or not the where query param array key is for a logic query param.
6407
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6408
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6409
+	 *
6410
+	 * @param $query_param_key
6411
+	 * @return bool
6412
+	 */
6413
+	public function is_logic_query_param_key($query_param_key)
6414
+	{
6415
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6416
+			if (
6417
+				$query_param_key === $logic_query_param_key
6418
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6419
+			) {
6420
+				return true;
6421
+			}
6422
+		}
6423
+		return false;
6424
+	}
6425
+
6426
+
6427
+	/**
6428
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6429
+	 *
6430
+	 * @return boolean
6431
+	 * @since 4.9.74.p
6432
+	 */
6433
+	public function hasPassword()
6434
+	{
6435
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6436
+		if ($this->has_password_field === null) {
6437
+			$password_field           = $this->getPasswordField();
6438
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6439
+		}
6440
+		return $this->has_password_field;
6441
+	}
6442
+
6443
+
6444
+	/**
6445
+	 * Returns the password field on this model, if there is one
6446
+	 *
6447
+	 * @return EE_Password_Field|null
6448
+	 * @since 4.9.74.p
6449
+	 */
6450
+	public function getPasswordField()
6451
+	{
6452
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6453
+		// there's no need to search for it. If we don't know yet, then find out
6454
+		if ($this->has_password_field === null && $this->password_field === null) {
6455
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6456
+		}
6457
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6458
+		return $this->password_field;
6459
+	}
6460
+
6461
+
6462
+	/**
6463
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6464
+	 *
6465
+	 * @return EE_Model_Field_Base[]
6466
+	 * @throws EE_Error
6467
+	 * @since 4.9.74.p
6468
+	 */
6469
+	public function getPasswordProtectedFields()
6470
+	{
6471
+		$password_field = $this->getPasswordField();
6472
+		$fields         = [];
6473
+		if ($password_field instanceof EE_Password_Field) {
6474
+			$field_names = $password_field->protectedFields();
6475
+			foreach ($field_names as $field_name) {
6476
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6477
+			}
6478
+		}
6479
+		return $fields;
6480
+	}
6481
+
6482
+
6483
+	/**
6484
+	 * Checks if the current user can perform the requested action on this model
6485
+	 *
6486
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6487
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6488
+	 * @return bool
6489
+	 * @throws EE_Error
6490
+	 * @throws InvalidArgumentException
6491
+	 * @throws InvalidDataTypeException
6492
+	 * @throws InvalidInterfaceException
6493
+	 * @throws ReflectionException
6494
+	 * @throws UnexpectedEntityException
6495
+	 * @since 4.9.74.p
6496
+	 */
6497
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6498
+	{
6499
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6500
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6501
+		}
6502
+		if (! is_array($model_obj_or_fields_n_values)) {
6503
+			throw new UnexpectedEntityException(
6504
+				$model_obj_or_fields_n_values,
6505
+				'EE_Base_Class',
6506
+				sprintf(
6507
+					esc_html__(
6508
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6509
+						'event_espresso'
6510
+					),
6511
+					__FUNCTION__
6512
+				)
6513
+			);
6514
+		}
6515
+		return $this->exists(
6516
+			$this->alter_query_params_to_restrict_by_ID(
6517
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6518
+				[
6519
+					'default_where_conditions' => 'none',
6520
+					'caps'                     => $cap_to_check,
6521
+				]
6522
+			)
6523
+		);
6524
+	}
6525
+
6526
+
6527
+	/**
6528
+	 * Returns the query param where conditions key to the password affecting this model.
6529
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6530
+	 *
6531
+	 * @return null|string
6532
+	 * @throws EE_Error
6533
+	 * @throws InvalidArgumentException
6534
+	 * @throws InvalidDataTypeException
6535
+	 * @throws InvalidInterfaceException
6536
+	 * @throws ModelConfigurationException
6537
+	 * @throws ReflectionException
6538
+	 * @since 4.9.74.p
6539
+	 */
6540
+	public function modelChainAndPassword()
6541
+	{
6542
+		if ($this->model_chain_to_password === null) {
6543
+			throw new ModelConfigurationException(
6544
+				$this,
6545
+				esc_html_x(
6546
+				// @codingStandardsIgnoreStart
6547
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6548
+					// @codingStandardsIgnoreEnd
6549
+					'1: model name',
6550
+					'event_espresso'
6551
+				)
6552
+			);
6553
+		}
6554
+		if ($this->model_chain_to_password === '') {
6555
+			$model_with_password = $this;
6556
+		} else {
6557
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6558
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6559
+			} else {
6560
+				$last_model_in_chain = $this->model_chain_to_password;
6561
+			}
6562
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6563
+		}
6564
+
6565
+		$password_field = $model_with_password->getPasswordField();
6566
+		if ($password_field instanceof EE_Password_Field) {
6567
+			$password_field_name = $password_field->get_name();
6568
+		} else {
6569
+			throw new ModelConfigurationException(
6570
+				$this,
6571
+				sprintf(
6572
+					esc_html_x(
6573
+						'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"',
6574
+						'1: model name, 2: special string',
6575
+						'event_espresso'
6576
+					),
6577
+					$model_with_password->get_this_model_name(),
6578
+					$this->model_chain_to_password
6579
+				)
6580
+			);
6581
+		}
6582
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6583
+	}
6584
+
6585
+
6586
+	/**
6587
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6588
+	 * or if this model itself has a password affecting access to some of its other fields.
6589
+	 *
6590
+	 * @return boolean
6591
+	 * @since 4.9.74.p
6592
+	 */
6593
+	public function restrictedByRelatedModelPassword()
6594
+	{
6595
+		return $this->model_chain_to_password !== null;
6596
+	}
6597 6597
 }
Please login to merge, or discard this patch.
Spacing   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
     protected function __construct($timezone = null)
565 565
     {
566 566
         // check that the model has not been loaded too soon
567
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
567
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
568 568
             throw new EE_Error(
569 569
                 sprintf(
570 570
                     esc_html__(
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
          *
588 588
          * @var EE_Table_Base[] $_tables
589 589
          */
590
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
590
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
591 591
         foreach ($this->_tables as $table_alias => $table_obj) {
592 592
             /** @var $table_obj EE_Table_Base */
593 593
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -602,10 +602,10 @@  discard block
 block discarded – undo
602 602
          *
603 603
          * @param EE_Model_Field_Base[] $_fields
604 604
          */
605
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
605
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
606 606
         $this->_invalidate_field_caches();
607 607
         foreach ($this->_fields as $table_alias => $fields_for_table) {
608
-            if (! array_key_exists($table_alias, $this->_tables)) {
608
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
609 609
                 throw new EE_Error(
610 610
                     sprintf(
611 611
                         esc_html__(
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
          * @param EE_Model_Relation_Base[] $_model_relations
643 643
          */
644 644
         $this->_model_relations = (array) apply_filters(
645
-            'FHEE__' . get_class($this) . '__construct__model_relations',
645
+            'FHEE__'.get_class($this).'__construct__model_relations',
646 646
             $this->_model_relations
647 647
         );
648 648
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -654,12 +654,12 @@  discard block
 block discarded – undo
654 654
         }
655 655
         $this->set_timezone($timezone);
656 656
         // finalize default where condition strategy, or set default
657
-        if (! $this->_default_where_conditions_strategy) {
657
+        if ( ! $this->_default_where_conditions_strategy) {
658 658
             // nothing was set during child constructor, so set default
659 659
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
660 660
         }
661 661
         $this->_default_where_conditions_strategy->_finalize_construct($this);
662
-        if (! $this->_minimum_where_conditions_strategy) {
662
+        if ( ! $this->_minimum_where_conditions_strategy) {
663 663
             // nothing was set during child constructor, so set default
664 664
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
665 665
         }
@@ -672,8 +672,8 @@  discard block
 block discarded – undo
672 672
         // initialize the standard cap restriction generators if none were specified by the child constructor
673 673
         if (is_array($this->_cap_restriction_generators)) {
674 674
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
675
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
676
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
675
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
676
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
677 677
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
678 678
                         new EE_Restriction_Generator_Protected(),
679 679
                         $cap_context,
@@ -685,10 +685,10 @@  discard block
 block discarded – undo
685 685
         // if there are cap restriction generators, use them to make the default cap restrictions
686 686
         if (is_array($this->_cap_restriction_generators)) {
687 687
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
688
-                if (! $generator_object) {
688
+                if ( ! $generator_object) {
689 689
                     continue;
690 690
                 }
691
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
691
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
692 692
                     throw new EE_Error(
693 693
                         sprintf(
694 694
                             esc_html__(
@@ -701,12 +701,12 @@  discard block
 block discarded – undo
701 701
                     );
702 702
                 }
703 703
                 $action = $this->cap_action_for_context($context);
704
-                if (! $generator_object->construction_finalized()) {
704
+                if ( ! $generator_object->construction_finalized()) {
705 705
                     $generator_object->_construct_finalize($this, $action);
706 706
                 }
707 707
             }
708 708
         }
709
-        do_action('AHEE__' . get_class($this) . '__construct__end');
709
+        do_action('AHEE__'.get_class($this).'__construct__end');
710 710
     }
711 711
 
712 712
 
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
      */
719 719
     protected static function getLoader(): LoaderInterface
720 720
     {
721
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
721
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
722 722
             EEM_Base::$loader = LoaderFactory::getLoader();
723 723
         }
724 724
         return EEM_Base::$loader;
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
      */
732 732
     private static function getMirror(): Mirror
733 733
     {
734
-        if (! EEM_Base::$mirror instanceof Mirror) {
734
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
735 735
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
736 736
         }
737 737
         return EEM_Base::$mirror;
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
     public static function instance($timezone = null)
788 788
     {
789 789
         // check if instance of Espresso_model already exists
790
-        if (! static::$_instance instanceof static) {
790
+        if ( ! static::$_instance instanceof static) {
791 791
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
792 792
             $model     = new static(...$arguments);
793 793
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
      */
817 817
     public static function reset($timezone = null)
818 818
     {
819
-        if (! static::$_instance instanceof EEM_Base) {
819
+        if ( ! static::$_instance instanceof EEM_Base) {
820 820
             return null;
821 821
         }
822 822
         // Let's NOT swap out the current instance for a new one
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
828 828
             // don't set instance to null like it was originally,
829 829
             // but it's static anyways, and we're ignoring static properties (for now at least)
830
-            if (! isset($static_properties[ $property ])) {
830
+            if ( ! isset($static_properties[$property])) {
831 831
                 static::$_instance->{$property} = $value;
832 832
             }
833 833
         }
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
      */
876 876
     public function status_array($translated = false)
877 877
     {
878
-        if (! array_key_exists('Status', $this->_model_relations)) {
878
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
879 879
             return [];
880 880
         }
881 881
         $model_name   = $this->get_this_model_name();
@@ -883,7 +883,7 @@  discard block
 block discarded – undo
883 883
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
884 884
         $status_array = [];
885 885
         foreach ($stati as $status) {
886
-            $status_array[ $status->ID() ] = $status->get('STS_code');
886
+            $status_array[$status->ID()] = $status->get('STS_code');
887 887
         }
888 888
         return $translated
889 889
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
     {
946 946
         $wp_user_field_name = $this->wp_user_field_name();
947 947
         if ($wp_user_field_name) {
948
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
948
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
949 949
         }
950 950
         return $query_params;
951 951
     }
@@ -962,17 +962,17 @@  discard block
 block discarded – undo
962 962
     public function wp_user_field_name()
963 963
     {
964 964
         try {
965
-            if (! empty($this->_model_chain_to_wp_user)) {
965
+            if ( ! empty($this->_model_chain_to_wp_user)) {
966 966
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
967 967
                 $last_model_name              = end($models_to_follow_to_wp_users);
968 968
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
969
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
969
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
970 970
             } else {
971 971
                 $model_with_fk_to_wp_users = $this;
972 972
                 $model_chain_to_wp_user    = '';
973 973
             }
974 974
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
975
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
975
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
976 976
         } catch (EE_Error $e) {
977 977
             return false;
978 978
         }
@@ -1047,11 +1047,11 @@  discard block
 block discarded – undo
1047 1047
         if ($this->_custom_selections instanceof CustomSelects) {
1048 1048
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1049 1049
             $select_expressions .= $select_expressions
1050
-                ? ', ' . $custom_expressions
1050
+                ? ', '.$custom_expressions
1051 1051
                 : $custom_expressions;
1052 1052
         }
1053 1053
 
1054
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1054
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1055 1055
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1056 1056
     }
1057 1057
 
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
      */
1069 1069
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1070 1070
     {
1071
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1072 1072
             return null;
1073 1073
         }
1074 1074
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1116,7 +1116,7 @@  discard block
 block discarded – undo
1116 1116
         if (is_array($columns_to_select)) {
1117 1117
             $select_sql_array = [];
1118 1118
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120 1120
                     throw new EE_Error(
1121 1121
                         sprintf(
1122 1122
                             esc_html__(
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
                         )
1129 1129
                     );
1130 1130
                 }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132 1132
                     throw new EE_Error(
1133 1133
                         sprintf(
1134 1134
                             esc_html__(
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
                 ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1184 1184
             )
1185 1185
         );
1186
-        $className    = $this->_get_class_name();
1186
+        $className = $this->_get_class_name();
1187 1187
         if ($model_object instanceof $className) {
1188 1188
             // make sure valid objects get added to the entity map
1189 1189
             // so that the next call to this method doesn't trigger another trip to the db
@@ -1206,12 +1206,12 @@  discard block
 block discarded – undo
1206 1206
      */
1207 1207
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1208 1208
     {
1209
-        if (! isset($query_params[0])) {
1209
+        if ( ! isset($query_params[0])) {
1210 1210
             $query_params[0] = [];
1211 1211
         }
1212 1212
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1213 1213
         if ($conditions_from_id === null) {
1214
-            $query_params[0][ $this->primary_key_name() ] = $id;
1214
+            $query_params[0][$this->primary_key_name()] = $id;
1215 1215
         } else {
1216 1216
             // no primary key, so the $id must be from the get_index_primary_key_string()
1217 1217
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1230,7 +1230,7 @@  discard block
 block discarded – undo
1230 1230
      */
1231 1231
     public function get_one($query_params = [])
1232 1232
     {
1233
-        if (! is_array($query_params)) {
1233
+        if ( ! is_array($query_params)) {
1234 1234
             EE_Error::doing_it_wrong(
1235 1235
                 'EEM_Base::get_one',
1236 1236
                 sprintf(
@@ -1425,7 +1425,7 @@  discard block
 block discarded – undo
1425 1425
                 return [];
1426 1426
             }
1427 1427
         }
1428
-        if (! is_array($query_params)) {
1428
+        if ( ! is_array($query_params)) {
1429 1429
             EE_Error::doing_it_wrong(
1430 1430
                 'EEM_Base::_get_consecutive',
1431 1431
                 sprintf(
@@ -1437,7 +1437,7 @@  discard block
 block discarded – undo
1437 1437
             $query_params = [];
1438 1438
         }
1439 1439
         // let's add the where query param for consecutive look up.
1440
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1440
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1441 1441
         $query_params['limit']                 = $limit;
1442 1442
         // set direction
1443 1443
         $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
     {
1516 1516
         $field_settings = $this->field_settings_for($field_name);
1517 1517
         // if not a valid EE_Datetime_Field then throw error
1518
-        if (! $field_settings instanceof EE_Datetime_Field) {
1518
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1519 1519
             throw new EE_Error(
1520 1520
                 sprintf(
1521 1521
                     esc_html__(
@@ -1667,7 +1667,7 @@  discard block
 block discarded – undo
1667 1667
      */
1668 1668
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1669 1669
     {
1670
-        if (! is_array($query_params)) {
1670
+        if ( ! is_array($query_params)) {
1671 1671
             EE_Error::doing_it_wrong(
1672 1672
                 'EEM_Base::update',
1673 1673
                 sprintf(
@@ -1715,7 +1715,7 @@  discard block
 block discarded – undo
1715 1715
             $wpdb_result = (array) $wpdb_result;
1716 1716
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1717 1717
             if ($this->has_primary_key_field()) {
1718
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1718
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1719 1719
             } else {
1720 1720
                 // 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)
1721 1721
                 $main_table_pk_value = null;
@@ -1731,7 +1731,7 @@  discard block
 block discarded – undo
1731 1731
                     // in this table, right? so insert a row in the current table, using any fields available
1732 1732
                     if (
1733 1733
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1734
-                           && $wpdb_result[ $this_table_pk_column ])
1734
+                           && $wpdb_result[$this_table_pk_column])
1735 1735
                     ) {
1736 1736
                         $success = $this->_insert_into_specific_table(
1737 1737
                             $table_obj,
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
                             $main_table_pk_value
1740 1740
                         );
1741 1741
                         // if we died here, report the error
1742
-                        if (! $success) {
1742
+                        if ( ! $success) {
1743 1743
                             return false;
1744 1744
                         }
1745 1745
                     }
@@ -1767,10 +1767,10 @@  discard block
 block discarded – undo
1767 1767
                 $model_objs_affected_ids     = [];
1768 1768
                 foreach ($models_affected_key_columns as $row) {
1769 1769
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1770
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1770
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1771 1771
                 }
1772 1772
             }
1773
-            if (! $model_objs_affected_ids) {
1773
+            if ( ! $model_objs_affected_ids) {
1774 1774
                 // wait wait wait- if nothing was affected let's stop here
1775 1775
                 return 0;
1776 1776
             }
@@ -1798,7 +1798,7 @@  discard block
 block discarded – undo
1798 1798
                 SET {$this->_construct_update_sql($fields_n_values)}
1799 1799
                 {$model_query_info->get_where_sql()}";
1800 1800
         // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1801
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1801
+        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1802 1802
         /**
1803 1803
          * Action called after a model update call has been made.
1804 1804
          *
@@ -1808,7 +1808,7 @@  discard block
 block discarded – undo
1808 1808
          * @param int      $rows_affected
1809 1809
          */
1810 1810
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1811
-        return $rows_affected;// how many supposedly got updated
1811
+        return $rows_affected; // how many supposedly got updated
1812 1812
     }
1813 1813
 
1814 1814
 
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1839 1839
         $select_expressions = $field->get_qualified_column();
1840 1840
         $SQL                =
1841
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1841
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1842 1842
         return $this->_do_wpdb_query('get_col', [$SQL]);
1843 1843
     }
1844 1844
 
@@ -1856,7 +1856,7 @@  discard block
 block discarded – undo
1856 1856
     {
1857 1857
         $query_params['limit'] = 1;
1858 1858
         $col                   = $this->get_col($query_params, $field_to_select);
1859
-        if (! empty($col)) {
1859
+        if ( ! empty($col)) {
1860 1860
             return reset($col);
1861 1861
         }
1862 1862
         return null;
@@ -1886,7 +1886,7 @@  discard block
 block discarded – undo
1886 1886
             $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1887 1887
             $value_sql       = $prepared_value === null ? 'NULL'
1888 1888
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1889
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1889
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1890 1890
         }
1891 1891
         return implode(",", $cols_n_values);
1892 1892
     }
@@ -2017,7 +2017,7 @@  discard block
 block discarded – undo
2017 2017
                                 . $model_query_info->get_full_join_sql()
2018 2018
                                 . " WHERE "
2019 2019
                                 . $deletion_where_query_part;
2020
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2020
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
2021 2021
         } else {
2022 2022
             $rows_deleted = 0;
2023 2023
         }
@@ -2027,12 +2027,12 @@  discard block
 block discarded – undo
2027 2027
         if (
2028 2028
             $this->has_primary_key_field()
2029 2029
             && $rows_deleted !== false
2030
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2030
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2031 2031
         ) {
2032
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2032
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2033 2033
             foreach ($ids_for_removal as $id) {
2034
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2035
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2034
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2035
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2036 2036
                 }
2037 2037
             }
2038 2038
 
@@ -2069,7 +2069,7 @@  discard block
 block discarded – undo
2069 2069
          * @param int      $rows_deleted
2070 2070
          */
2071 2071
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2072
-        return $rows_deleted;// how many supposedly got deleted
2072
+        return $rows_deleted; // how many supposedly got deleted
2073 2073
     }
2074 2074
 
2075 2075
 
@@ -2163,15 +2163,15 @@  discard block
 block discarded – undo
2163 2163
                 if (
2164 2164
                     $allow_blocking
2165 2165
                     && $this->delete_is_blocked_by_related_models(
2166
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2166
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2167 2167
                     )
2168 2168
                 ) {
2169 2169
                     continue;
2170 2170
                 }
2171 2171
                 // primary table deletes
2172
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2173
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2174
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2172
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2173
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2174
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2175 2175
                 }
2176 2176
             }
2177 2177
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2180,8 +2180,8 @@  discard block
 block discarded – undo
2180 2180
                 $ids_to_delete_indexed_by_column_for_row = [];
2181 2181
                 foreach ($fields as $cpk_field) {
2182 2182
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2183
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2184
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2183
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2184
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2185 2185
                     }
2186 2186
                 }
2187 2187
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2219,7 +2219,7 @@  discard block
 block discarded – undo
2219 2219
         } elseif ($this->has_primary_key_field()) {
2220 2220
             $query = [];
2221 2221
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2222
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2222
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2223 2223
             }
2224 2224
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2225 2225
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2227,7 +2227,7 @@  discard block
 block discarded – undo
2227 2227
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2228 2228
                 $values_for_each_combined_primary_key_for_a_row = [];
2229 2229
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2230
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2230
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2231 2231
                 }
2232 2232
                 $ways_to_identify_a_row[] = '('
2233 2233
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2299,9 +2299,9 @@  discard block
 block discarded – undo
2299 2299
                 $column_to_count = '*';
2300 2300
             }
2301 2301
         }
2302
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2302
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2303 2303
         $SQL             =
2304
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2304
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2305 2305
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2306 2306
     }
2307 2307
 
@@ -2325,7 +2325,7 @@  discard block
 block discarded – undo
2325 2325
         }
2326 2326
         $column_to_count = $field_obj->get_qualified_column();
2327 2327
         $SQL             =
2328
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2328
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2329 2329
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2330 2330
         $data_type       = $field_obj->get_wpdb_data_type();
2331 2331
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2351,7 +2351,7 @@  discard block
 block discarded – undo
2351 2351
         // if we're in maintenance mode level 2, DON'T run any queries
2352 2352
         // because level 2 indicates the database needs updating and
2353 2353
         // is probably out of sync with the code
2354
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2354
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2355 2355
             throw new EE_Error(
2356 2356
                 sprintf(
2357 2357
                     esc_html__(
@@ -2363,7 +2363,7 @@  discard block
 block discarded – undo
2363 2363
         }
2364 2364
         /** @type WPDB $wpdb */
2365 2365
         global $wpdb;
2366
-        if (! method_exists($wpdb, $wpdb_method)) {
2366
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2367 2367
             throw new EE_Error(
2368 2368
                 sprintf(
2369 2369
                     esc_html__(
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2383 2383
         if (WP_DEBUG) {
2384 2384
             $wpdb->show_errors($old_show_errors_value);
2385
-            if (! empty($wpdb->last_error)) {
2385
+            if ( ! empty($wpdb->last_error)) {
2386 2386
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2387 2387
             }
2388 2388
             if ($result === false) {
@@ -2453,7 +2453,7 @@  discard block
 block discarded – undo
2453 2453
                     return $result;
2454 2454
                     break;
2455 2455
             }
2456
-            if (! empty($error_message)) {
2456
+            if ( ! empty($error_message)) {
2457 2457
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2458 2458
                 trigger_error($error_message);
2459 2459
             }
@@ -2530,11 +2530,11 @@  discard block
 block discarded – undo
2530 2530
      */
2531 2531
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2532 2532
     {
2533
-        return " FROM " . $model_query_info->get_full_join_sql() .
2534
-               $model_query_info->get_where_sql() .
2535
-               $model_query_info->get_group_by_sql() .
2536
-               $model_query_info->get_having_sql() .
2537
-               $model_query_info->get_order_by_sql() .
2533
+        return " FROM ".$model_query_info->get_full_join_sql().
2534
+               $model_query_info->get_where_sql().
2535
+               $model_query_info->get_group_by_sql().
2536
+               $model_query_info->get_having_sql().
2537
+               $model_query_info->get_order_by_sql().
2538 2538
                $model_query_info->get_limit_sql();
2539 2539
     }
2540 2540
 
@@ -2723,12 +2723,12 @@  discard block
 block discarded – undo
2723 2723
         $related_model = $this->get_related_model_obj($model_name);
2724 2724
         // we're just going to use the query params on the related model's normal get_all query,
2725 2725
         // except add a condition to say to match the current mod
2726
-        if (! isset($query_params['default_where_conditions'])) {
2726
+        if ( ! isset($query_params['default_where_conditions'])) {
2727 2727
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2728 2728
         }
2729 2729
         $this_model_name                                                 = $this->get_this_model_name();
2730 2730
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2731
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2731
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2732 2732
         return $related_model->count($query_params, $field_to_count, $distinct);
2733 2733
     }
2734 2734
 
@@ -2748,7 +2748,7 @@  discard block
 block discarded – undo
2748 2748
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2749 2749
     {
2750 2750
         $related_model = $this->get_related_model_obj($model_name);
2751
-        if (! is_array($query_params)) {
2751
+        if ( ! is_array($query_params)) {
2752 2752
             EE_Error::doing_it_wrong(
2753 2753
                 'EEM_Base::sum_related',
2754 2754
                 sprintf(
@@ -2761,12 +2761,12 @@  discard block
 block discarded – undo
2761 2761
         }
2762 2762
         // we're just going to use the query params on the related model's normal get_all query,
2763 2763
         // except add a condition to say to match the current mod
2764
-        if (! isset($query_params['default_where_conditions'])) {
2764
+        if ( ! isset($query_params['default_where_conditions'])) {
2765 2765
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2766 2766
         }
2767 2767
         $this_model_name                                                 = $this->get_this_model_name();
2768 2768
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2769
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2769
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2770 2770
         return $related_model->sum($query_params, $field_to_sum);
2771 2771
     }
2772 2772
 
@@ -2817,7 +2817,7 @@  discard block
 block discarded – undo
2817 2817
                 $field_with_model_name = $field;
2818 2818
             }
2819 2819
         }
2820
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2820
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2821 2821
             throw new EE_Error(
2822 2822
                 sprintf(
2823 2823
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2953,14 +2953,14 @@  discard block
 block discarded – undo
2953 2953
                 || $this->get_primary_key_field()
2954 2954
                    instanceof
2955 2955
                    EE_Primary_Key_String_Field)
2956
-            && isset($fields_n_values[ $this->primary_key_name() ])
2956
+            && isset($fields_n_values[$this->primary_key_name()])
2957 2957
         ) {
2958
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2958
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2959 2959
         }
2960 2960
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2961 2961
             $uniqueness_where_params                              =
2962 2962
                 array_intersect_key($fields_n_values, $unique_index->fields());
2963
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2963
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2964 2964
         }
2965 2965
         // if there is nothing to base this search on, then we shouldn't find anything
2966 2966
         if (empty($query_params)) {
@@ -3035,16 +3035,16 @@  discard block
 block discarded – undo
3035 3035
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3036 3036
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3037 3037
             if ($prepared_value !== null) {
3038
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3038
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3039 3039
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3040 3040
             }
3041 3041
         }
3042 3042
         if ($table instanceof EE_Secondary_Table && $new_id) {
3043 3043
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3044 3044
             // so add the fk to the main table as a column
3045
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3045
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3046 3046
             $format_for_insertion[]                              =
3047
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3047
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3048 3048
         }
3049 3049
 
3050 3050
         // insert the new entry
@@ -3062,7 +3062,7 @@  discard block
 block discarded – undo
3062 3062
             }
3063 3063
             // it's not an auto-increment primary key, so
3064 3064
             // it must have been supplied
3065
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3065
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3066 3066
         }
3067 3067
         // we can't return a  primary key because there is none. instead return
3068 3068
         // a unique string indicating this model
@@ -3084,10 +3084,10 @@  discard block
 block discarded – undo
3084 3084
     {
3085 3085
         $field_name = $field_obj->get_name();
3086 3086
         // if this field doesn't allow nullable, don't allow it
3087
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3088
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3087
+        if ( ! $field_obj->is_nullable() && ! isset($fields_n_values[$field_name])) {
3088
+            $fields_n_values[$field_name] = $field_obj->get_default_value();
3089 3089
         }
3090
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3090
+        $unprepared_value = $fields_n_values[$field_name] ?? null;
3091 3091
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092 3092
     }
3093 3093
 
@@ -3188,7 +3188,7 @@  discard block
 block discarded – undo
3188 3188
      */
3189 3189
     public function get_table_obj_by_alias($table_alias = '')
3190 3190
     {
3191
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3192 3192
     }
3193 3193
 
3194 3194
 
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
         $other_tables = [];
3203 3203
         foreach ($this->_tables as $table_alias => $table) {
3204 3204
             if ($table instanceof EE_Secondary_Table) {
3205
-                $other_tables[ $table_alias ] = $table;
3205
+                $other_tables[$table_alias] = $table;
3206 3206
             }
3207 3207
         }
3208 3208
         return $other_tables;
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
      */
3218 3218
     public function _get_fields_for_table($table_alias)
3219 3219
     {
3220
-        return $this->_fields[ $table_alias ];
3220
+        return $this->_fields[$table_alias];
3221 3221
     }
3222 3222
 
3223 3223
 
@@ -3246,7 +3246,7 @@  discard block
 block discarded – undo
3246 3246
                     $query_info_carrier,
3247 3247
                     'group_by'
3248 3248
                 );
3249
-            } elseif (! empty($query_params['group_by'])) {
3249
+            } elseif ( ! empty($query_params['group_by'])) {
3250 3250
                 $this->_extract_related_model_info_from_query_param(
3251 3251
                     $query_params['group_by'],
3252 3252
                     $query_info_carrier,
@@ -3268,7 +3268,7 @@  discard block
 block discarded – undo
3268 3268
                     $query_info_carrier,
3269 3269
                     'order_by'
3270 3270
                 );
3271
-            } elseif (! empty($query_params['order_by'])) {
3271
+            } elseif ( ! empty($query_params['order_by'])) {
3272 3272
                 $this->_extract_related_model_info_from_query_param(
3273 3273
                     $query_params['order_by'],
3274 3274
                     $query_info_carrier,
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3304 3304
         $query_param_type
3305 3305
     ) {
3306
-        if (! empty($sub_query_params)) {
3306
+        if ( ! empty($sub_query_params)) {
3307 3307
             $sub_query_params = (array) $sub_query_params;
3308 3308
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3309 3309
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3319,7 +3319,7 @@  discard block
 block discarded – undo
3319 3319
                 $query_param_sans_stars =
3320 3320
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3321 3321
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3322
-                    if (! is_array($possibly_array_of_params)) {
3322
+                    if ( ! is_array($possibly_array_of_params)) {
3323 3323
                         throw new EE_Error(
3324 3324
                             sprintf(
3325 3325
                                 esc_html__(
@@ -3345,7 +3345,7 @@  discard block
 block discarded – undo
3345 3345
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3346 3346
                     // indicating that $possible_array_of_params[1] is actually a field name,
3347 3347
                     // from which we should extract query parameters!
3348
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3349 3349
                         throw new EE_Error(
3350 3350
                             sprintf(
3351 3351
                                 esc_html__(
@@ -3385,8 +3385,8 @@  discard block
 block discarded – undo
3385 3385
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3386 3386
         $query_param_type
3387 3387
     ) {
3388
-        if (! empty($sub_query_params)) {
3389
-            if (! is_array($sub_query_params)) {
3388
+        if ( ! empty($sub_query_params)) {
3389
+            if ( ! is_array($sub_query_params)) {
3390 3390
                 throw new EE_Error(
3391 3391
                     sprintf(
3392 3392
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3423,7 +3423,7 @@  discard block
 block discarded – undo
3423 3423
      */
3424 3424
     public function _create_model_query_info_carrier($query_params)
3425 3425
     {
3426
-        if (! is_array($query_params)) {
3426
+        if ( ! is_array($query_params)) {
3427 3427
             EE_Error::doing_it_wrong(
3428 3428
                 'EEM_Base::_create_model_query_info_carrier',
3429 3429
                 sprintf(
@@ -3454,7 +3454,7 @@  discard block
 block discarded – undo
3454 3454
             // only include if related to a cpt where no password has been set
3455 3455
             $query_params[0]['OR*nopassword'] = [
3456 3456
                 $where_param_key_for_password       => '',
3457
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3457
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3458 3458
             ];
3459 3459
         }
3460 3460
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3508,7 +3508,7 @@  discard block
 block discarded – undo
3508 3508
         // set limit
3509 3509
         if (array_key_exists('limit', $query_params)) {
3510 3510
             if (is_array($query_params['limit'])) {
3511
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3511
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3512 3512
                     $e = sprintf(
3513 3513
                         esc_html__(
3514 3514
                             "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)",
@@ -3516,12 +3516,12 @@  discard block
 block discarded – undo
3516 3516
                         ),
3517 3517
                         http_build_query($query_params['limit'])
3518 3518
                     );
3519
-                    throw new EE_Error($e . "|" . $e);
3519
+                    throw new EE_Error($e."|".$e);
3520 3520
                 }
3521 3521
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3522
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3523
-            } elseif (! empty($query_params['limit'])) {
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3522
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3523
+            } elseif ( ! empty($query_params['limit'])) {
3524
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3525 3525
             }
3526 3526
         }
3527 3527
         // set order by
@@ -3553,10 +3553,10 @@  discard block
 block discarded – undo
3553 3553
                 $order_array = [];
3554 3554
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3555 3555
                     $order         = $this->_extract_order($order);
3556
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3556
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3557 3557
                 }
3558
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3559
-            } elseif (! empty($query_params['order_by'])) {
3558
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3559
+            } elseif ( ! empty($query_params['order_by'])) {
3560 3560
                 $this->_extract_related_model_info_from_query_param(
3561 3561
                     $query_params['order_by'],
3562 3562
                     $query_object,
@@ -3567,7 +3567,7 @@  discard block
 block discarded – undo
3567 3567
                     ? $this->_extract_order($query_params['order'])
3568 3568
                     : 'DESC';
3569 3569
                 $query_object->set_order_by_sql(
3570
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3570
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3571 3571
                 );
3572 3572
             }
3573 3573
         }
@@ -3579,7 +3579,7 @@  discard block
 block discarded – undo
3579 3579
         ) {
3580 3580
             $pk_field = $this->get_primary_key_field();
3581 3581
             $order    = $this->_extract_order($query_params['order']);
3582
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3582
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3583 3583
         }
3584 3584
         // set group by
3585 3585
         if (array_key_exists('group_by', $query_params)) {
@@ -3589,10 +3589,10 @@  discard block
 block discarded – undo
3589 3589
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3590 3590
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3591 3591
                 }
3592
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3593
-            } elseif (! empty($query_params['group_by'])) {
3592
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3593
+            } elseif ( ! empty($query_params['group_by'])) {
3594 3594
                 $query_object->set_group_by_sql(
3595
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3595
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3596 3596
                 );
3597 3597
             }
3598 3598
         }
@@ -3602,7 +3602,7 @@  discard block
 block discarded – undo
3602 3602
         }
3603 3603
         // now, just verify they didn't pass anything wack
3604 3604
         foreach ($query_params as $query_key => $query_value) {
3605
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3605
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3606 3606
                 throw new EE_Error(
3607 3607
                     sprintf(
3608 3608
                         esc_html__(
@@ -3710,7 +3710,7 @@  discard block
 block discarded – undo
3710 3710
         $where_query_params = []
3711 3711
     ) {
3712 3712
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3713
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3713
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3714 3714
             throw new EE_Error(
3715 3715
                 sprintf(
3716 3716
                     esc_html__(
@@ -3740,7 +3740,7 @@  discard block
 block discarded – undo
3740 3740
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3741 3741
                 continue;
3742 3742
             }
3743
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3743
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3744 3744
                 $related_model_universal_where_params,
3745 3745
                 $where_query_params,
3746 3746
                 $related_model,
@@ -3849,19 +3849,19 @@  discard block
 block discarded – undo
3849 3849
     ) {
3850 3850
         $null_friendly_where_conditions = [];
3851 3851
         $none_overridden                = true;
3852
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3852
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3853 3853
         foreach ($default_where_conditions as $key => $val) {
3854
-            if (isset($provided_where_conditions[ $key ])) {
3854
+            if (isset($provided_where_conditions[$key])) {
3855 3855
                 $none_overridden = false;
3856 3856
             } else {
3857
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3858 3858
             }
3859 3859
         }
3860 3860
         if ($none_overridden && $default_where_conditions) {
3861 3861
             if ($model->has_primary_key_field()) {
3862
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3863 3863
                                                                                    . "."
3864
-                                                                                   . $model->primary_key_name() ] =
3864
+                                                                                   . $model->primary_key_name()] =
3865 3865
                     ['IS NULL'];
3866 3866
             }/*else{
3867 3867
                 //@todo NO PK, use other defaults
@@ -3968,7 +3968,7 @@  discard block
 block discarded – undo
3968 3968
             foreach ($tables as $table_obj) {
3969 3969
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970 3970
                                        . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3971
+                if ( ! in_array($qualified_pk_column, $selects)) {
3972 3972
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973 3973
                 }
3974 3974
             }
@@ -4120,9 +4120,9 @@  discard block
 block discarded – undo
4120 4120
         $query_parameter_type
4121 4121
     ) {
4122 4122
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4123
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4124 4124
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4125
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4126 4126
                 if ($possible_join_string === '') {
4127 4127
                     // nothing left to $query_param
4128 4128
                     // we should actually end in a field name, not a model like this!
@@ -4255,7 +4255,7 @@  discard block
 block discarded – undo
4255 4255
     {
4256 4256
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4257 4257
         if ($SQL) {
4258
-            return " WHERE " . $SQL;
4258
+            return " WHERE ".$SQL;
4259 4259
         }
4260 4260
         return '';
4261 4261
     }
@@ -4273,7 +4273,7 @@  discard block
 block discarded – undo
4273 4273
     {
4274 4274
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4275 4275
         if ($SQL) {
4276
-            return " HAVING " . $SQL;
4276
+            return " HAVING ".$SQL;
4277 4277
         }
4278 4278
         return '';
4279 4279
     }
@@ -4327,7 +4327,7 @@  discard block
 block discarded – undo
4327 4327
             } else {
4328 4328
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4329 4329
                 // if it's not a normal field, maybe it's a custom selection?
4330
-                if (! $field_obj) {
4330
+                if ( ! $field_obj) {
4331 4331
                     if ($this->_custom_selections instanceof CustomSelects) {
4332 4332
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4333 4333
                     } else {
@@ -4343,7 +4343,7 @@  discard block
 block discarded – undo
4343 4343
                     }
4344 4344
                 }
4345 4345
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4346
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4346
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4347 4347
             }
4348 4348
         }
4349 4349
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4365,7 +4365,7 @@  discard block
 block discarded – undo
4365 4365
                 $field->get_model_name(),
4366 4366
                 $query_param
4367 4367
             );
4368
-            return $table_alias_prefix . $field->get_qualified_column();
4368
+            return $table_alias_prefix.$field->get_qualified_column();
4369 4369
         }
4370 4370
         if (
4371 4371
             $this->_custom_selections instanceof CustomSelects
@@ -4423,7 +4423,7 @@  discard block
 block discarded – undo
4423 4423
     {
4424 4424
         if (is_array($op_and_value)) {
4425 4425
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4426
-            if (! $operator) {
4426
+            if ( ! $operator) {
4427 4427
                 $php_array_like_string = [];
4428 4428
                 foreach ($op_and_value as $key => $value) {
4429 4429
                     $php_array_like_string[] = "$key=>$value";
@@ -4445,14 +4445,14 @@  discard block
 block discarded – undo
4445 4445
         }
4446 4446
         // check to see if the value is actually another field
4447 4447
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4448
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4448
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4449 4449
         }
4450 4450
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451 4451
             // in this case, the value should be an array, or at least a comma-separated list
4452 4452
             // it will need to handle a little differently
4453 4453
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4454 4454
             // note: $cleaned_value has already been run through $wpdb->prepare()
4455
-            return $operator . SP . $cleaned_value;
4455
+            return $operator.SP.$cleaned_value;
4456 4456
         }
4457 4457
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4458 4458
             // the value should be an array with count of two.
@@ -4468,7 +4468,7 @@  discard block
 block discarded – undo
4468 4468
                 );
4469 4469
             }
4470 4470
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4471
-            return $operator . SP . $cleaned_value;
4471
+            return $operator.SP.$cleaned_value;
4472 4472
         }
4473 4473
         if (in_array($operator, $this->valid_null_style_operators())) {
4474 4474
             if ($value !== null) {
@@ -4488,10 +4488,10 @@  discard block
 block discarded – undo
4488 4488
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4489 4489
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4490 4490
             // remove other junk. So just treat it as a string.
4491
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4491
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4492 4492
         }
4493
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4494
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4493
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4494
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4495 4495
         }
4496 4496
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4497 4497
             throw new EE_Error(
@@ -4505,7 +4505,7 @@  discard block
 block discarded – undo
4505 4505
                 )
4506 4506
             );
4507 4507
         }
4508
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4508
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4509 4509
             throw new EE_Error(
4510 4510
                 sprintf(
4511 4511
                     esc_html__(
@@ -4544,7 +4544,7 @@  discard block
 block discarded – undo
4544 4544
         foreach ($values as $value) {
4545 4545
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4546 4546
         }
4547
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4547
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4548 4548
     }
4549 4549
 
4550 4550
 
@@ -4582,7 +4582,7 @@  discard block
 block discarded – undo
4582 4582
             $main_table  = $this->_get_main_table();
4583 4583
             $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4584 4584
         }
4585
-        return '(' . implode(',', $prepped) . ')';
4585
+        return '('.implode(',', $prepped).')';
4586 4586
     }
4587 4587
 
4588 4588
 
@@ -4602,7 +4602,7 @@  discard block
 block discarded – undo
4602 4602
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4603 4603
             );
4604 4604
         } //$field_obj should really just be a data type
4605
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4605
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4606 4606
             throw new EE_Error(
4607 4607
                 sprintf(
4608 4608
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4639,14 +4639,14 @@  discard block
 block discarded – undo
4639 4639
             );
4640 4640
         }
4641 4641
         $number_of_parts       = count($query_param_parts);
4642
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4642
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4643 4643
         if ($number_of_parts === 1) {
4644 4644
             $field_name = $last_query_param_part;
4645 4645
             $model_obj  = $this;
4646 4646
         } else {// $number_of_parts >= 2
4647 4647
             // the last part is the column name, and there are only 2parts. therefore...
4648 4648
             $field_name = $last_query_param_part;
4649
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4649
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4650 4650
         }
4651 4651
         try {
4652 4652
             return $model_obj->field_settings_for($field_name);
@@ -4667,7 +4667,7 @@  discard block
 block discarded – undo
4667 4667
     public function _get_qualified_column_for_field($field_name)
4668 4668
     {
4669 4669
         $all_fields = $this->field_settings();
4670
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4670
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4671 4671
         if ($field) {
4672 4672
             return $field->get_qualified_column();
4673 4673
         }
@@ -4737,10 +4737,10 @@  discard block
 block discarded – undo
4737 4737
      */
4738 4738
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4739 4739
     {
4740
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4740
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4741 4741
         $qualified_columns = [];
4742 4742
         foreach ($this->field_settings() as $field_name => $field) {
4743
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4743
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4744 4744
         }
4745 4745
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4746 4746
     }
@@ -4763,11 +4763,11 @@  discard block
 block discarded – undo
4763 4763
             if ($table_obj instanceof EE_Primary_Table) {
4764 4764
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4765 4765
                     ? $table_obj->get_select_join_limit($limit)
4766
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4766
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4767 4767
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4768 4768
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4769 4769
                     ? $table_obj->get_select_join_limit_join($limit)
4770
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4770
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4771 4771
             }
4772 4772
         }
4773 4773
         return $SQL;
@@ -4836,7 +4836,7 @@  discard block
 block discarded – undo
4836 4836
         foreach ($this->field_settings() as $field_obj) {
4837 4837
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838 4838
             /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4839
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4840 4840
         }
4841 4841
         return $data_types;
4842 4842
     }
@@ -4851,8 +4851,8 @@  discard block
 block discarded – undo
4851 4851
      */
4852 4852
     public function get_related_model_obj($model_name)
4853 4853
     {
4854
-        $model_classname = "EEM_" . $model_name;
4855
-        if (! class_exists($model_classname)) {
4854
+        $model_classname = "EEM_".$model_name;
4855
+        if ( ! class_exists($model_classname)) {
4856 4856
             throw new EE_Error(
4857 4857
                 sprintf(
4858 4858
                     esc_html__(
@@ -4864,7 +4864,7 @@  discard block
 block discarded – undo
4864 4864
                 )
4865 4865
             );
4866 4866
         }
4867
-        return call_user_func($model_classname . "::instance");
4867
+        return call_user_func($model_classname."::instance");
4868 4868
     }
4869 4869
 
4870 4870
 
@@ -4891,7 +4891,7 @@  discard block
 block discarded – undo
4891 4891
         $belongs_to_relations = [];
4892 4892
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4893 4893
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4894
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4894
+                $belongs_to_relations[$model_name] = $relation_obj;
4895 4895
             }
4896 4896
         }
4897 4897
         return $belongs_to_relations;
@@ -4908,7 +4908,7 @@  discard block
 block discarded – undo
4908 4908
     public function related_settings_for($relation_name)
4909 4909
     {
4910 4910
         $relatedModels = $this->relation_settings();
4911
-        if (! array_key_exists($relation_name, $relatedModels)) {
4911
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4912 4912
             throw new EE_Error(
4913 4913
                 sprintf(
4914 4914
                     esc_html__(
@@ -4921,7 +4921,7 @@  discard block
 block discarded – undo
4921 4921
                 )
4922 4922
             );
4923 4923
         }
4924
-        return $relatedModels[ $relation_name ];
4924
+        return $relatedModels[$relation_name];
4925 4925
     }
4926 4926
 
4927 4927
 
@@ -4937,7 +4937,7 @@  discard block
 block discarded – undo
4937 4937
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4938 4938
     {
4939 4939
         $fieldSettings = $this->field_settings($include_db_only_fields);
4940
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4940
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4941 4941
             throw new EE_Error(
4942 4942
                 sprintf(
4943 4943
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4946,7 +4946,7 @@  discard block
 block discarded – undo
4946 4946
                 )
4947 4947
             );
4948 4948
         }
4949
-        return $fieldSettings[ $fieldName ];
4949
+        return $fieldSettings[$fieldName];
4950 4950
     }
4951 4951
 
4952 4952
 
@@ -4959,7 +4959,7 @@  discard block
 block discarded – undo
4959 4959
     public function has_field($fieldName)
4960 4960
     {
4961 4961
         $fieldSettings = $this->field_settings(true);
4962
-        if (isset($fieldSettings[ $fieldName ])) {
4962
+        if (isset($fieldSettings[$fieldName])) {
4963 4963
             return true;
4964 4964
         }
4965 4965
         return false;
@@ -4975,7 +4975,7 @@  discard block
 block discarded – undo
4975 4975
     public function has_relation($relation_name)
4976 4976
     {
4977 4977
         $relations = $this->relation_settings();
4978
-        if (isset($relations[ $relation_name ])) {
4978
+        if (isset($relations[$relation_name])) {
4979 4979
             return true;
4980 4980
         }
4981 4981
         return false;
@@ -5011,7 +5011,7 @@  discard block
 block discarded – undo
5011 5011
                     break;
5012 5012
                 }
5013 5013
             }
5014
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5014
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5015 5015
                 throw new EE_Error(
5016 5016
                     sprintf(
5017 5017
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5071,17 +5071,17 @@  discard block
 block discarded – undo
5071 5071
      */
5072 5072
     public function get_foreign_key_to($model_name)
5073 5073
     {
5074
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5074
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5075 5075
             foreach ($this->field_settings() as $field) {
5076 5076
                 if (
5077 5077
                     $field instanceof EE_Foreign_Key_Field_Base
5078 5078
                     && in_array($model_name, $field->get_model_names_pointed_to())
5079 5079
                 ) {
5080
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5080
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5081 5081
                     break;
5082 5082
                 }
5083 5083
             }
5084
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5084
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5085 5085
                 throw new EE_Error(
5086 5086
                     sprintf(
5087 5087
                         esc_html__(
@@ -5094,7 +5094,7 @@  discard block
 block discarded – undo
5094 5094
                 );
5095 5095
             }
5096 5096
         }
5097
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5097
+        return $this->_cache_foreign_key_to_fields[$model_name];
5098 5098
     }
5099 5099
 
5100 5100
 
@@ -5110,7 +5110,7 @@  discard block
 block discarded – undo
5110 5110
     {
5111 5111
         $table_alias_sans_model_relation_chain_prefix =
5112 5112
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5113
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5113
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5114 5114
     }
5115 5115
 
5116 5116
 
@@ -5128,7 +5128,7 @@  discard block
 block discarded – undo
5128 5128
                 $this->_cached_fields = [];
5129 5129
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5130 5130
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5131
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5131
+                        $this->_cached_fields[$field_name] = $field_obj;
5132 5132
                     }
5133 5133
                 }
5134 5134
             }
@@ -5139,8 +5139,8 @@  discard block
 block discarded – undo
5139 5139
             foreach ($this->_fields as $fields_corresponding_to_table) {
5140 5140
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5141 5141
                     /** @var $field_obj EE_Model_Field_Base */
5142
-                    if (! $field_obj->is_db_only_field()) {
5143
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5142
+                    if ( ! $field_obj->is_db_only_field()) {
5143
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5144 5144
                     }
5145 5145
                 }
5146 5146
             }
@@ -5180,12 +5180,12 @@  discard block
 block discarded – undo
5180 5180
                     $primary_key_field->get_qualified_column(),
5181 5181
                     $primary_key_field->get_table_column()
5182 5182
                 );
5183
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5183
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5184 5184
                     continue;
5185 5185
                 }
5186 5186
             }
5187 5187
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5188
-            if (! $classInstance) {
5188
+            if ( ! $classInstance) {
5189 5189
                 throw new EE_Error(
5190 5190
                     sprintf(
5191 5191
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5198,7 +5198,7 @@  discard block
 block discarded – undo
5198 5198
             $classInstance->set_timezone($this->_timezone);
5199 5199
             // make sure if there is any timezone setting present that we set the timezone for the object
5200 5200
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5201
-            $array_of_objects[ $key ] = $classInstance;
5201
+            $array_of_objects[$key] = $classInstance;
5202 5202
             // also, for all the relations of type BelongsTo, see if we can cache
5203 5203
             // those related models
5204 5204
             // (we could do this for other relations too, but if there are conditions
@@ -5242,9 +5242,9 @@  discard block
 block discarded – undo
5242 5242
         $results = [];
5243 5243
         if ($this->_custom_selections instanceof CustomSelects) {
5244 5244
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5245
-                if (isset($db_results_row[ $alias ])) {
5246
-                    $results[ $alias ] = $this->convertValueToDataType(
5247
-                        $db_results_row[ $alias ],
5245
+                if (isset($db_results_row[$alias])) {
5246
+                    $results[$alias] = $this->convertValueToDataType(
5247
+                        $db_results_row[$alias],
5248 5248
                         $this->_custom_selections->getDataTypeForAlias($alias)
5249 5249
                     );
5250 5250
                 }
@@ -5289,9 +5289,9 @@  discard block
 block discarded – undo
5289 5289
         $this_model_fields_and_values = [];
5290 5290
         // setup the row using default values;
5291 5291
         foreach ($this->field_settings() as $field_name => $field_obj) {
5292
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5292
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5293 5293
         }
5294
-        $className     = $this->_get_class_name();
5294
+        $className = $this->_get_class_name();
5295 5295
         return EE_Registry::instance()->load_class(
5296 5296
             $className,
5297 5297
             [$this_model_fields_and_values],
@@ -5309,20 +5309,20 @@  discard block
 block discarded – undo
5309 5309
      */
5310 5310
     public function instantiate_class_from_array_or_object($cols_n_values)
5311 5311
     {
5312
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5312
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5313 5313
             $cols_n_values = get_object_vars($cols_n_values);
5314 5314
         }
5315 5315
         $primary_key = null;
5316 5316
         // make sure the array only has keys that are fields/columns on this model
5317 5317
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5318
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5318
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5319
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5320 5320
         }
5321 5321
         $className = $this->_get_class_name();
5322 5322
         // check we actually found results that we can use to build our model object
5323 5323
         // if not, return null
5324 5324
         if ($this->has_primary_key_field()) {
5325
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5326 5326
                 return null;
5327 5327
             }
5328 5328
         } elseif ($this->unique_indexes()) {
@@ -5334,7 +5334,7 @@  discard block
 block discarded – undo
5334 5334
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5335 5335
         if ($primary_key) {
5336 5336
             $classInstance = $this->get_from_entity_map($primary_key);
5337
-            if (! $classInstance) {
5337
+            if ( ! $classInstance) {
5338 5338
                 $classInstance = EE_Registry::instance()
5339 5339
                                             ->load_class(
5340 5340
                                                 $className,
@@ -5366,8 +5366,8 @@  discard block
 block discarded – undo
5366 5366
      */
5367 5367
     public function get_from_entity_map($id)
5368 5368
     {
5369
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5370
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5369
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5370
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5371 5371
     }
5372 5372
 
5373 5373
 
@@ -5389,7 +5389,7 @@  discard block
 block discarded – undo
5389 5389
     public function add_to_entity_map(EE_Base_Class $object)
5390 5390
     {
5391 5391
         $className = $this->_get_class_name();
5392
-        if (! $object instanceof $className) {
5392
+        if ( ! $object instanceof $className) {
5393 5393
             throw new EE_Error(
5394 5394
                 sprintf(
5395 5395
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5399,7 +5399,7 @@  discard block
 block discarded – undo
5399 5399
             );
5400 5400
         }
5401 5401
         /** @var $object EE_Base_Class */
5402
-        if (! $object->ID()) {
5402
+        if ( ! $object->ID()) {
5403 5403
             throw new EE_Error(
5404 5404
                 sprintf(
5405 5405
                     esc_html__(
@@ -5415,7 +5415,7 @@  discard block
 block discarded – undo
5415 5415
         if ($classInstance) {
5416 5416
             return $classInstance;
5417 5417
         }
5418
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5418
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5419 5419
         return $object;
5420 5420
     }
5421 5421
 
@@ -5430,11 +5430,11 @@  discard block
 block discarded – undo
5430 5430
     public function clear_entity_map($id = null)
5431 5431
     {
5432 5432
         if (empty($id)) {
5433
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5433
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5434 5434
             return true;
5435 5435
         }
5436
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5437
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5436
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5437
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5438 5438
             return true;
5439 5439
         }
5440 5440
         return false;
@@ -5479,17 +5479,17 @@  discard block
 block discarded – undo
5479 5479
             // there is a primary key on this table and its not set. Use defaults for all its columns
5480 5480
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481 5481
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5482
+                    if ( ! $field_obj->is_db_only_field()) {
5483 5483
                         // prepare field as if its coming from db
5484 5484
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5485
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5485
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5486 5486
                     }
5487 5487
                 }
5488 5488
             } else {
5489 5489
                 // the table's rows existed. Use their values
5490 5490
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5491
-                    if (! $field_obj->is_db_only_field()) {
5492
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5491
+                    if ( ! $field_obj->is_db_only_field()) {
5492
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5493 5493
                             $cols_n_values,
5494 5494
                             $field_obj->get_qualified_column(),
5495 5495
                             $field_obj->get_table_column()
@@ -5516,17 +5516,17 @@  discard block
 block discarded – undo
5516 5516
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5517 5517
         // does the field on the model relate to this column retrieved from the db?
5518 5518
         // or is it a db-only field? (not relating to the model)
5519
-        if (isset($cols_n_values[ $qualified_column ])) {
5520
-            $value = $cols_n_values[ $qualified_column ];
5521
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5522
-            $value = $cols_n_values[ $regular_column ];
5523
-        } elseif (! empty($this->foreign_key_aliases)) {
5519
+        if (isset($cols_n_values[$qualified_column])) {
5520
+            $value = $cols_n_values[$qualified_column];
5521
+        } elseif (isset($cols_n_values[$regular_column])) {
5522
+            $value = $cols_n_values[$regular_column];
5523
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5524 5524
             // no PK?  ok check if there is a foreign key alias set for this table
5525 5525
             // then check if that alias exists in the incoming data
5526 5526
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5527 5527
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5528
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5529
-                    $value = $cols_n_values[ $FK_alias ];
5528
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5529
+                    $value = $cols_n_values[$FK_alias];
5530 5530
                     [$pk_class] = explode('.', $PK_column);
5531 5531
                     $pk_model_name = "EEM_{$pk_class}";
5532 5532
                     /** @var EEM_Base $pk_model */
@@ -5570,7 +5570,7 @@  discard block
 block discarded – undo
5570 5570
                     $obj_in_map->clear_cache($relation_name, null, true);
5571 5571
                 }
5572 5572
             }
5573
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5573
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5574 5574
             return $obj_in_map;
5575 5575
         }
5576 5576
         return $this->get_one_by_ID($id);
@@ -5621,7 +5621,7 @@  discard block
 block discarded – undo
5621 5621
      */
5622 5622
     private function _get_class_name()
5623 5623
     {
5624
-        return "EE_" . $this->get_this_model_name();
5624
+        return "EE_".$this->get_this_model_name();
5625 5625
     }
5626 5626
 
5627 5627
 
@@ -5673,7 +5673,7 @@  discard block
 block discarded – undo
5673 5673
     {
5674 5674
         $className = get_class($this);
5675 5675
         $tagName   = "FHEE__{$className}__{$methodName}";
5676
-        if (! has_filter($tagName)) {
5676
+        if ( ! has_filter($tagName)) {
5677 5677
             throw new EE_Error(
5678 5678
                 sprintf(
5679 5679
                     esc_html__(
@@ -5842,7 +5842,7 @@  discard block
 block discarded – undo
5842 5842
         $unique_indexes = [];
5843 5843
         foreach ($this->_indexes as $name => $index) {
5844 5844
             if ($index instanceof EE_Unique_Index) {
5845
-                $unique_indexes [ $name ] = $index;
5845
+                $unique_indexes [$name] = $index;
5846 5846
             }
5847 5847
         }
5848 5848
         return $unique_indexes;
@@ -5906,7 +5906,7 @@  discard block
 block discarded – undo
5906 5906
         $key_vals_in_combined_pk = [];
5907 5907
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5908 5908
         foreach ($key_fields as $key_field_name => $field_obj) {
5909
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5909
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5910 5910
                 return null;
5911 5911
             }
5912 5912
         }
@@ -5926,7 +5926,7 @@  discard block
 block discarded – undo
5926 5926
     {
5927 5927
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5928 5928
         foreach ($keys_it_should_have as $key) {
5929
-            if (! isset($key_vals[ $key ])) {
5929
+            if ( ! isset($key_vals[$key])) {
5930 5930
                 return false;
5931 5931
             }
5932 5932
         }
@@ -5964,8 +5964,8 @@  discard block
 block discarded – undo
5964 5964
         }
5965 5965
         // even copies obviously won't have the same ID, so remove the primary key
5966 5966
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5967
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5968
-            unset($attributes_array[ $this->primary_key_name() ]);
5967
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5968
+            unset($attributes_array[$this->primary_key_name()]);
5969 5969
         }
5970 5970
         if (isset($query_params[0])) {
5971 5971
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5986,7 +5986,7 @@  discard block
 block discarded – undo
5986 5986
      */
5987 5987
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5988 5988
     {
5989
-        if (! is_array($query_params)) {
5989
+        if ( ! is_array($query_params)) {
5990 5990
             EE_Error::doing_it_wrong(
5991 5991
                 'EEM_Base::get_one_copy',
5992 5992
                 sprintf(
@@ -6036,7 +6036,7 @@  discard block
 block discarded – undo
6036 6036
      */
6037 6037
     private function _prepare_operator_for_sql($operator_supplied)
6038 6038
     {
6039
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6039
+        $sql_operator = $this->_valid_operators[$operator_supplied] ?? null;
6040 6040
         if ($sql_operator) {
6041 6041
             return $sql_operator;
6042 6042
         }
@@ -6133,7 +6133,7 @@  discard block
 block discarded – undo
6133 6133
         $objs  = $this->get_all($query_params);
6134 6134
         $names = [];
6135 6135
         foreach ($objs as $obj) {
6136
-            $names[ $obj->ID() ] = $obj->name();
6136
+            $names[$obj->ID()] = $obj->name();
6137 6137
         }
6138 6138
         return $names;
6139 6139
     }
@@ -6153,7 +6153,7 @@  discard block
 block discarded – undo
6153 6153
      */
6154 6154
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6155 6155
     {
6156
-        if (! $this->has_primary_key_field()) {
6156
+        if ( ! $this->has_primary_key_field()) {
6157 6157
             if (WP_DEBUG) {
6158 6158
                 EE_Error::add_error(
6159 6159
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6166,7 +6166,7 @@  discard block
 block discarded – undo
6166 6166
         $IDs = [];
6167 6167
         foreach ($model_objects as $model_object) {
6168 6168
             $id = $model_object->ID();
6169
-            if (! $id) {
6169
+            if ( ! $id) {
6170 6170
                 if ($filter_out_empty_ids) {
6171 6171
                     continue;
6172 6172
                 }
@@ -6216,22 +6216,22 @@  discard block
 block discarded – undo
6216 6216
         EEM_Base::verify_is_valid_cap_context($context);
6217 6217
         // check if we ought to run the restriction generator first
6218 6218
         if (
6219
-            isset($this->_cap_restriction_generators[ $context ])
6220
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6221
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6219
+            isset($this->_cap_restriction_generators[$context])
6220
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6221
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6222 6222
         ) {
6223
-            $this->_cap_restrictions[ $context ] = array_merge(
6224
-                $this->_cap_restrictions[ $context ],
6225
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6223
+            $this->_cap_restrictions[$context] = array_merge(
6224
+                $this->_cap_restrictions[$context],
6225
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6226 6226
             );
6227 6227
         }
6228 6228
         // and make sure we've finalized the construction of each restriction
6229
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6229
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6230 6230
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6231 6231
                 $where_conditions_obj->_finalize_construct($this);
6232 6232
             }
6233 6233
         }
6234
-        return $this->_cap_restrictions[ $context ];
6234
+        return $this->_cap_restrictions[$context];
6235 6235
     }
6236 6236
 
6237 6237
 
@@ -6261,9 +6261,9 @@  discard block
 block discarded – undo
6261 6261
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6262 6262
             if (
6263 6263
                 ! EE_Capabilities::instance()
6264
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6264
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6265 6265
             ) {
6266
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6266
+                $missing_caps[$cap] = $restriction_if_no_cap;
6267 6267
             }
6268 6268
         }
6269 6269
         return $missing_caps;
@@ -6296,8 +6296,8 @@  discard block
 block discarded – undo
6296 6296
     public function cap_action_for_context($context)
6297 6297
     {
6298 6298
         $mapping = $this->cap_contexts_to_cap_action_map();
6299
-        if (isset($mapping[ $context ])) {
6300
-            return $mapping[ $context ];
6299
+        if (isset($mapping[$context])) {
6300
+            return $mapping[$context];
6301 6301
         }
6302 6302
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6303 6303
             return $action;
@@ -6415,7 +6415,7 @@  discard block
 block discarded – undo
6415 6415
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6416 6416
             if (
6417 6417
                 $query_param_key === $logic_query_param_key
6418
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6418
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6419 6419
             ) {
6420 6420
                 return true;
6421 6421
             }
@@ -6473,7 +6473,7 @@  discard block
 block discarded – undo
6473 6473
         if ($password_field instanceof EE_Password_Field) {
6474 6474
             $field_names = $password_field->protectedFields();
6475 6475
             foreach ($field_names as $field_name) {
6476
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6476
+                $fields[$field_name] = $this->field_settings_for($field_name);
6477 6477
             }
6478 6478
         }
6479 6479
         return $fields;
@@ -6499,7 +6499,7 @@  discard block
 block discarded – undo
6499 6499
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6500 6500
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6501 6501
         }
6502
-        if (! is_array($model_obj_or_fields_n_values)) {
6502
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6503 6503
             throw new UnexpectedEntityException(
6504 6504
                 $model_obj_or_fields_n_values,
6505 6505
                 'EE_Base_Class',
@@ -6579,7 +6579,7 @@  discard block
 block discarded – undo
6579 6579
                 )
6580 6580
             );
6581 6581
         }
6582
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6582
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6583 6583
     }
6584 6584
 
6585 6585
 
Please login to merge, or discard this patch.