Completed
Branch CAFEREL (e3f72f)
by
unknown
09:30 queued 03:31
created
admin_pages/events/Events_Admin_Page.core.php 1 patch
Indentation   +2956 added lines, -2956 removed lines patch added patch discarded remove patch
@@ -18,2963 +18,2963 @@
 block discarded – undo
18 18
  */
19 19
 class Events_Admin_Page extends EE_Admin_Page_CPT
20 20
 {
21
-    /**
22
-     * This will hold the event object for event_details screen.
21
+	/**
22
+	 * This will hold the event object for event_details screen.
23
+	 *
24
+	 * @var EE_Event $_event
25
+	 */
26
+	protected $_event;
27
+
28
+
29
+	/**
30
+	 * This will hold the category object for category_details screen.
31
+	 *
32
+	 * @var stdClass $_category
33
+	 */
34
+	protected $_category;
35
+
36
+
37
+	/**
38
+	 * This will hold the event model instance
39
+	 *
40
+	 * @var EEM_Event $_event_model
41
+	 */
42
+	protected $_event_model;
43
+
44
+
45
+	/**
46
+	 * @var EE_Event
47
+	 */
48
+	protected $_cpt_model_obj = false;
49
+
50
+
51
+	/**
52
+	 * @var NodeGroupDao
53
+	 */
54
+	protected $model_obj_node_group_persister;
55
+
56
+	/**
57
+	 * @var AdvancedEditorAdminFormSection
58
+	 */
59
+	protected $advanced_editor_admin_form;
60
+
61
+
62
+	/**
63
+	 * Initialize page props for this admin page group.
64
+	 */
65
+	protected function _init_page_props()
66
+	{
67
+		$this->page_slug        = EVENTS_PG_SLUG;
68
+		$this->page_label       = EVENTS_LABEL;
69
+		$this->_admin_base_url  = EVENTS_ADMIN_URL;
70
+		$this->_admin_base_path = EVENTS_ADMIN;
71
+		$this->_cpt_model_names = [
72
+			'create_new' => 'EEM_Event',
73
+			'edit'       => 'EEM_Event',
74
+		];
75
+		$this->_cpt_edit_routes = [
76
+			'espresso_events' => 'edit',
77
+		];
78
+		add_action(
79
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
80
+			[$this, 'verify_event_edit'],
81
+			10,
82
+			2
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 * Sets the ajax hooks used for this admin page group.
89
+	 */
90
+	protected function _ajax_hooks()
91
+	{
92
+		add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
93
+	}
94
+
95
+
96
+	/**
97
+	 * Sets the page properties for this admin page group.
98
+	 */
99
+	protected function _define_page_props()
100
+	{
101
+		$event_id = $this->request->getRequestParam('post', 0, DataType::INT);
102
+		if ($event_id) {
103
+			$event_post = get_post($event_id);
104
+		}
105
+
106
+		$this->_admin_page_title = EVENTS_LABEL;
107
+		$this->_labels           = [
108
+			'buttons'      => [
109
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
110
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
111
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
112
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
113
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
114
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
115
+			],
116
+			'editor_title' => [
117
+				'espresso_events' => isset($event_post) && $event_post instanceof WP_Post
118
+					? $event_post->post_title
119
+					: esc_html__('Edit Event', 'event_espresso'),
120
+			],
121
+			'publishbox'   => [
122
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
123
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
124
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
125
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
126
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
127
+			],
128
+		];
129
+	}
130
+
131
+
132
+	/**
133
+	 * Sets the page routes property for this admin page group.
134
+	 */
135
+	protected function _set_page_routes()
136
+	{
137
+		// load formatter helper
138
+		// load field generator helper
139
+		// is there a evt_id in the request?
140
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, DataType::INT);
141
+		$EVT_ID = $this->request->getRequestParam('post', $EVT_ID, DataType::INT);
142
+
143
+		$this->_page_routes = [
144
+			'default'                       => [
145
+				'func'       => [$this, '_events_overview_list_table'],
146
+				'capability' => 'ee_read_events',
147
+			],
148
+			'create_new'                    => [
149
+				'func'       => [$this, '_create_new_cpt_item'],
150
+				'capability' => 'ee_edit_events',
151
+			],
152
+			'edit'                          => [
153
+				'func'       => [$this, '_edit_cpt_item'],
154
+				'capability' => 'ee_edit_event',
155
+				'obj_id'     => $EVT_ID,
156
+			],
157
+			'copy_event'                    => [
158
+				'func'       => [$this, '_copy_events'],
159
+				'capability' => 'ee_edit_event',
160
+				'obj_id'     => $EVT_ID,
161
+				'noheader'   => true,
162
+			],
163
+			'trash_event'                   => [
164
+				'func'       => [$this, '_trash_or_restore_event'],
165
+				'args'       => ['event_status' => 'trash'],
166
+				'capability' => 'ee_delete_event',
167
+				'obj_id'     => $EVT_ID,
168
+				'noheader'   => true,
169
+			],
170
+			'trash_events'                  => [
171
+				'func'       => [$this, '_trash_or_restore_events'],
172
+				'args'       => ['event_status' => 'trash'],
173
+				'capability' => 'ee_delete_events',
174
+				'noheader'   => true,
175
+			],
176
+			'restore_event'                 => [
177
+				'func'       => [$this, '_trash_or_restore_event'],
178
+				'args'       => ['event_status' => 'draft'],
179
+				'capability' => 'ee_delete_event',
180
+				'obj_id'     => $EVT_ID,
181
+				'noheader'   => true,
182
+			],
183
+			'restore_events'                => [
184
+				'func'       => [$this, '_trash_or_restore_events'],
185
+				'args'       => ['event_status' => 'draft'],
186
+				'capability' => 'ee_delete_events',
187
+				'noheader'   => true,
188
+			],
189
+			'delete_event'                  => [
190
+				'func'       => [$this, '_delete_event'],
191
+				'capability' => 'ee_delete_event',
192
+				'obj_id'     => $EVT_ID,
193
+				'noheader'   => true,
194
+			],
195
+			'delete_events'                 => [
196
+				'func'       => [$this, '_delete_events'],
197
+				'capability' => 'ee_delete_events',
198
+				'noheader'   => true,
199
+			],
200
+			'view_report'                   => [
201
+				'func'       => [$this, '_view_report'],
202
+				'capability' => 'ee_edit_events',
203
+			],
204
+			'default_event_settings'        => [
205
+				'func'       => [$this, '_default_event_settings'],
206
+				'capability' => 'manage_options',
207
+			],
208
+			'update_default_event_settings' => [
209
+				'func'       => [$this, '_update_default_event_settings'],
210
+				'capability' => 'manage_options',
211
+				'noheader'   => true,
212
+			],
213
+			'template_settings'             => [
214
+				'func'       => [$this, '_template_settings'],
215
+				'capability' => 'manage_options',
216
+			],
217
+			// event category tab related
218
+			'add_category'                  => [
219
+				'func'       => [$this, '_category_details'],
220
+				'capability' => 'ee_edit_event_category',
221
+				'args'       => ['view' => 'add'],
222
+			],
223
+			'edit_category'                 => [
224
+				'func'       => [$this, '_category_details'],
225
+				'capability' => 'ee_edit_event_category',
226
+				'args'       => ['view' => 'edit'],
227
+			],
228
+			'delete_categories'             => [
229
+				'func'       => [$this, '_delete_categories'],
230
+				'capability' => 'ee_delete_event_category',
231
+				'noheader'   => true,
232
+			],
233
+			'delete_category'               => [
234
+				'func'       => [$this, '_delete_categories'],
235
+				'capability' => 'ee_delete_event_category',
236
+				'noheader'   => true,
237
+			],
238
+			'insert_category'               => [
239
+				'func'       => [$this, '_insert_or_update_category'],
240
+				'args'       => ['new_category' => true],
241
+				'capability' => 'ee_edit_event_category',
242
+				'noheader'   => true,
243
+			],
244
+			'update_category'               => [
245
+				'func'       => [$this, '_insert_or_update_category'],
246
+				'args'       => ['new_category' => false],
247
+				'capability' => 'ee_edit_event_category',
248
+				'noheader'   => true,
249
+			],
250
+			'category_list'                 => [
251
+				'func'       => [$this, '_category_list_table'],
252
+				'capability' => 'ee_manage_event_categories',
253
+			],
254
+			'preview_deletion'              => [
255
+				'func'       => [$this, 'previewDeletion'],
256
+				'capability' => 'ee_delete_events',
257
+			],
258
+			'confirm_deletion'              => [
259
+				'func'       => [$this, 'confirmDeletion'],
260
+				'capability' => 'ee_delete_events',
261
+				'noheader'   => true,
262
+			],
263
+		];
264
+	}
265
+
266
+
267
+	/**
268
+	 * Set the _page_config property for this admin page group.
269
+	 */
270
+	protected function _set_page_config()
271
+	{
272
+		$post_id            = $this->request->getRequestParam('post', 0, DataType::INT);
273
+		$EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
274
+		$this->_page_config = [
275
+			'default'                => [
276
+				'nav'           => [
277
+					'label' => esc_html__('Overview', 'event_espresso'),
278
+					'icon'  => 'dashicons-list-view',
279
+					'order' => 10,
280
+				],
281
+				'list_table'    => 'Events_Admin_List_Table',
282
+				'help_tabs'     => [
283
+					'events_overview_help_tab'                       => [
284
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
285
+						'filename' => 'events_overview',
286
+					],
287
+					'events_overview_table_column_headings_help_tab' => [
288
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
289
+						'filename' => 'events_overview_table_column_headings',
290
+					],
291
+					'events_overview_filters_help_tab'               => [
292
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
293
+						'filename' => 'events_overview_filters',
294
+					],
295
+					'events_overview_view_help_tab'                  => [
296
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
297
+						'filename' => 'events_overview_views',
298
+					],
299
+					'events_overview_other_help_tab'                 => [
300
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
301
+						'filename' => 'events_overview_other',
302
+					],
303
+				],
304
+				'require_nonce' => false,
305
+			],
306
+			'create_new'             => [
307
+				'nav'           => [
308
+					'label'      => esc_html__('Add New Event', 'event_espresso'),
309
+					'icon'       => 'dashicons-plus-alt',
310
+					'order'      => 15,
311
+					'persistent' => false,
312
+				],
313
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
314
+				'help_tabs'     => [
315
+					'event_editor_help_tab'                            => [
316
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
317
+						'filename' => 'event_editor',
318
+					],
319
+					'event_editor_title_richtexteditor_help_tab'       => [
320
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
321
+						'filename' => 'event_editor_title_richtexteditor',
322
+					],
323
+					'event_editor_venue_details_help_tab'              => [
324
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
325
+						'filename' => 'event_editor_venue_details',
326
+					],
327
+					'event_editor_event_datetimes_help_tab'            => [
328
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
329
+						'filename' => 'event_editor_event_datetimes',
330
+					],
331
+					'event_editor_event_tickets_help_tab'              => [
332
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
333
+						'filename' => 'event_editor_event_tickets',
334
+					],
335
+					'event_editor_event_registration_options_help_tab' => [
336
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
337
+						'filename' => 'event_editor_event_registration_options',
338
+					],
339
+					'event_editor_tags_categories_help_tab'            => [
340
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
341
+						'filename' => 'event_editor_tags_categories',
342
+					],
343
+					'event_editor_questions_registrants_help_tab'      => [
344
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
345
+						'filename' => 'event_editor_questions_registrants',
346
+					],
347
+					'event_editor_save_new_event_help_tab'             => [
348
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
349
+						'filename' => 'event_editor_save_new_event',
350
+					],
351
+					'event_editor_other_help_tab'                      => [
352
+						'title'    => esc_html__('Event Other', 'event_espresso'),
353
+						'filename' => 'event_editor_other',
354
+					],
355
+				],
356
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
357
+				'require_nonce' => false,
358
+			],
359
+			'edit'                   => [
360
+				'nav'           => [
361
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
362
+					'icon'       => 'dashicons-edit',
363
+					'order'      => 15,
364
+					'persistent' => false,
365
+					'url'        => $post_id
366
+						? EE_Admin_Page::add_query_args_and_nonce(
367
+							['post' => $post_id, 'action' => 'edit'],
368
+							$this->_current_page_view_url
369
+						)
370
+						: $this->_admin_base_url,
371
+				],
372
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
373
+				'help_tabs'     => [
374
+					'event_editor_help_tab'                            => [
375
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
376
+						'filename' => 'event_editor',
377
+					],
378
+					'event_editor_title_richtexteditor_help_tab'       => [
379
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
380
+						'filename' => 'event_editor_title_richtexteditor',
381
+					],
382
+					'event_editor_venue_details_help_tab'              => [
383
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
384
+						'filename' => 'event_editor_venue_details',
385
+					],
386
+					'event_editor_event_datetimes_help_tab'            => [
387
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
388
+						'filename' => 'event_editor_event_datetimes',
389
+					],
390
+					'event_editor_event_tickets_help_tab'              => [
391
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
392
+						'filename' => 'event_editor_event_tickets',
393
+					],
394
+					'event_editor_event_registration_options_help_tab' => [
395
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
396
+						'filename' => 'event_editor_event_registration_options',
397
+					],
398
+					'event_editor_tags_categories_help_tab'            => [
399
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
400
+						'filename' => 'event_editor_tags_categories',
401
+					],
402
+					'event_editor_questions_registrants_help_tab'      => [
403
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
404
+						'filename' => 'event_editor_questions_registrants',
405
+					],
406
+					'event_editor_save_new_event_help_tab'             => [
407
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
408
+						'filename' => 'event_editor_save_new_event',
409
+					],
410
+					'event_editor_other_help_tab'                      => [
411
+						'title'    => esc_html__('Event Other', 'event_espresso'),
412
+						'filename' => 'event_editor_other',
413
+					],
414
+				],
415
+				'require_nonce' => false,
416
+			],
417
+			'default_event_settings' => [
418
+				'nav'           => [
419
+					'label' => esc_html__('Default Settings', 'event_espresso'),
420
+					'icon'  => 'dashicons-admin-generic',
421
+					'order' => 40,
422
+				],
423
+				'metaboxes'     => array_merge(['_publish_post_box'], $this->_default_espresso_metaboxes),
424
+				'labels'        => [
425
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
426
+				],
427
+				'help_tabs'     => [
428
+					'default_settings_help_tab'        => [
429
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
430
+						'filename' => 'events_default_settings',
431
+					],
432
+					'default_settings_status_help_tab' => [
433
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
434
+						'filename' => 'events_default_settings_status',
435
+					],
436
+					'default_maximum_tickets_help_tab' => [
437
+						'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
438
+						'filename' => 'events_default_settings_max_tickets',
439
+					],
440
+				],
441
+				'require_nonce' => false,
442
+			],
443
+			// template settings
444
+			'template_settings'      => [
445
+				'nav'           => [
446
+					'label' => esc_html__('Templates', 'event_espresso'),
447
+					'icon'  => 'dashicons-layout',
448
+					'order' => 30,
449
+				],
450
+				'metaboxes'     => $this->_default_espresso_metaboxes,
451
+				'help_tabs'     => [
452
+					'general_settings_templates_help_tab' => [
453
+						'title'    => esc_html__('Templates', 'event_espresso'),
454
+						'filename' => 'general_settings_templates',
455
+					],
456
+				],
457
+				'require_nonce' => false,
458
+			],
459
+			// event category stuff
460
+			'add_category'           => [
461
+				'nav'           => [
462
+					'label'      => esc_html__('Add Category', 'event_espresso'),
463
+					'icon'       => 'dashicons-plus-alt',
464
+					'order'      => 25,
465
+					'persistent' => false,
466
+				],
467
+				'help_tabs'     => [
468
+					'add_category_help_tab' => [
469
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
470
+						'filename' => 'events_add_category',
471
+					],
472
+				],
473
+				'metaboxes'     => ['_publish_post_box'],
474
+				'require_nonce' => false,
475
+			],
476
+			'edit_category'          => [
477
+				'nav'           => [
478
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
479
+					'icon'       => 'dashicons-edit',
480
+					'order'      => 25,
481
+					'persistent' => false,
482
+					'url'        => $EVT_CAT_ID
483
+						? add_query_arg(
484
+							['EVT_CAT_ID' => $EVT_CAT_ID],
485
+							$this->_current_page_view_url
486
+						)
487
+						: $this->_admin_base_url,
488
+				],
489
+				'help_tabs'     => [
490
+					'edit_category_help_tab' => [
491
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
492
+						'filename' => 'events_edit_category',
493
+					],
494
+				],
495
+				'metaboxes'     => ['_publish_post_box'],
496
+				'require_nonce' => false,
497
+			],
498
+			'category_list'          => [
499
+				'nav'           => [
500
+					'label' => esc_html__('Categories', 'event_espresso'),
501
+					'icon'  => 'dashicons-networking',
502
+					'order' => 20,
503
+				],
504
+				'list_table'    => 'Event_Categories_Admin_List_Table',
505
+				'help_tabs'     => [
506
+					'events_categories_help_tab'                       => [
507
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
508
+						'filename' => 'events_categories',
509
+					],
510
+					'events_categories_table_column_headings_help_tab' => [
511
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
512
+						'filename' => 'events_categories_table_column_headings',
513
+					],
514
+					'events_categories_view_help_tab'                  => [
515
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
516
+						'filename' => 'events_categories_views',
517
+					],
518
+					'events_categories_other_help_tab'                 => [
519
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
520
+						'filename' => 'events_categories_other',
521
+					],
522
+				],
523
+				'metaboxes'     => $this->_default_espresso_metaboxes,
524
+				'require_nonce' => false,
525
+			],
526
+			'preview_deletion'       => [
527
+				'nav'           => [
528
+					'label'      => esc_html__('Preview Deletion', 'event_espresso'),
529
+					'icon'       => 'dashicons-remove',
530
+					'order'      => 15,
531
+					'persistent' => false,
532
+					'url'        => '',
533
+				],
534
+				'require_nonce' => false,
535
+			],
536
+		];
537
+	}
538
+
539
+
540
+	/**
541
+	 * Used to register any global screen options if necessary for every route in this admin page group.
542
+	 */
543
+	protected function _add_screen_options()
544
+	{
545
+	}
546
+
547
+
548
+	/**
549
+	 * Implementing the screen options for the 'default' route.
550
+	 *
551
+	 * @throws InvalidArgumentException
552
+	 * @throws InvalidDataTypeException
553
+	 * @throws InvalidInterfaceException
554
+	 */
555
+	protected function _add_screen_options_default()
556
+	{
557
+		$this->_per_page_screen_option();
558
+	}
559
+
560
+
561
+	/**
562
+	 * Implementing screen options for the category list route.
563
+	 *
564
+	 * @throws InvalidArgumentException
565
+	 * @throws InvalidDataTypeException
566
+	 * @throws InvalidInterfaceException
567
+	 */
568
+	protected function _add_screen_options_category_list()
569
+	{
570
+		$page_title              = $this->_admin_page_title;
571
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
572
+		$this->_per_page_screen_option();
573
+		$this->_admin_page_title = $page_title;
574
+	}
575
+
576
+
577
+	/**
578
+	 * Used to register any global feature pointers for the admin page group.
579
+	 */
580
+	protected function _add_feature_pointers()
581
+	{
582
+	}
583
+
584
+
585
+	/**
586
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
587
+	 */
588
+	public function load_scripts_styles()
589
+	{
590
+		wp_register_style(
591
+			'events-admin-css',
592
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
593
+			[],
594
+			EVENT_ESPRESSO_VERSION
595
+		);
596
+		wp_register_style(
597
+			'ee-cat-admin',
598
+			EVENTS_ASSETS_URL . 'ee-cat-admin.css',
599
+			[],
600
+			EVENT_ESPRESSO_VERSION
601
+		);
602
+		wp_enqueue_style('events-admin-css');
603
+		wp_enqueue_style('ee-cat-admin');
604
+		// scripts
605
+		wp_register_script(
606
+			'event_editor_js',
607
+			EVENTS_ASSETS_URL . 'event_editor.js',
608
+			['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
609
+			EVENT_ESPRESSO_VERSION,
610
+			true
611
+		);
612
+	}
613
+
614
+
615
+	/**
616
+	 * Enqueuing scripts and styles specific to this view
617
+	 */
618
+	public function load_scripts_styles_create_new()
619
+	{
620
+		$this->load_scripts_styles_edit();
621
+	}
622
+
623
+
624
+	/**
625
+	 * Enqueuing scripts and styles specific to this view
626
+	 */
627
+	public function load_scripts_styles_edit()
628
+	{
629
+		// styles
630
+		wp_enqueue_style('espresso-ui-theme');
631
+		wp_register_style(
632
+			'event-editor-css',
633
+			EVENTS_ASSETS_URL . 'event-editor.css',
634
+			['ee-admin-css'],
635
+			EVENT_ESPRESSO_VERSION
636
+		);
637
+		wp_enqueue_style('event-editor-css');
638
+		// scripts
639
+		if (! $this->admin_config->useAdvancedEditor()) {
640
+			wp_register_script(
641
+				'event-datetime-metabox',
642
+				EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
643
+				['event_editor_js', 'ee-datepicker'],
644
+				EVENT_ESPRESSO_VERSION
645
+			);
646
+			wp_enqueue_script('event-datetime-metabox');
647
+		}
648
+	}
649
+
650
+
651
+	/**
652
+	 * Populating the _views property for the category list table view.
653
+	 */
654
+	protected function _set_list_table_views_category_list()
655
+	{
656
+		$this->_views = [
657
+			'all' => [
658
+				'slug'        => 'all',
659
+				'label'       => esc_html__('All', 'event_espresso'),
660
+				'count'       => 0,
661
+				'bulk_action' => [
662
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
663
+				],
664
+			],
665
+		];
666
+	}
667
+
668
+
669
+	/**
670
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
671
+	 */
672
+	public function admin_init()
673
+	{
674
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
675
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
676
+			'event_espresso'
677
+		);
678
+	}
679
+
680
+
681
+	/**
682
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
683
+	 * group.
684
+	 */
685
+	public function admin_notices()
686
+	{
687
+	}
688
+
689
+
690
+	/**
691
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
692
+	 * this admin page group.
693
+	 */
694
+	public function admin_footer_scripts()
695
+	{
696
+	}
697
+
698
+
699
+	/**
700
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
701
+	 * warning (via EE_Error::add_error());
702
+	 *
703
+	 * @param EE_Event|null $event Event object
704
+	 * @param string        $req_type
705
+	 * @return void
706
+	 * @throws EE_Error
707
+	 * @throws ReflectionException
708
+	 */
709
+	public function verify_event_edit(?EE_Base_Class $event = null, string $req_type = '')
710
+	{
711
+		// don't need to do this when processing
712
+		if (! empty($req_type)) {
713
+			return;
714
+		}
715
+		// no event?
716
+		if (! $event instanceof EE_Event) {
717
+			$event = $this->_cpt_model_obj;
718
+		}
719
+		// STILL no event?
720
+		if (! $event instanceof EE_Event) {
721
+			return;
722
+		}
723
+		// don't need to keep calling this
724
+		remove_action(
725
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
726
+			[$this, 'verify_event_edit']
727
+		);
728
+		$orig_status = $event->status();
729
+		// first check if event is active.
730
+		if (
731
+			$orig_status === EEM_Event::cancelled
732
+			|| $orig_status === EEM_Event::postponed
733
+			|| $event->is_expired()
734
+			|| $event->is_inactive()
735
+		) {
736
+			return;
737
+		}
738
+		// made it here so it IS active... next check that any of the tickets are sold.
739
+		if ($event->is_sold_out(true)) {
740
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
741
+				EE_Error::add_attention(
742
+					sprintf(
743
+						esc_html__(
744
+							'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.',
745
+							'event_espresso'
746
+						),
747
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
748
+					)
749
+				);
750
+			}
751
+			return;
752
+		}
753
+		if ($orig_status === EEM_Event::sold_out) {
754
+			EE_Error::add_attention(
755
+				sprintf(
756
+					esc_html__(
757
+						'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.',
758
+						'event_espresso'
759
+					),
760
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
761
+				)
762
+			);
763
+		}
764
+		// now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
765
+		if (! $event->tickets_on_sale()) {
766
+			return;
767
+		}
768
+		// made it here so show warning
769
+		$this->_edit_event_warning();
770
+	}
771
+
772
+
773
+	/**
774
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
775
+	 * When needed, hook this into a EE_Error::add_error() notice.
776
+	 *
777
+	 * @access protected
778
+	 * @return void
779
+	 */
780
+	protected function _edit_event_warning()
781
+	{
782
+		// we don't want to add warnings during these requests
783
+		if ($this->request->getRequestParam('action') === 'editpost') {
784
+			return;
785
+		}
786
+		EE_Error::add_attention(
787
+			sprintf(
788
+				esc_html__(
789
+					'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
790
+					'event_espresso'
791
+				),
792
+				'<a class="espresso-help-tab-lnk ee-help-tab-link">',
793
+				'</a>'
794
+			)
795
+		);
796
+	}
797
+
798
+
799
+	/**
800
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
801
+	 * Otherwise, do the normal logic
802
+	 *
803
+	 * @return void
804
+	 * @throws EE_Error
805
+	 * @throws InvalidArgumentException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws InvalidInterfaceException
808
+	 * @throws ReflectionException
809
+	 */
810
+	protected function _create_new_cpt_item()
811
+	{
812
+		$has_timezone_string = get_option('timezone_string');
813
+		// only nag them about setting their timezone if it's their first event, and they haven't already done it
814
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
815
+			EE_Error::add_attention(
816
+				sprintf(
817
+					esc_html__(
818
+						'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',
819
+						'event_espresso'
820
+					),
821
+					'<br>',
822
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
823
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
824
+					. '</select>',
825
+					'<button class="button button--secondary timezone-submit">',
826
+					'</button><span class="spinner"></span>'
827
+				),
828
+				__FILE__,
829
+				__FUNCTION__,
830
+				__LINE__
831
+			);
832
+		}
833
+		parent::_create_new_cpt_item();
834
+	}
835
+
836
+
837
+	/**
838
+	 * Sets the _views property for the default route in this admin page group.
839
+	 */
840
+	protected function _set_list_table_views_default()
841
+	{
842
+		$this->_views = [
843
+			'all'   => [
844
+				'slug'        => 'all',
845
+				'label'       => esc_html__('View All Events', 'event_espresso'),
846
+				'count'       => 0,
847
+				'bulk_action' => [
848
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
849
+				],
850
+			],
851
+			'draft' => [
852
+				'slug'        => 'draft',
853
+				'label'       => esc_html__('Draft', 'event_espresso'),
854
+				'count'       => 0,
855
+				'bulk_action' => [
856
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
857
+				],
858
+			],
859
+		];
860
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
861
+			$this->_views['trash'] = [
862
+				'slug'        => 'trash',
863
+				'label'       => esc_html__('Trash', 'event_espresso'),
864
+				'count'       => 0,
865
+				'bulk_action' => [
866
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
867
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
868
+				],
869
+			];
870
+		}
871
+	}
872
+
873
+
874
+	/**
875
+	 * Provides the legend item array for the default list table view.
876
+	 *
877
+	 * @return array
878
+	 * @throws EE_Error
879
+	 * @throws EE_Error
880
+	 */
881
+	protected function _event_legend_items(): array
882
+	{
883
+		$items    = [
884
+			'view_details'   => [
885
+				'class' => 'dashicons dashicons-visibility',
886
+				'desc'  => esc_html__('View Event', 'event_espresso'),
887
+			],
888
+			'edit_event'     => [
889
+				'class' => 'dashicons dashicons-calendar-alt',
890
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
891
+			],
892
+			'view_attendees' => [
893
+				'class' => 'dashicons dashicons-groups',
894
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
895
+			],
896
+		];
897
+		$items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
898
+		$statuses = [
899
+			'sold_out_status'  => [
900
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::sold_out,
901
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
902
+			],
903
+			'active_status'    => [
904
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::active,
905
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
906
+			],
907
+			'upcoming_status'  => [
908
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::upcoming,
909
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
910
+			],
911
+			'postponed_status' => [
912
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::postponed,
913
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
914
+			],
915
+			'cancelled_status' => [
916
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::cancelled,
917
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
918
+			],
919
+			'expired_status'   => [
920
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::expired,
921
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
922
+			],
923
+			'inactive_status'  => [
924
+				'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::inactive,
925
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
926
+			],
927
+		];
928
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
929
+		return array_merge($items, $statuses);
930
+	}
931
+
932
+
933
+	/**
934
+	 * @return EEM_Event
935
+	 * @throws EE_Error
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws InvalidInterfaceException
939
+	 * @throws ReflectionException
940
+	 */
941
+	private function _event_model(): EEM_Event
942
+	{
943
+		if (! $this->_event_model instanceof EEM_Event) {
944
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
945
+		}
946
+		return $this->_event_model;
947
+	}
948
+
949
+
950
+	/**
951
+	 * Adds extra buttons to the WP CPT permalink field row.
952
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
953
+	 *
954
+	 * @param string      $return    the current html
955
+	 * @param int         $id        the post id for the page
956
+	 * @param string|null $new_title What the title is
957
+	 * @param string|null $new_slug  what the slug is
958
+	 * @return string            The new html string for the permalink area
959
+	 * @deprecated $VID:$
960
+	 * @see TicketSelectorShortcodeButton::addButton
961
+	 */
962
+	public function extra_permalink_field_buttons(
963
+		string $return,
964
+		int $id,
965
+		?string $new_title,
966
+		?string $new_slug
967
+	): string {
968
+		return TicketSelectorShortcodeButton::addButton($return, $id, $new_title, $new_slug);
969
+	}
970
+
971
+
972
+	/**
973
+	 * _events_overview_list_table
974
+	 * This contains the logic for showing the events_overview list
975
+	 *
976
+	 * @access protected
977
+	 * @return void
978
+	 * @throws DomainException
979
+	 * @throws EE_Error
980
+	 * @throws InvalidArgumentException
981
+	 * @throws InvalidDataTypeException
982
+	 * @throws InvalidInterfaceException
983
+	 */
984
+	protected function _events_overview_list_table()
985
+	{
986
+		$after_list_table = [];
987
+		$links_html       = EEH_HTML::div('', '', 'ee-admin-section ee-layout-stack');
988
+		$links_html       .= EEH_HTML::h3(esc_html__('Links', 'event_espresso'));
989
+		$links_html       .= EEH_HTML::div(
990
+			EEH_Template::get_button_or_link(
991
+				get_post_type_archive_link('espresso_events'),
992
+				esc_html__('View Event Archive Page', 'event_espresso'),
993
+				'button button--small button--secondary'
994
+			),
995
+			'',
996
+			'ee-admin-button-row ee-admin-button-row--align-start'
997
+		);
998
+		$links_html       .= EEH_HTML::divx();
999
+
1000
+		$after_list_table['view_event_list_button'] = $links_html;
1001
+
1002
+		$after_list_table['legend'] = $this->_display_legend($this->_event_legend_items());
1003
+		$this->_admin_page_title    .= ' ' . $this->get_action_link_or_button(
1004
+			'create_new',
1005
+			'add',
1006
+			[],
1007
+			'add-new-h2'
1008
+		);
1009
+
1010
+		$this->_template_args['after_list_table'] = array_merge(
1011
+			(array) $this->_template_args['after_list_table'],
1012
+			$after_list_table
1013
+		);
1014
+		$this->display_admin_list_table_page_with_no_sidebar();
1015
+	}
1016
+
1017
+
1018
+	/**
1019
+	 * this allows for extra misc actions in the default WP publish box
1020
+	 *
1021
+	 * @return void
1022
+	 * @throws DomainException
1023
+	 * @throws EE_Error
1024
+	 * @throws InvalidArgumentException
1025
+	 * @throws InvalidDataTypeException
1026
+	 * @throws InvalidInterfaceException
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	public function extra_misc_actions_publish_box()
1030
+	{
1031
+		$this->_generate_publish_box_extra_content();
1032
+	}
1033
+
1034
+
1035
+	/**
1036
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1037
+	 * saved.
1038
+	 * Typically you would use this to save any additional data.
1039
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
1040
+	 * ALSO very important.  When a post transitions from scheduled to published,
1041
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1042
+	 * other meta saves. So MAKE sure that you handle this accordingly.
1043
+	 *
1044
+	 * @access protected
1045
+	 * @abstract
1046
+	 * @param string  $post_id The ID of the cpt that was saved (so you can link relationally)
1047
+	 * @param WP_Post $post    The post object of the cpt that was saved.
1048
+	 * @return void
1049
+	 * @throws EE_Error
1050
+	 * @throws InvalidArgumentException
1051
+	 * @throws InvalidDataTypeException
1052
+	 * @throws InvalidInterfaceException
1053
+	 * @throws ReflectionException
1054
+	 */
1055
+	protected function _insert_update_cpt_item($post_id, $post)
1056
+	{
1057
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1058
+			// get out we're not processing an event save.
1059
+			return;
1060
+		}
1061
+		$event_values = [
1062
+			'EVT_member_only'     => $this->request->getRequestParam('member_only', false, DataType::BOOL),
1063
+			'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, DataType::BOOL),
1064
+			'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1065
+		];
1066
+		// check if the new EDTR reg options meta box is being used, and if so, don't run updates for legacy version
1067
+		if (! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1068
+			$event_values['EVT_display_ticket_selector']     = $this->request->getRequestParam(
1069
+				'display_ticket_selector',
1070
+				false,
1071
+				'bool'
1072
+			);
1073
+			$event_values['EVT_additional_limit']            = min(
1074
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1075
+				$this->request->getRequestParam(
1076
+					'additional_limit',
1077
+					EEM_Event::get_default_additional_limit(),
1078
+					'int'
1079
+				)
1080
+			);
1081
+			$event_values['EVT_default_registration_status'] = $this->request->getRequestParam(
1082
+				'EVT_default_registration_status',
1083
+				EE_Registry::instance()->CFG->registration->default_STS_ID
1084
+			);
1085
+
1086
+			$event_values['EVT_external_URL'] = $this->request->getRequestParam('externalURL');
1087
+			$event_values['EVT_phone']        = $this->request->getRequestParam('event_phone');
1088
+			$event_values['EVT_display_desc'] = $this->request->getRequestParam('display_desc', false, DataType::BOOL);
1089
+		} elseif ($post instanceof WP_Post) {
1090
+			$event_values['EVT_name'] = $post->post_title;
1091
+			$event_values['EVT_desc'] = $post->post_content;
1092
+		}
1093
+		// update event
1094
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1095
+		// get event_object for other metaboxes...
1096
+		// though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1097
+		// i have to setup where conditions to override the filters in the model
1098
+		// that filter out auto-draft and inherit statuses so we GET the inherit id!
1099
+		/** @var EE_Event $event */
1100
+		$event = $this->_event_model()->get_one(
1101
+			[
1102
+				[
1103
+					$this->_event_model()->primary_key_name() => $post_id,
1104
+					'OR'                                      => [
1105
+						'status'   => $post->post_status,
1106
+						// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1107
+						// but the returned object here has a status of "publish", so use the original post status as well
1108
+						'status*1' => $this->request->getRequestParam('original_post_status'),
1109
+					],
1110
+				],
1111
+			]
1112
+		);
1113
+
1114
+		// the following are default callbacks for event attachment updates
1115
+		// that can be overridden by caffeinated functionality and/or addons.
1116
+		$event_update_callbacks = [];
1117
+		if (! $this->admin_config->useAdvancedEditor()) {
1118
+			$event_update_callbacks['_default_venue_update']   = [$this, '_default_venue_update'];
1119
+			$event_update_callbacks['_default_tickets_update'] = [$this, '_default_tickets_update'];
1120
+		}
1121
+		$event_update_callbacks = apply_filters(
1122
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1123
+			$event_update_callbacks
1124
+		);
1125
+
1126
+		$att_success = true;
1127
+		foreach ($event_update_callbacks as $e_callback) {
1128
+			$_success = is_callable($e_callback)
1129
+				? $e_callback($event, $this->request->requestParams())
1130
+				: false;
1131
+			// if ANY of these updates fail then we want the appropriate global error message
1132
+			$att_success = $_success !== false ? $att_success : false;
1133
+		}
1134
+		// any errors?
1135
+		if ($success && $att_success === false) {
1136
+			EE_Error::add_error(
1137
+				esc_html__(
1138
+					'Event Details saved successfully but something went wrong with saving attachments.',
1139
+					'event_espresso'
1140
+				),
1141
+				__FILE__,
1142
+				__FUNCTION__,
1143
+				__LINE__
1144
+			);
1145
+		} elseif ($success === false) {
1146
+			EE_Error::add_error(
1147
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1148
+				__FILE__,
1149
+				__FUNCTION__,
1150
+				__LINE__
1151
+			);
1152
+		}
1153
+	}
1154
+
1155
+
1156
+	/**
1157
+	 * @param int $post_id
1158
+	 * @param int $revision_id
1159
+	 * @throws EE_Error
1160
+	 * @throws EE_Error
1161
+	 * @throws ReflectionException
1162
+	 * @see parent::restore_item()
1163
+	 */
1164
+	protected function _restore_cpt_item(int $post_id, int $revision_id)
1165
+	{
1166
+		// copy existing event meta to new post
1167
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1168
+		if ($post_evt instanceof EE_Event) {
1169
+			// meta revision restore
1170
+			$post_evt->restore_revision($revision_id);
1171
+			// related objs restore
1172
+			$post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1173
+		}
1174
+	}
1175
+
1176
+
1177
+	/**
1178
+	 * Attach the venue to the Event
1179
+	 *
1180
+	 * @param EE_Event $event Event Object to add the venue to
1181
+	 * @param array    $data  The request data from the form
1182
+	 * @return bool           Success or fail.
1183
+	 * @throws EE_Error
1184
+	 * @throws ReflectionException
1185
+	 */
1186
+	protected function _default_venue_update(EE_Event $event, array $data): bool
1187
+	{
1188
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1189
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1190
+		$venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1191
+		// very important.  If we don't have a venue name...
1192
+		// then we'll get out because not necessary to create empty venue
1193
+		if (empty($data['venue_title'])) {
1194
+			return false;
1195
+		}
1196
+		$venue_array = [
1197
+			'VNU_wp_user'         => $event->get('EVT_wp_user'),
1198
+			'VNU_name'            => $data['venue_title'],
1199
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1200
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1201
+			'VNU_short_desc'      => ! empty($data['venue_short_description'])
1202
+				? $data['venue_short_description']
1203
+				: null,
1204
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1205
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1206
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1207
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1208
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1209
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1210
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1211
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1212
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1213
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1214
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1215
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1216
+			'status'              => 'publish',
1217
+		];
1218
+		// if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1219
+		if (! empty($venue_id)) {
1220
+			$update_where  = [$venue_model->primary_key_name() => $venue_id];
1221
+			$rows_affected = $venue_model->update($venue_array, [$update_where]);
1222
+			// we've gotta make sure that the venue is always attached to a revision..
1223
+			// add_relation_to should take care of making sure that the relation is already present.
1224
+			$event->_add_relation_to($venue_id, 'Venue');
1225
+			return $rows_affected > 0;
1226
+		}
1227
+		// we insert the venue
1228
+		$venue_id = $venue_model->insert($venue_array);
1229
+		$event->_add_relation_to($venue_id, 'Venue');
1230
+		return ! empty($venue_id);
1231
+		// when we have the ancestor come in it's already been handled by the revision save.
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1237
+	 *
1238
+	 * @param EE_Event $event The Event object we're attaching data to
1239
+	 * @param array    $data  The request data from the form
1240
+	 * @return array
1241
+	 * @throws EE_Error
1242
+	 * @throws ReflectionException
1243
+	 * @throws Exception
1244
+	 */
1245
+	protected function _default_tickets_update(EE_Event $event, array $data): array
1246
+	{
1247
+		if ($this->admin_config->useAdvancedEditor()) {
1248
+			return [];
1249
+		}
1250
+		$datetime       = null;
1251
+		$saved_tickets  = [];
1252
+		$event_timezone = $event->get_timezone();
1253
+		$date_formats   = ['Y-m-d', 'h:i a'];
1254
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1255
+			// trim all values to ensure any excess whitespace is removed.
1256
+			$datetime_data                = array_map('trim', $datetime_data);
1257
+			$datetime_data['DTT_EVT_end'] =
1258
+				isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1259
+					? $datetime_data['DTT_EVT_end']
1260
+					: $datetime_data['DTT_EVT_start'];
1261
+			$datetime_values              = [
1262
+				'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1263
+				'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1264
+				'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1265
+				'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1266
+				'DTT_order'     => $row,
1267
+			];
1268
+			// if we have an id then let's get existing object first and then set the new values.
1269
+			//  Otherwise we instantiate a new object for save.
1270
+			if (! empty($datetime_data['DTT_ID'])) {
1271
+				$datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1272
+				if (! $datetime instanceof EE_Datetime) {
1273
+					throw new RuntimeException(
1274
+						sprintf(
1275
+							esc_html__(
1276
+								'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1277
+								'event_espresso'
1278
+							),
1279
+							$datetime_data['DTT_ID']
1280
+						)
1281
+					);
1282
+				}
1283
+				$datetime->set_date_format($date_formats[0]);
1284
+				$datetime->set_time_format($date_formats[1]);
1285
+				foreach ($datetime_values as $field => $value) {
1286
+					$datetime->set($field, $value);
1287
+				}
1288
+			} else {
1289
+				$datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1290
+			}
1291
+			if (! $datetime instanceof EE_Datetime) {
1292
+				throw new RuntimeException(
1293
+					sprintf(
1294
+						esc_html__(
1295
+							'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1296
+							'event_espresso'
1297
+						),
1298
+						print_r($datetime_values, true)
1299
+					)
1300
+				);
1301
+			}
1302
+			// before going any further make sure our dates are setup correctly
1303
+			// so that the end date is always equal or greater than the start date.
1304
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1305
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1306
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1307
+			}
1308
+			$datetime->save();
1309
+			$event->_add_relation_to($datetime, 'Datetime');
1310
+		}
1311
+		// no datetimes get deleted so we don't do any of that logic here.
1312
+		// update tickets next
1313
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1314
+
1315
+		// set up some default start and end dates in case those are not present in the incoming data
1316
+		$default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1317
+		$default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1318
+		// use the start date of the first datetime for the end date
1319
+		$first_datetime   = $event->first_datetime();
1320
+		$default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1321
+
1322
+		// now process the incoming data
1323
+		foreach ($data['edit_tickets'] as $row => $ticket_data) {
1324
+			$update_prices = false;
1325
+			$ticket_price  = $data['edit_prices'][ $row ][1]['PRC_amount'] ?? 0;
1326
+			// trim inputs to ensure any excess whitespace is removed.
1327
+			$ticket_data   = array_map('trim', $ticket_data);
1328
+			$ticket_values = [
1329
+				'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1330
+				'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1331
+				'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1332
+				'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1333
+				'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1334
+					? $ticket_data['TKT_start_date']
1335
+					: $default_start_date,
1336
+				'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1337
+					? $ticket_data['TKT_end_date']
1338
+					: $default_end_date,
1339
+				'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1340
+									 || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1341
+					? $ticket_data['TKT_qty']
1342
+					: EE_INF,
1343
+				'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1344
+									 || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1345
+					? $ticket_data['TKT_uses']
1346
+					: EE_INF,
1347
+				'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1348
+				'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1349
+				'TKT_order'       => $ticket_data['TKT_order'] ?? $row,
1350
+				'TKT_price'       => $ticket_price,
1351
+				'TKT_row'         => $row,
1352
+			];
1353
+			// if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1354
+			// which means in turn that the prices will become new prices as well.
1355
+			if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1356
+				$ticket_values['TKT_ID']         = 0;
1357
+				$ticket_values['TKT_is_default'] = 0;
1358
+				$update_prices                   = true;
1359
+			}
1360
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
1361
+			// we actually do our saves ahead of adding any relations because its entirely possible that this
1362
+			// ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1363
+			// keep in mind that if the ticket has been sold (and we have changed pricing information),
1364
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1365
+			if (! empty($ticket_data['TKT_ID'])) {
1366
+				$existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1367
+				if (! $existing_ticket instanceof EE_Ticket) {
1368
+					throw new RuntimeException(
1369
+						sprintf(
1370
+							esc_html__(
1371
+								'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1372
+								'event_espresso'
1373
+							),
1374
+							$ticket_data['TKT_ID']
1375
+						)
1376
+					);
1377
+				}
1378
+				$ticket_sold = $existing_ticket->count_related(
1379
+					'Registration',
1380
+					[
1381
+							[
1382
+								'STS_ID' => [
1383
+									'NOT IN',
1384
+									[EEM_Registration::status_id_incomplete],
1385
+								],
1386
+							],
1387
+						]
1388
+				) > 0;
1389
+				// let's just check the total price for the existing ticket and determine if it matches the new total price.
1390
+				// if they are different then we create a new ticket (if $ticket_sold)
1391
+				// if they aren't different then we go ahead and modify existing ticket.
1392
+				$create_new_ticket = $ticket_sold
1393
+									 && $ticket_price !== $existing_ticket->price()
1394
+									 && ! $existing_ticket->deleted();
1395
+				$existing_ticket->set_date_format($date_formats[0]);
1396
+				$existing_ticket->set_time_format($date_formats[1]);
1397
+				// set new values
1398
+				foreach ($ticket_values as $field => $value) {
1399
+					if ($field == 'TKT_qty') {
1400
+						$existing_ticket->set_qty($value);
1401
+					} elseif ($field == 'TKT_price') {
1402
+						$existing_ticket->set('TKT_price', $ticket_price);
1403
+					} else {
1404
+						$existing_ticket->set($field, $value);
1405
+					}
1406
+				}
1407
+				$ticket = $existing_ticket;
1408
+				// if $create_new_ticket is false then we can safely update the existing ticket.
1409
+				//  Otherwise we have to create a new ticket.
1410
+				if ($create_new_ticket) {
1411
+					// archive the old ticket first
1412
+					$existing_ticket->set('TKT_deleted', 1);
1413
+					$existing_ticket->save();
1414
+					// make sure this ticket is still recorded in our $saved_tickets
1415
+					// so we don't run it through the regular trash routine.
1416
+					$saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1417
+					// create new ticket that's a copy of the existing except,
1418
+					// (a new id of course and not archived) AND has the new TKT_price associated with it.
1419
+					$new_ticket = clone $existing_ticket;
1420
+					$new_ticket->set('TKT_ID', 0);
1421
+					$new_ticket->set('TKT_deleted', 0);
1422
+					$new_ticket->set('TKT_sold', 0);
1423
+					// now we need to make sure that $new prices are created as well and attached to new ticket.
1424
+					$update_prices = true;
1425
+					$ticket        = $new_ticket;
1426
+				}
1427
+			} else {
1428
+				// no TKT_id so a new ticket
1429
+				$ticket_values['TKT_price'] = $ticket_price;
1430
+				$ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1431
+				$update_prices              = true;
1432
+			}
1433
+			if (! $ticket instanceof EE_Ticket) {
1434
+				throw new RuntimeException(
1435
+					sprintf(
1436
+						esc_html__(
1437
+							'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1438
+							'event_espresso'
1439
+						),
1440
+						print_r($ticket_values, true)
1441
+					)
1442
+				);
1443
+			}
1444
+			// cap ticket qty by datetime reg limits
1445
+			$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1446
+			// update ticket.
1447
+			$ticket->save();
1448
+			// before going any further make sure our dates are setup correctly
1449
+			// so that the end date is always equal or greater than the start date.
1450
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1451
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1452
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1453
+				$ticket->save();
1454
+			}
1455
+			// initially let's add the ticket to the datetime
1456
+			$datetime->_add_relation_to($ticket, 'Ticket');
1457
+			$saved_tickets[ $ticket->ID() ] = $ticket;
1458
+			// add prices to ticket
1459
+			$prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1460
+				? $data['edit_prices'][ $row ]
1461
+				: [];
1462
+			$this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1463
+		}
1464
+		// however now we need to handle permanently deleting tickets via the ui.
1465
+		// Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1466
+		// However, it does allow for deleting tickets that have no tickets sold,
1467
+		// in which case we want to get rid of permanently because there is no need to save in db.
1468
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? [] : $old_tickets;
1469
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1470
+		foreach ($tickets_removed as $id) {
1471
+			$id = absint($id);
1472
+			// get the ticket for this id
1473
+			$ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1474
+			if (! $ticket_to_remove instanceof EE_Ticket) {
1475
+				continue;
1476
+			}
1477
+			// need to get all the related datetimes on this ticket and remove from every single one of them
1478
+			// (remember this process can ONLY kick off if there are NO tickets sold)
1479
+			$related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1480
+			foreach ($related_datetimes as $related_datetime) {
1481
+				$ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1482
+			}
1483
+			// need to do the same for prices (except these prices can also be deleted because again,
1484
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1485
+			$ticket_to_remove->delete_related_permanently('Price');
1486
+			// finally let's delete this ticket
1487
+			// (which should not be blocked at this point b/c we've removed all our relationships)
1488
+			$ticket_to_remove->delete_permanently();
1489
+		}
1490
+		return [$datetime, $saved_tickets];
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * This attaches a list of given prices to a ticket.
1496
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices)
1497
+	 * because if there is a change in price information on a ticket, a new ticket is created anyways
1498
+	 * so the archived ticket will retain the old price info and prices are automatically "archived" via the ticket.
1499
+	 *
1500
+	 * @access  private
1501
+	 * @param array     $prices_data Array of prices from the form.
1502
+	 * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1503
+	 * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1504
+	 * @return  void
1505
+	 * @throws EE_Error
1506
+	 * @throws ReflectionException
1507
+	 */
1508
+	private function _add_prices_to_ticket(array $prices_data, EE_Ticket $ticket, bool $new_prices = false)
1509
+	{
1510
+		$timezone = $ticket->get_timezone();
1511
+		foreach ($prices_data as $row => $price_data) {
1512
+			$price_values = [
1513
+				'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1514
+				'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1515
+				'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1516
+				'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1517
+				'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1518
+				'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1519
+				'PRC_order'      => $row,
1520
+			];
1521
+			if ($new_prices || empty($price_values['PRC_ID'])) {
1522
+				$price_values['PRC_ID'] = 0;
1523
+				$price                  = EE_Price::new_instance($price_values, $timezone);
1524
+			} else {
1525
+				$price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1526
+				// update this price with new values
1527
+				foreach ($price_values as $field => $new_price) {
1528
+					$price->set($field, $new_price);
1529
+				}
1530
+			}
1531
+			if (! $price instanceof EE_Price) {
1532
+				throw new RuntimeException(
1533
+					sprintf(
1534
+						esc_html__(
1535
+							'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1536
+							'event_espresso'
1537
+						),
1538
+						print_r($price_values, true)
1539
+					)
1540
+				);
1541
+			}
1542
+			$price->save();
1543
+			$ticket->_add_relation_to($price, 'Price');
1544
+		}
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * Add in our autosave ajax handlers
1550
+	 *
1551
+	 */
1552
+	protected function _ee_autosave_create_new()
1553
+	{
1554
+	}
1555
+
1556
+
1557
+	/**
1558
+	 * More autosave handlers.
1559
+	 */
1560
+	protected function _ee_autosave_edit()
1561
+	{
1562
+	}
1563
+
1564
+
1565
+	/**
1566
+	 * @throws EE_Error
1567
+	 * @throws ReflectionException
1568
+	 */
1569
+	private function _generate_publish_box_extra_content()
1570
+	{
1571
+		// load formatter helper
1572
+		// args for getting related registrations
1573
+		$approved_query_args        = [
1574
+			[
1575
+				'REG_deleted' => 0,
1576
+				'STS_ID'      => EEM_Registration::status_id_approved,
1577
+			],
1578
+		];
1579
+		$not_approved_query_args    = [
1580
+			[
1581
+				'REG_deleted' => 0,
1582
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1583
+			],
1584
+		];
1585
+		$pending_payment_query_args = [
1586
+			[
1587
+				'REG_deleted' => 0,
1588
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1589
+			],
1590
+		];
1591
+		// publish box
1592
+		$publish_box_extra_args = [
1593
+			'view_approved_reg_url'        => add_query_arg(
1594
+				[
1595
+					'action'      => 'default',
1596
+					'event_id'    => $this->_cpt_model_obj->ID(),
1597
+					'_reg_status' => EEM_Registration::status_id_approved,
1598
+					'use_filters' => true,
1599
+				],
1600
+				REG_ADMIN_URL
1601
+			),
1602
+			'view_not_approved_reg_url'    => add_query_arg(
1603
+				[
1604
+					'action'      => 'default',
1605
+					'event_id'    => $this->_cpt_model_obj->ID(),
1606
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1607
+					'use_filters' => true,
1608
+				],
1609
+				REG_ADMIN_URL
1610
+			),
1611
+			'view_pending_payment_reg_url' => add_query_arg(
1612
+				[
1613
+					'action'      => 'default',
1614
+					'event_id'    => $this->_cpt_model_obj->ID(),
1615
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1616
+					'use_filters' => true,
1617
+				],
1618
+				REG_ADMIN_URL
1619
+			),
1620
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1621
+				'Registration',
1622
+				$approved_query_args
1623
+			),
1624
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1625
+				'Registration',
1626
+				$not_approved_query_args
1627
+			),
1628
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1629
+				'Registration',
1630
+				$pending_payment_query_args
1631
+			),
1632
+			'misc_pub_section_class'       => apply_filters(
1633
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1634
+				'misc-pub-section'
1635
+			),
1636
+		];
1637
+		ob_start();
1638
+		do_action(
1639
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1640
+			$this->_cpt_model_obj
1641
+		);
1642
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1643
+		// load template
1644
+		EEH_Template::display_template(
1645
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1646
+			$publish_box_extra_args
1647
+		);
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * @return EE_Event
1653
+	 */
1654
+	public function get_event_object()
1655
+	{
1656
+		return $this->_cpt_model_obj;
1657
+	}
1658
+
1659
+
1660
+
1661
+
1662
+	/** METABOXES * */
1663
+	/**
1664
+	 * _register_event_editor_meta_boxes
1665
+	 * add all metaboxes related to the event_editor
1666
+	 *
1667
+	 * @return void
1668
+	 * @throws EE_Error
1669
+	 * @throws ReflectionException
1670
+	 */
1671
+	protected function _register_event_editor_meta_boxes()
1672
+	{
1673
+		$this->verify_cpt_object();
1674
+		$use_advanced_editor = $this->admin_config->useAdvancedEditor();
1675
+		// check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
1676
+		if (! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1677
+			$this->addMetaBox(
1678
+				'espresso_event_editor_event_options',
1679
+				esc_html__('Event Registration Options', 'event_espresso'),
1680
+				[$this, 'registration_options_meta_box'],
1681
+				$this->page_slug,
1682
+				'side'
1683
+			);
1684
+		}
1685
+		if (! $use_advanced_editor) {
1686
+			$this->addMetaBox(
1687
+				'espresso_event_editor_tickets',
1688
+				esc_html__('Event Datetime & Ticket', 'event_espresso'),
1689
+				[$this, 'ticket_metabox'],
1690
+				$this->page_slug,
1691
+				'normal',
1692
+				'high'
1693
+			);
1694
+		} elseif ($this->feature->allowed('use_reg_options_meta_box')) {
1695
+			add_action(
1696
+				'add_meta_boxes_espresso_events',
1697
+				function () {
1698
+					global $current_screen;
1699
+					remove_meta_box('authordiv', $current_screen, 'normal');
1700
+				},
1701
+				99
1702
+			);
1703
+		}
1704
+		// NOTE: if you're looking for other metaboxes in here,
1705
+		// where a metabox has a related management page in the admin
1706
+		// you will find it setup in the related management page's "_Hooks" file.
1707
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1708
+	}
1709
+
1710
+
1711
+	/**
1712
+	 * @throws DomainException
1713
+	 * @throws EE_Error
1714
+	 * @throws ReflectionException
1715
+	 */
1716
+	public function ticket_metabox()
1717
+	{
1718
+		$existing_datetime_ids = $existing_ticket_ids = [];
1719
+		// defaults for template args
1720
+		$template_args = [
1721
+			'ticket_rows'       => '',
1722
+			'total_ticket_rows' => 1,
1723
+			'trash_icon'        => 'dashicons dashicons-lock',
1724
+			'disabled'          => '',
1725
+		];
1726
+		$event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1727
+		/**
1728
+		 * 1. Start with retrieving Datetimes
1729
+		 * 2. Fore each datetime get related tickets
1730
+		 * 3. For each ticket get related prices
1731
+		 */
1732
+		/** @var EEM_Datetime $datetime_model */
1733
+		$datetime_model = EE_Registry::instance()->load_model('Datetime');
1734
+		/** @var EEM_Ticket $datetime_model */
1735
+		$ticket_model = EE_Registry::instance()->load_model('Ticket');
1736
+		$times        = $datetime_model->get_all_event_dates($event_id);
1737
+		/** @type EE_Datetime $first_datetime */
1738
+		$first_datetime = reset($times);
1739
+		// do we get related tickets?
1740
+		if (
1741
+			$first_datetime instanceof EE_Datetime
1742
+			&& $first_datetime->ID() !== 0
1743
+		) {
1744
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1745
+			$template_args['time']   = $first_datetime;
1746
+			$related_tickets         = $first_datetime->tickets(
1747
+				[
1748
+					['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1749
+					'default_where_conditions' => 'none',
1750
+				]
1751
+			);
1752
+			if (! empty($related_tickets)) {
1753
+				$template_args['total_ticket_rows'] = count($related_tickets);
1754
+				$row                                = 0;
1755
+				foreach ($related_tickets as $ticket) {
1756
+					$existing_ticket_ids[]        = $ticket->get('TKT_ID');
1757
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1758
+					$row++;
1759
+				}
1760
+			} else {
1761
+				$template_args['total_ticket_rows'] = 1;
1762
+				/** @type EE_Ticket $ticket */
1763
+				$ticket                       = $ticket_model->create_default_object();
1764
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1765
+			}
1766
+		} else {
1767
+			$template_args['time'] = $times[0];
1768
+			/** @type EE_Ticket[] $tickets */
1769
+			$tickets                      = $ticket_model->get_all_default_tickets();
1770
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1771
+			// NOTE: we're just sending the first default row
1772
+			// (decaf can't manage default tickets so this should be sufficient);
1773
+		}
1774
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1775
+			'event_editor_event_datetimes_help_tab'
1776
+		);
1777
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1778
+		$template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1779
+		$template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1780
+		$template_args['ticket_js_structure']      = $this->_get_ticket_row(
1781
+			$ticket_model->create_default_object(),
1782
+			true
1783
+		);
1784
+		$template                                  = apply_filters(
1785
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1786
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1787
+		);
1788
+		EEH_Template::display_template($template, $template_args);
1789
+	}
1790
+
1791
+
1792
+	/**
1793
+	 * Setup an individual ticket form for the decaf event editor page
1794
+	 *
1795
+	 * @access private
1796
+	 * @param EE_Ticket $ticket   the ticket object
1797
+	 * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1798
+	 * @param int       $row
1799
+	 * @return string generated html for the ticket row.
1800
+	 * @throws EE_Error
1801
+	 * @throws ReflectionException
1802
+	 */
1803
+	private function _get_ticket_row(EE_Ticket $ticket, bool $skeleton = false, int $row = 0): string
1804
+	{
1805
+		$template_args = [
1806
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1807
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1808
+				: '',
1809
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1810
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1811
+			'TKT_name'            => $ticket->get('TKT_name'),
1812
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1813
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1814
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1815
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1816
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1817
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1818
+			'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1819
+									 && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1820
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'dashicons dashicons-lock',
1821
+			'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1822
+				: ' disabled=disabled',
1823
+		];
1824
+		$price         = $ticket->ID() !== 0
1825
+			? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1826
+			: null;
1827
+		$price         = $price instanceof EE_Price
1828
+			? $price
1829
+			: EEM_Price::instance()->create_default_object();
1830
+		$price_args    = [
1831
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1832
+			'PRC_amount'            => $price->get('PRC_amount'),
1833
+			'PRT_ID'                => $price->get('PRT_ID'),
1834
+			'PRC_ID'                => $price->get('PRC_ID'),
1835
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1836
+		];
1837
+		// make sure we have default start and end dates if skeleton
1838
+		// handle rows that should NOT be empty
1839
+		if (empty($template_args['TKT_start_date'])) {
1840
+			// if empty then the start date will be now.
1841
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1842
+		}
1843
+		if (empty($template_args['TKT_end_date'])) {
1844
+			// get the earliest datetime (if present);
1845
+			$earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1846
+				? $this->_cpt_model_obj->get_first_related(
1847
+					'Datetime',
1848
+					['order_by' => ['DTT_EVT_start' => 'ASC']]
1849
+				)
1850
+				: null;
1851
+			$template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1852
+				? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1853
+				: date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1854
+		}
1855
+		$template_args = array_merge($template_args, $price_args);
1856
+		$template      = apply_filters(
1857
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1858
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1859
+			$ticket
1860
+		);
1861
+		return EEH_Template::display_template($template, $template_args, true);
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * @throws EE_Error
1867
+	 * @throws ReflectionException
1868
+	 */
1869
+	public function registration_options_meta_box()
1870
+	{
1871
+		$yes_no_values             = [
1872
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1873
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1874
+		];
1875
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1876
+			[
1877
+				EEM_Registration::status_id_cancelled,
1878
+				EEM_Registration::status_id_declined,
1879
+				EEM_Registration::status_id_incomplete,
1880
+			],
1881
+			true
1882
+		);
1883
+		// $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1884
+		$template_args['_event']                          = $this->_cpt_model_obj;
1885
+		$template_args['event']                           = $this->_cpt_model_obj;
1886
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1887
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1888
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1889
+			'default_reg_status',
1890
+			$default_reg_status_values,
1891
+			$this->_cpt_model_obj->default_registration_status()
1892
+		);
1893
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
1894
+			'display_desc',
1895
+			$yes_no_values,
1896
+			$this->_cpt_model_obj->display_description()
1897
+		);
1898
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1899
+			'display_ticket_selector',
1900
+			$yes_no_values,
1901
+			$this->_cpt_model_obj->display_ticket_selector(),
1902
+			'',
1903
+			'',
1904
+			false
1905
+		);
1906
+		$template_args['additional_registration_options'] = apply_filters(
1907
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1908
+			'',
1909
+			$template_args,
1910
+			$yes_no_values,
1911
+			$default_reg_status_values
1912
+		);
1913
+		EEH_Template::display_template(
1914
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1915
+			$template_args
1916
+		);
1917
+	}
1918
+
1919
+
1920
+	/**
1921
+	 * _get_events()
1922
+	 * This method simply returns all the events (for the given _view and paging)
1923
+	 *
1924
+	 * @access public
1925
+	 * @param int  $per_page     count of items per page (20 default);
1926
+	 * @param int  $current_page what is the current page being viewed.
1927
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1928
+	 *                           If FALSE then we return an array of event objects
1929
+	 *                           that match the given _view and paging parameters.
1930
+	 * @return array|int         an array of event objects or a count of them.
1931
+	 * @throws Exception
1932
+	 */
1933
+	public function get_events(int $per_page = 10, int $current_page = 1, bool $count = false)
1934
+	{
1935
+		$EEM_Event   = $this->_event_model();
1936
+		$offset      = ($current_page - 1) * $per_page;
1937
+		$limit       = $count ? null : $offset . ',' . $per_page;
1938
+		$orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1939
+		$order       = $this->request->getRequestParam('order', 'DESC');
1940
+		$month_range = $this->request->getRequestParam('month_range');
1941
+		if ($month_range) {
1942
+			$pieces = explode(' ', $month_range, 3);
1943
+			// simulate the FIRST day of the month, that fixes issues for months like February
1944
+			// where PHP doesn't know what to assume for date.
1945
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1946
+			$month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1947
+			$year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1948
+		}
1949
+		$where  = [];
1950
+		$status = $this->request->getRequestParam('status');
1951
+		// determine what post_status our condition will have for the query.
1952
+		switch ($status) {
1953
+			case 'month':
1954
+			case 'today':
1955
+			case null:
1956
+			case 'all':
1957
+				break;
1958
+			case 'draft':
1959
+				$where['status'] = ['IN', ['draft', 'auto-draft']];
1960
+				break;
1961
+			default:
1962
+				$where['status'] = $status;
1963
+		}
1964
+		// categories? The default for all categories is -1
1965
+		$category = $this->request->getRequestParam('EVT_CAT', -1, DataType::INT);
1966
+		if ($category !== -1) {
1967
+			$where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1968
+			$where['Term_Taxonomy.term_id']  = $category;
1969
+		}
1970
+		// date where conditions
1971
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1972
+		if ($month_range) {
1973
+			$DateTime = new DateTime(
1974
+				$year_r . '-' . $month_r . '-01 00:00:00',
1975
+				new DateTimeZone('UTC')
1976
+			);
1977
+			$start    = $DateTime->getTimestamp();
1978
+			// set the datetime to be the end of the month
1979
+			$DateTime->setDate(
1980
+				$year_r,
1981
+				$month_r,
1982
+				$DateTime->format('t')
1983
+			)->setTime(23, 59, 59);
1984
+			$end                             = $DateTime->getTimestamp();
1985
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1986
+		} elseif ($status === 'today') {
1987
+			$DateTime                        =
1988
+				new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1989
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1990
+			$end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1991
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1992
+		} elseif ($status === 'month') {
1993
+			$now                             = date('Y-m-01');
1994
+			$DateTime                        =
1995
+				new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1996
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1997
+			$end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1998
+														->setTime(23, 59, 59)
1999
+														->format(implode(' ', $start_formats));
2000
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
2001
+		}
2002
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
2003
+			$where['EVT_wp_user'] = get_current_user_id();
2004
+		} else {
2005
+			if (! isset($where['status'])) {
2006
+				if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
2007
+					$where['OR'] = [
2008
+						'status*restrict_private' => ['!=', 'private'],
2009
+						'AND'                     => [
2010
+							'status*inclusive' => ['=', 'private'],
2011
+							'EVT_wp_user'      => get_current_user_id(),
2012
+						],
2013
+					];
2014
+				}
2015
+			}
2016
+		}
2017
+		$wp_user = $this->request->getRequestParam('EVT_wp_user', 0, DataType::INT);
2018
+		if (
2019
+			$wp_user
2020
+			&& $wp_user !== get_current_user_id()
2021
+			&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
2022
+		) {
2023
+			$where['EVT_wp_user'] = $wp_user;
2024
+		}
2025
+		// search query handling
2026
+		$search_term = $this->request->getRequestParam('s');
2027
+		if ($search_term) {
2028
+			$search_term = '%' . $search_term . '%';
2029
+			$where['OR'] = [
2030
+				'EVT_name'       => ['LIKE', $search_term],
2031
+				'EVT_desc'       => ['LIKE', $search_term],
2032
+				'EVT_short_desc' => ['LIKE', $search_term],
2033
+			];
2034
+		}
2035
+		// filter events by venue.
2036
+		$venue = $this->request->getRequestParam('venue', 0, DataType::INT);
2037
+		if ($venue) {
2038
+			$where['Venue.VNU_ID'] = $venue;
2039
+		}
2040
+		$request_params = $this->request->requestParams();
2041
+		$where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
2042
+		$query_params   = apply_filters(
2043
+			'FHEE__Events_Admin_Page__get_events__query_params',
2044
+			[
2045
+				$where,
2046
+				'limit'    => $limit,
2047
+				'order_by' => $orderby,
2048
+				'order'    => $order,
2049
+				'group_by' => 'EVT_ID',
2050
+			],
2051
+			$request_params
2052
+		);
2053
+
2054
+		// let's first check if we have special requests coming in.
2055
+		$active_status = $this->request->getRequestParam('active_status');
2056
+		if ($active_status) {
2057
+			switch ($active_status) {
2058
+				case 'upcoming':
2059
+					return $EEM_Event->get_upcoming_events($query_params, $count);
2060
+				case 'expired':
2061
+					return $EEM_Event->get_expired_events($query_params, $count);
2062
+				case 'active':
2063
+					return $EEM_Event->get_active_events($query_params, $count);
2064
+				case 'inactive':
2065
+					return $EEM_Event->get_inactive_events($query_params, $count);
2066
+			}
2067
+		}
2068
+
2069
+		return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * handling for WordPress CPT actions (trash, restore, delete)
2075
+	 *
2076
+	 * @param string $post_id
2077
+	 * @throws EE_Error
2078
+	 * @throws ReflectionException
2079
+	 */
2080
+	public function trash_cpt_item($post_id)
2081
+	{
2082
+		$this->request->setRequestParam('EVT_ID', $post_id);
2083
+		$this->_trash_or_restore_event('trash', false);
2084
+	}
2085
+
2086
+
2087
+	/**
2088
+	 * @param string $post_id
2089
+	 * @throws EE_Error
2090
+	 * @throws ReflectionException
2091
+	 */
2092
+	public function restore_cpt_item($post_id)
2093
+	{
2094
+		$this->request->setRequestParam('EVT_ID', $post_id);
2095
+		$this->_trash_or_restore_event('draft', false);
2096
+	}
2097
+
2098
+
2099
+	/**
2100
+	 * @param string $post_id
2101
+	 * @throws EE_Error
2102
+	 * @throws EE_Error
2103
+	 */
2104
+	public function delete_cpt_item($post_id)
2105
+	{
2106
+		throw new EE_Error(
2107
+			esc_html__(
2108
+				'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2109
+				'event_espresso'
2110
+			)
2111
+		);
2112
+		// $this->request->setRequestParam('EVT_ID', $post_id);
2113
+		// $this->_delete_event();
2114
+	}
2115
+
2116
+
2117
+	/**
2118
+	 * _trash_or_restore_event
2119
+	 *
2120
+	 * @access protected
2121
+	 * @param string $event_status
2122
+	 * @param bool   $redirect_after
2123
+	 * @throws EE_Error
2124
+	 * @throws EE_Error
2125
+	 * @throws ReflectionException
2126
+	 */
2127
+	protected function _trash_or_restore_event(string $event_status = 'trash', bool $redirect_after = true)
2128
+	{
2129
+		// determine the event id and set to array.
2130
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, DataType::INT);
2131
+		// loop thru events
2132
+		if ($EVT_ID) {
2133
+			// clean status
2134
+			$event_status = sanitize_key($event_status);
2135
+			// grab status
2136
+			if (! empty($event_status)) {
2137
+				$success = $this->_change_event_status($EVT_ID, $event_status);
2138
+			} else {
2139
+				$success = false;
2140
+				$msg     = esc_html__(
2141
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2142
+					'event_espresso'
2143
+				);
2144
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2145
+			}
2146
+		} else {
2147
+			$success = false;
2148
+			$msg     = esc_html__(
2149
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2150
+				'event_espresso'
2151
+			);
2152
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2153
+		}
2154
+		$action = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2155
+		if ($redirect_after) {
2156
+			$this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2157
+		}
2158
+	}
2159
+
2160
+
2161
+	/**
2162
+	 * _trash_or_restore_events
2163
+	 *
2164
+	 * @access protected
2165
+	 * @param string $event_status
2166
+	 * @return void
2167
+	 * @throws EE_Error
2168
+	 * @throws EE_Error
2169
+	 * @throws ReflectionException
2170
+	 */
2171
+	protected function _trash_or_restore_events(string $event_status = 'trash')
2172
+	{
2173
+		// clean status
2174
+		$event_status = sanitize_key($event_status);
2175
+		// grab status
2176
+		if (! empty($event_status)) {
2177
+			$success = true;
2178
+			// determine the event id and set to array.
2179
+			$EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2180
+			// loop thru events
2181
+			foreach ($EVT_IDs as $EVT_ID) {
2182
+				if ($EVT_ID = absint($EVT_ID)) {
2183
+					$results = $this->_change_event_status($EVT_ID, $event_status);
2184
+					$success = $results !== false ? $success : false;
2185
+				} else {
2186
+					$msg = sprintf(
2187
+						esc_html__(
2188
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2189
+							'event_espresso'
2190
+						),
2191
+						$EVT_ID
2192
+					);
2193
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2194
+					$success = false;
2195
+				}
2196
+			}
2197
+		} else {
2198
+			$success = false;
2199
+			$msg     = esc_html__(
2200
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2201
+				'event_espresso'
2202
+			);
2203
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2204
+		}
2205
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2206
+		$success = $success ? 2 : false;
2207
+		$action  = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2208
+		$this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2209
+	}
2210
+
2211
+
2212
+	/**
2213
+	 * @param int    $EVT_ID
2214
+	 * @param string $event_status
2215
+	 * @return bool
2216
+	 * @throws EE_Error
2217
+	 * @throws ReflectionException
2218
+	 */
2219
+	private function _change_event_status(int $EVT_ID = 0, string $event_status = ''): bool
2220
+	{
2221
+		// grab event id
2222
+		if (! $EVT_ID) {
2223
+			$msg = esc_html__(
2224
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2225
+				'event_espresso'
2226
+			);
2227
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2228
+			return false;
2229
+		}
2230
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2231
+		// clean status
2232
+		$event_status = sanitize_key($event_status);
2233
+		// grab status
2234
+		if (empty($event_status)) {
2235
+			$msg = esc_html__(
2236
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2237
+				'event_espresso'
2238
+			);
2239
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2240
+			return false;
2241
+		}
2242
+		// was event trashed or restored ?
2243
+		switch ($event_status) {
2244
+			case 'draft':
2245
+				$action = 'restored from the trash';
2246
+				$hook   = 'AHEE_event_restored_from_trash';
2247
+				break;
2248
+			case 'trash':
2249
+				$action = 'moved to the trash';
2250
+				$hook   = 'AHEE_event_moved_to_trash';
2251
+				break;
2252
+			default:
2253
+				$action = 'updated';
2254
+				$hook   = false;
2255
+		}
2256
+		// use class to change status
2257
+		$this->_cpt_model_obj->set_status($event_status);
2258
+		$success = $this->_cpt_model_obj->save();
2259
+		if (! $success) {
2260
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2261
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2262
+			return false;
2263
+		}
2264
+		if ($hook) {
2265
+			do_action($hook);
2266
+			// fake the action hook in EE_Soft_Delete_Base_Class::delete_or_restore()
2267
+			// because events side step that and it otherwise won't get called
2268
+			do_action(
2269
+				'AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after',
2270
+				$this->_cpt_model_obj,
2271
+				$hook === 'AHEE_event_moved_to_trash',
2272
+				$success
2273
+			);
2274
+		}
2275
+		return true;
2276
+	}
2277
+
2278
+
2279
+	/**
2280
+	 * @param array $event_ids
2281
+	 * @return array
2282
+	 * @since   4.10.23.p
2283
+	 */
2284
+	private function cleanEventIds(array $event_ids): array
2285
+	{
2286
+		return array_map('absint', $event_ids);
2287
+	}
2288
+
2289
+
2290
+	/**
2291
+	 * @return array
2292
+	 * @since   4.10.23.p
2293
+	 */
2294
+	private function getEventIdsFromRequest(): array
2295
+	{
2296
+		if ($this->request->requestParamIsSet('EVT_IDs')) {
2297
+			return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2298
+		} else {
2299
+			return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2300
+		}
2301
+	}
2302
+
2303
+
2304
+	/**
2305
+	 * @param bool $preview_delete
2306
+	 * @throws EE_Error
2307
+	 * @throws ReflectionException
2308
+	 */
2309
+	protected function _delete_event(bool $preview_delete = true)
2310
+	{
2311
+		$this->_delete_events($preview_delete);
2312
+	}
2313
+
2314
+
2315
+	/**
2316
+	 * Gets the tree traversal batch persister.
2317
+	 *
2318
+	 * @return NodeGroupDao
2319
+	 * @throws InvalidArgumentException
2320
+	 * @throws InvalidDataTypeException
2321
+	 * @throws InvalidInterfaceException
2322
+	 * @since 4.10.12.p
2323
+	 */
2324
+	protected function getModelObjNodeGroupPersister(): NodeGroupDao
2325
+	{
2326
+		if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2327
+			$this->model_obj_node_group_persister =
2328
+				$this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2329
+		}
2330
+		return $this->model_obj_node_group_persister;
2331
+	}
2332
+
2333
+
2334
+	/**
2335
+	 * @param bool $preview_delete
2336
+	 * @return void
2337
+	 * @throws EE_Error
2338
+	 * @throws ReflectionException
2339
+	 */
2340
+	protected function _delete_events(bool $preview_delete = true)
2341
+	{
2342
+		$event_ids = $this->getEventIdsFromRequest();
2343
+		if ($preview_delete) {
2344
+			$this->generateDeletionPreview($event_ids);
2345
+		} else {
2346
+			foreach ($event_ids as $event_id) {
2347
+				$event = EEM_Event::instance()->get_one_by_ID($event_id);
2348
+				if ($event instanceof EE_Event) {
2349
+					$event->delete_permanently();
2350
+				}
2351
+			}
2352
+		}
2353
+	}
2354
+
2355
+
2356
+	/**
2357
+	 * @param array $event_ids
2358
+	 */
2359
+	protected function generateDeletionPreview(array $event_ids)
2360
+	{
2361
+		$event_ids = $this->cleanEventIds($event_ids);
2362
+		// Set a code we can use to reference this deletion task in the batch jobs and preview page.
2363
+		$deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2364
+		$return_url        = EE_Admin_Page::add_query_args_and_nonce(
2365
+			[
2366
+				'action'            => 'preview_deletion',
2367
+				'deletion_job_code' => $deletion_job_code,
2368
+			],
2369
+			$this->_admin_base_url
2370
+		);
2371
+		EEH_URL::safeRedirectAndExit(
2372
+			EE_Admin_Page::add_query_args_and_nonce(
2373
+				[
2374
+					'page'              => EED_Batch::PAGE_SLUG,
2375
+					'batch'             => EED_Batch::batch_job,
2376
+					'EVT_IDs'           => $event_ids,
2377
+					'deletion_job_code' => $deletion_job_code,
2378
+					'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2379
+					'return_url'        => urlencode($return_url),
2380
+				],
2381
+				admin_url()
2382
+			)
2383
+		);
2384
+	}
2385
+
2386
+
2387
+	/**
2388
+	 * Checks for a POST submission
2389
+	 *
2390
+	 * @since 4.10.12.p
2391
+	 */
2392
+	protected function confirmDeletion()
2393
+	{
2394
+		$deletion_redirect_logic = $this->getLoader()->getShared(
2395
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'
2396
+		);
2397
+		$deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2398
+	}
2399
+
2400
+
2401
+	/**
2402
+	 * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2403
+	 *
2404
+	 * @throws EE_Error
2405
+	 * @since 4.10.12.p
2406
+	 */
2407
+	protected function previewDeletion()
2408
+	{
2409
+		$preview_deletion_logic = $this->getLoader()->getShared(
2410
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'
2411
+		);
2412
+		$this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2413
+		$this->display_admin_page_with_no_sidebar();
2414
+	}
2415
+
2416
+
2417
+	/**
2418
+	 * get total number of events
2419
+	 *
2420
+	 * @access public
2421
+	 * @return int
2422
+	 * @throws EE_Error
2423
+	 * @throws EE_Error
2424
+	 * @throws ReflectionException
2425
+	 */
2426
+	public function total_events(): int
2427
+	{
2428
+		return EEM_Event::instance()->count(
2429
+			['caps' => 'read_admin'],
2430
+			'EVT_ID',
2431
+			true
2432
+		);
2433
+	}
2434
+
2435
+
2436
+	/**
2437
+	 * get total number of draft events
2438
+	 *
2439
+	 * @access public
2440
+	 * @return int
2441
+	 * @throws EE_Error
2442
+	 * @throws EE_Error
2443
+	 * @throws ReflectionException
2444
+	 */
2445
+	public function total_events_draft(): int
2446
+	{
2447
+		return EEM_Event::instance()->count(
2448
+			[
2449
+				['status' => ['IN', ['draft', 'auto-draft']]],
2450
+				'caps' => 'read_admin',
2451
+			],
2452
+			'EVT_ID',
2453
+			true
2454
+		);
2455
+	}
2456
+
2457
+
2458
+	/**
2459
+	 * get total number of trashed events
2460
+	 *
2461
+	 * @access public
2462
+	 * @return int
2463
+	 * @throws EE_Error
2464
+	 * @throws EE_Error
2465
+	 * @throws ReflectionException
2466
+	 */
2467
+	public function total_trashed_events(): int
2468
+	{
2469
+		return EEM_Event::instance()->count(
2470
+			[
2471
+				['status' => 'trash'],
2472
+				'caps' => 'read_admin',
2473
+			],
2474
+			'EVT_ID',
2475
+			true
2476
+		);
2477
+	}
2478
+
2479
+
2480
+	/**
2481
+	 *    _default_event_settings
2482
+	 *    This generates the Default Settings Tab
2483
+	 *
2484
+	 * @return void
2485
+	 * @throws DomainException
2486
+	 * @throws EE_Error
2487
+	 * @throws InvalidArgumentException
2488
+	 * @throws InvalidDataTypeException
2489
+	 * @throws InvalidInterfaceException
2490
+	 */
2491
+	protected function _default_event_settings()
2492
+	{
2493
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2494
+		$this->_set_publish_post_box_vars();
2495
+		$this->_template_args['admin_page_content'] = EEH_HTML::div(
2496
+			$this->_default_event_settings_form()->get_html(),
2497
+			'',
2498
+			'padding'
2499
+		);
2500
+		$this->display_admin_page_with_sidebar();
2501
+	}
2502
+
2503
+
2504
+	/**
2505
+	 * Return the form for event settings.
2506
+	 *
2507
+	 * @return EE_Form_Section_Proper
2508
+	 * @throws EE_Error
2509
+	 */
2510
+	protected function _default_event_settings_form(): EE_Form_Section_Proper
2511
+	{
2512
+		$registration_config              = EE_Registry::instance()->CFG->registration;
2513
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2514
+		// exclude
2515
+			[
2516
+				EEM_Registration::status_id_cancelled,
2517
+				EEM_Registration::status_id_declined,
2518
+				EEM_Registration::status_id_incomplete,
2519
+				EEM_Registration::status_id_wait_list,
2520
+			],
2521
+			true
2522
+		);
2523
+		// setup Advanced Editor ???
2524
+		if (
2525
+			$this->raw_req_action === 'default_event_settings'
2526
+			|| $this->raw_req_action === 'update_default_event_settings'
2527
+		) {
2528
+			$this->advanced_editor_admin_form = $this->loader->getShared(AdvancedEditorAdminFormSection::class);
2529
+		}
2530
+		return new EE_Form_Section_Proper(
2531
+			[
2532
+				'name'            => 'update_default_event_settings',
2533
+				'html_id'         => 'update_default_event_settings',
2534
+				'html_class'      => 'form-table',
2535
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2536
+				'subsections'     => apply_filters(
2537
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2538
+					[
2539
+						'defaults_section_header' => new EE_Form_Section_HTML(
2540
+							EEH_HTML::h2(
2541
+								esc_html__('Default Settings', 'event_espresso'),
2542
+								'',
2543
+								'ee-admin-settings-hdr'
2544
+							)
2545
+						),
2546
+						'default_reg_status'      => new EE_Select_Input(
2547
+							$registration_stati_for_selection,
2548
+							[
2549
+								'default'         => isset($registration_config->default_STS_ID)
2550
+													 && array_key_exists(
2551
+														 $registration_config->default_STS_ID,
2552
+														 $registration_stati_for_selection
2553
+													 )
2554
+									? sanitize_text_field($registration_config->default_STS_ID)
2555
+									: EEM_Registration::status_id_pending_payment,
2556
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2557
+													 . EEH_Template::get_help_tab_link(
2558
+														 'default_settings_status_help_tab'
2559
+													 ),
2560
+								'html_help_text'  => esc_html__(
2561
+									'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.',
2562
+									'event_espresso'
2563
+								),
2564
+							]
2565
+						),
2566
+						'default_max_tickets'     => new EE_Integer_Input(
2567
+							[
2568
+								'default'         => $registration_config->default_maximum_number_of_tickets
2569
+													 ?? EEM_Event::get_default_additional_limit(),
2570
+								'html_label_text' => esc_html__(
2571
+									'Default Maximum Tickets Allowed Per Order:',
2572
+									'event_espresso'
2573
+								)
2574
+													 . EEH_Template::get_help_tab_link(
2575
+														 'default_maximum_tickets_help_tab"'
2576
+													 ),
2577
+								'html_help_text'  => esc_html__(
2578
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2579
+									'event_espresso'
2580
+								),
2581
+							]
2582
+						),
2583
+					]
2584
+				),
2585
+			]
2586
+		);
2587
+	}
2588
+
2589
+
2590
+	/**
2591
+	 * @return void
2592
+	 * @throws EE_Error
2593
+	 * @throws InvalidArgumentException
2594
+	 * @throws InvalidDataTypeException
2595
+	 * @throws InvalidInterfaceException
2596
+	 */
2597
+	protected function _update_default_event_settings()
2598
+	{
2599
+		$form = $this->_default_event_settings_form();
2600
+		if ($form->was_submitted()) {
2601
+			$form->receive_form_submission();
2602
+			if ($form->is_valid()) {
2603
+				$registration_config = EE_Registry::instance()->CFG->registration;
2604
+				$valid_data          = $form->valid_data();
2605
+				if (isset($valid_data['default_reg_status'])) {
2606
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2607
+				}
2608
+				if (isset($valid_data['default_max_tickets'])) {
2609
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2610
+				}
2611
+				do_action(
2612
+					'AHEE__Events_Admin_Page___update_default_event_settings',
2613
+					$valid_data,
2614
+					EE_Registry::instance()->CFG,
2615
+					$this
2616
+				);
2617
+				// update because data was valid!
2618
+				EE_Registry::instance()->CFG->update_espresso_config();
2619
+				EE_Error::overwrite_success();
2620
+				EE_Error::add_success(
2621
+					esc_html__('Default Event Settings were updated', 'event_espresso')
2622
+				);
2623
+			}
2624
+		}
2625
+		$this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2626
+	}
2627
+
2628
+
2629
+	/*************        Templates        *************
23 2630
      *
24
-     * @var EE_Event $_event
25
-     */
26
-    protected $_event;
27
-
28
-
29
-    /**
30
-     * This will hold the category object for category_details screen.
31
-     *
32
-     * @var stdClass $_category
33
-     */
34
-    protected $_category;
35
-
36
-
37
-    /**
38
-     * This will hold the event model instance
39
-     *
40
-     * @var EEM_Event $_event_model
41
-     */
42
-    protected $_event_model;
43
-
44
-
45
-    /**
46
-     * @var EE_Event
47
-     */
48
-    protected $_cpt_model_obj = false;
49
-
50
-
51
-    /**
52
-     * @var NodeGroupDao
53
-     */
54
-    protected $model_obj_node_group_persister;
55
-
56
-    /**
57
-     * @var AdvancedEditorAdminFormSection
58
-     */
59
-    protected $advanced_editor_admin_form;
60
-
61
-
62
-    /**
63
-     * Initialize page props for this admin page group.
64
-     */
65
-    protected function _init_page_props()
66
-    {
67
-        $this->page_slug        = EVENTS_PG_SLUG;
68
-        $this->page_label       = EVENTS_LABEL;
69
-        $this->_admin_base_url  = EVENTS_ADMIN_URL;
70
-        $this->_admin_base_path = EVENTS_ADMIN;
71
-        $this->_cpt_model_names = [
72
-            'create_new' => 'EEM_Event',
73
-            'edit'       => 'EEM_Event',
74
-        ];
75
-        $this->_cpt_edit_routes = [
76
-            'espresso_events' => 'edit',
77
-        ];
78
-        add_action(
79
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
80
-            [$this, 'verify_event_edit'],
81
-            10,
82
-            2
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     * Sets the ajax hooks used for this admin page group.
89
-     */
90
-    protected function _ajax_hooks()
91
-    {
92
-        add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
93
-    }
94
-
95
-
96
-    /**
97
-     * Sets the page properties for this admin page group.
98
-     */
99
-    protected function _define_page_props()
100
-    {
101
-        $event_id = $this->request->getRequestParam('post', 0, DataType::INT);
102
-        if ($event_id) {
103
-            $event_post = get_post($event_id);
104
-        }
105
-
106
-        $this->_admin_page_title = EVENTS_LABEL;
107
-        $this->_labels           = [
108
-            'buttons'      => [
109
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
110
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
111
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
112
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
113
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
114
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
115
-            ],
116
-            'editor_title' => [
117
-                'espresso_events' => isset($event_post) && $event_post instanceof WP_Post
118
-                    ? $event_post->post_title
119
-                    : esc_html__('Edit Event', 'event_espresso'),
120
-            ],
121
-            'publishbox'   => [
122
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
123
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
124
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
125
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
126
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
127
-            ],
128
-        ];
129
-    }
130
-
131
-
132
-    /**
133
-     * Sets the page routes property for this admin page group.
134
-     */
135
-    protected function _set_page_routes()
136
-    {
137
-        // load formatter helper
138
-        // load field generator helper
139
-        // is there a evt_id in the request?
140
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, DataType::INT);
141
-        $EVT_ID = $this->request->getRequestParam('post', $EVT_ID, DataType::INT);
142
-
143
-        $this->_page_routes = [
144
-            'default'                       => [
145
-                'func'       => [$this, '_events_overview_list_table'],
146
-                'capability' => 'ee_read_events',
147
-            ],
148
-            'create_new'                    => [
149
-                'func'       => [$this, '_create_new_cpt_item'],
150
-                'capability' => 'ee_edit_events',
151
-            ],
152
-            'edit'                          => [
153
-                'func'       => [$this, '_edit_cpt_item'],
154
-                'capability' => 'ee_edit_event',
155
-                'obj_id'     => $EVT_ID,
156
-            ],
157
-            'copy_event'                    => [
158
-                'func'       => [$this, '_copy_events'],
159
-                'capability' => 'ee_edit_event',
160
-                'obj_id'     => $EVT_ID,
161
-                'noheader'   => true,
162
-            ],
163
-            'trash_event'                   => [
164
-                'func'       => [$this, '_trash_or_restore_event'],
165
-                'args'       => ['event_status' => 'trash'],
166
-                'capability' => 'ee_delete_event',
167
-                'obj_id'     => $EVT_ID,
168
-                'noheader'   => true,
169
-            ],
170
-            'trash_events'                  => [
171
-                'func'       => [$this, '_trash_or_restore_events'],
172
-                'args'       => ['event_status' => 'trash'],
173
-                'capability' => 'ee_delete_events',
174
-                'noheader'   => true,
175
-            ],
176
-            'restore_event'                 => [
177
-                'func'       => [$this, '_trash_or_restore_event'],
178
-                'args'       => ['event_status' => 'draft'],
179
-                'capability' => 'ee_delete_event',
180
-                'obj_id'     => $EVT_ID,
181
-                'noheader'   => true,
182
-            ],
183
-            'restore_events'                => [
184
-                'func'       => [$this, '_trash_or_restore_events'],
185
-                'args'       => ['event_status' => 'draft'],
186
-                'capability' => 'ee_delete_events',
187
-                'noheader'   => true,
188
-            ],
189
-            'delete_event'                  => [
190
-                'func'       => [$this, '_delete_event'],
191
-                'capability' => 'ee_delete_event',
192
-                'obj_id'     => $EVT_ID,
193
-                'noheader'   => true,
194
-            ],
195
-            'delete_events'                 => [
196
-                'func'       => [$this, '_delete_events'],
197
-                'capability' => 'ee_delete_events',
198
-                'noheader'   => true,
199
-            ],
200
-            'view_report'                   => [
201
-                'func'       => [$this, '_view_report'],
202
-                'capability' => 'ee_edit_events',
203
-            ],
204
-            'default_event_settings'        => [
205
-                'func'       => [$this, '_default_event_settings'],
206
-                'capability' => 'manage_options',
207
-            ],
208
-            'update_default_event_settings' => [
209
-                'func'       => [$this, '_update_default_event_settings'],
210
-                'capability' => 'manage_options',
211
-                'noheader'   => true,
212
-            ],
213
-            'template_settings'             => [
214
-                'func'       => [$this, '_template_settings'],
215
-                'capability' => 'manage_options',
216
-            ],
217
-            // event category tab related
218
-            'add_category'                  => [
219
-                'func'       => [$this, '_category_details'],
220
-                'capability' => 'ee_edit_event_category',
221
-                'args'       => ['view' => 'add'],
222
-            ],
223
-            'edit_category'                 => [
224
-                'func'       => [$this, '_category_details'],
225
-                'capability' => 'ee_edit_event_category',
226
-                'args'       => ['view' => 'edit'],
227
-            ],
228
-            'delete_categories'             => [
229
-                'func'       => [$this, '_delete_categories'],
230
-                'capability' => 'ee_delete_event_category',
231
-                'noheader'   => true,
232
-            ],
233
-            'delete_category'               => [
234
-                'func'       => [$this, '_delete_categories'],
235
-                'capability' => 'ee_delete_event_category',
236
-                'noheader'   => true,
237
-            ],
238
-            'insert_category'               => [
239
-                'func'       => [$this, '_insert_or_update_category'],
240
-                'args'       => ['new_category' => true],
241
-                'capability' => 'ee_edit_event_category',
242
-                'noheader'   => true,
243
-            ],
244
-            'update_category'               => [
245
-                'func'       => [$this, '_insert_or_update_category'],
246
-                'args'       => ['new_category' => false],
247
-                'capability' => 'ee_edit_event_category',
248
-                'noheader'   => true,
249
-            ],
250
-            'category_list'                 => [
251
-                'func'       => [$this, '_category_list_table'],
252
-                'capability' => 'ee_manage_event_categories',
253
-            ],
254
-            'preview_deletion'              => [
255
-                'func'       => [$this, 'previewDeletion'],
256
-                'capability' => 'ee_delete_events',
257
-            ],
258
-            'confirm_deletion'              => [
259
-                'func'       => [$this, 'confirmDeletion'],
260
-                'capability' => 'ee_delete_events',
261
-                'noheader'   => true,
262
-            ],
263
-        ];
264
-    }
265
-
266
-
267
-    /**
268
-     * Set the _page_config property for this admin page group.
269
-     */
270
-    protected function _set_page_config()
271
-    {
272
-        $post_id            = $this->request->getRequestParam('post', 0, DataType::INT);
273
-        $EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
274
-        $this->_page_config = [
275
-            'default'                => [
276
-                'nav'           => [
277
-                    'label' => esc_html__('Overview', 'event_espresso'),
278
-                    'icon'  => 'dashicons-list-view',
279
-                    'order' => 10,
280
-                ],
281
-                'list_table'    => 'Events_Admin_List_Table',
282
-                'help_tabs'     => [
283
-                    'events_overview_help_tab'                       => [
284
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
285
-                        'filename' => 'events_overview',
286
-                    ],
287
-                    'events_overview_table_column_headings_help_tab' => [
288
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
289
-                        'filename' => 'events_overview_table_column_headings',
290
-                    ],
291
-                    'events_overview_filters_help_tab'               => [
292
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
293
-                        'filename' => 'events_overview_filters',
294
-                    ],
295
-                    'events_overview_view_help_tab'                  => [
296
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
297
-                        'filename' => 'events_overview_views',
298
-                    ],
299
-                    'events_overview_other_help_tab'                 => [
300
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
301
-                        'filename' => 'events_overview_other',
302
-                    ],
303
-                ],
304
-                'require_nonce' => false,
305
-            ],
306
-            'create_new'             => [
307
-                'nav'           => [
308
-                    'label'      => esc_html__('Add New Event', 'event_espresso'),
309
-                    'icon'       => 'dashicons-plus-alt',
310
-                    'order'      => 15,
311
-                    'persistent' => false,
312
-                ],
313
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
314
-                'help_tabs'     => [
315
-                    'event_editor_help_tab'                            => [
316
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
317
-                        'filename' => 'event_editor',
318
-                    ],
319
-                    'event_editor_title_richtexteditor_help_tab'       => [
320
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
321
-                        'filename' => 'event_editor_title_richtexteditor',
322
-                    ],
323
-                    'event_editor_venue_details_help_tab'              => [
324
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
325
-                        'filename' => 'event_editor_venue_details',
326
-                    ],
327
-                    'event_editor_event_datetimes_help_tab'            => [
328
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
329
-                        'filename' => 'event_editor_event_datetimes',
330
-                    ],
331
-                    'event_editor_event_tickets_help_tab'              => [
332
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
333
-                        'filename' => 'event_editor_event_tickets',
334
-                    ],
335
-                    'event_editor_event_registration_options_help_tab' => [
336
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
337
-                        'filename' => 'event_editor_event_registration_options',
338
-                    ],
339
-                    'event_editor_tags_categories_help_tab'            => [
340
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
341
-                        'filename' => 'event_editor_tags_categories',
342
-                    ],
343
-                    'event_editor_questions_registrants_help_tab'      => [
344
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
345
-                        'filename' => 'event_editor_questions_registrants',
346
-                    ],
347
-                    'event_editor_save_new_event_help_tab'             => [
348
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
349
-                        'filename' => 'event_editor_save_new_event',
350
-                    ],
351
-                    'event_editor_other_help_tab'                      => [
352
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
353
-                        'filename' => 'event_editor_other',
354
-                    ],
355
-                ],
356
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
357
-                'require_nonce' => false,
358
-            ],
359
-            'edit'                   => [
360
-                'nav'           => [
361
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
362
-                    'icon'       => 'dashicons-edit',
363
-                    'order'      => 15,
364
-                    'persistent' => false,
365
-                    'url'        => $post_id
366
-                        ? EE_Admin_Page::add_query_args_and_nonce(
367
-                            ['post' => $post_id, 'action' => 'edit'],
368
-                            $this->_current_page_view_url
369
-                        )
370
-                        : $this->_admin_base_url,
371
-                ],
372
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
373
-                'help_tabs'     => [
374
-                    'event_editor_help_tab'                            => [
375
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
376
-                        'filename' => 'event_editor',
377
-                    ],
378
-                    'event_editor_title_richtexteditor_help_tab'       => [
379
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
380
-                        'filename' => 'event_editor_title_richtexteditor',
381
-                    ],
382
-                    'event_editor_venue_details_help_tab'              => [
383
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
384
-                        'filename' => 'event_editor_venue_details',
385
-                    ],
386
-                    'event_editor_event_datetimes_help_tab'            => [
387
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
388
-                        'filename' => 'event_editor_event_datetimes',
389
-                    ],
390
-                    'event_editor_event_tickets_help_tab'              => [
391
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
392
-                        'filename' => 'event_editor_event_tickets',
393
-                    ],
394
-                    'event_editor_event_registration_options_help_tab' => [
395
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
396
-                        'filename' => 'event_editor_event_registration_options',
397
-                    ],
398
-                    'event_editor_tags_categories_help_tab'            => [
399
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
400
-                        'filename' => 'event_editor_tags_categories',
401
-                    ],
402
-                    'event_editor_questions_registrants_help_tab'      => [
403
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
404
-                        'filename' => 'event_editor_questions_registrants',
405
-                    ],
406
-                    'event_editor_save_new_event_help_tab'             => [
407
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
408
-                        'filename' => 'event_editor_save_new_event',
409
-                    ],
410
-                    'event_editor_other_help_tab'                      => [
411
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
412
-                        'filename' => 'event_editor_other',
413
-                    ],
414
-                ],
415
-                'require_nonce' => false,
416
-            ],
417
-            'default_event_settings' => [
418
-                'nav'           => [
419
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
420
-                    'icon'  => 'dashicons-admin-generic',
421
-                    'order' => 40,
422
-                ],
423
-                'metaboxes'     => array_merge(['_publish_post_box'], $this->_default_espresso_metaboxes),
424
-                'labels'        => [
425
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
426
-                ],
427
-                'help_tabs'     => [
428
-                    'default_settings_help_tab'        => [
429
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
430
-                        'filename' => 'events_default_settings',
431
-                    ],
432
-                    'default_settings_status_help_tab' => [
433
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
434
-                        'filename' => 'events_default_settings_status',
435
-                    ],
436
-                    'default_maximum_tickets_help_tab' => [
437
-                        'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
438
-                        'filename' => 'events_default_settings_max_tickets',
439
-                    ],
440
-                ],
441
-                'require_nonce' => false,
442
-            ],
443
-            // template settings
444
-            'template_settings'      => [
445
-                'nav'           => [
446
-                    'label' => esc_html__('Templates', 'event_espresso'),
447
-                    'icon'  => 'dashicons-layout',
448
-                    'order' => 30,
449
-                ],
450
-                'metaboxes'     => $this->_default_espresso_metaboxes,
451
-                'help_tabs'     => [
452
-                    'general_settings_templates_help_tab' => [
453
-                        'title'    => esc_html__('Templates', 'event_espresso'),
454
-                        'filename' => 'general_settings_templates',
455
-                    ],
456
-                ],
457
-                'require_nonce' => false,
458
-            ],
459
-            // event category stuff
460
-            'add_category'           => [
461
-                'nav'           => [
462
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
463
-                    'icon'       => 'dashicons-plus-alt',
464
-                    'order'      => 25,
465
-                    'persistent' => false,
466
-                ],
467
-                'help_tabs'     => [
468
-                    'add_category_help_tab' => [
469
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
470
-                        'filename' => 'events_add_category',
471
-                    ],
472
-                ],
473
-                'metaboxes'     => ['_publish_post_box'],
474
-                'require_nonce' => false,
475
-            ],
476
-            'edit_category'          => [
477
-                'nav'           => [
478
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
479
-                    'icon'       => 'dashicons-edit',
480
-                    'order'      => 25,
481
-                    'persistent' => false,
482
-                    'url'        => $EVT_CAT_ID
483
-                        ? add_query_arg(
484
-                            ['EVT_CAT_ID' => $EVT_CAT_ID],
485
-                            $this->_current_page_view_url
486
-                        )
487
-                        : $this->_admin_base_url,
488
-                ],
489
-                'help_tabs'     => [
490
-                    'edit_category_help_tab' => [
491
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
492
-                        'filename' => 'events_edit_category',
493
-                    ],
494
-                ],
495
-                'metaboxes'     => ['_publish_post_box'],
496
-                'require_nonce' => false,
497
-            ],
498
-            'category_list'          => [
499
-                'nav'           => [
500
-                    'label' => esc_html__('Categories', 'event_espresso'),
501
-                    'icon'  => 'dashicons-networking',
502
-                    'order' => 20,
503
-                ],
504
-                'list_table'    => 'Event_Categories_Admin_List_Table',
505
-                'help_tabs'     => [
506
-                    'events_categories_help_tab'                       => [
507
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
508
-                        'filename' => 'events_categories',
509
-                    ],
510
-                    'events_categories_table_column_headings_help_tab' => [
511
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'events_categories_table_column_headings',
513
-                    ],
514
-                    'events_categories_view_help_tab'                  => [
515
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
516
-                        'filename' => 'events_categories_views',
517
-                    ],
518
-                    'events_categories_other_help_tab'                 => [
519
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
520
-                        'filename' => 'events_categories_other',
521
-                    ],
522
-                ],
523
-                'metaboxes'     => $this->_default_espresso_metaboxes,
524
-                'require_nonce' => false,
525
-            ],
526
-            'preview_deletion'       => [
527
-                'nav'           => [
528
-                    'label'      => esc_html__('Preview Deletion', 'event_espresso'),
529
-                    'icon'       => 'dashicons-remove',
530
-                    'order'      => 15,
531
-                    'persistent' => false,
532
-                    'url'        => '',
533
-                ],
534
-                'require_nonce' => false,
535
-            ],
536
-        ];
537
-    }
538
-
539
-
540
-    /**
541
-     * Used to register any global screen options if necessary for every route in this admin page group.
542
-     */
543
-    protected function _add_screen_options()
544
-    {
545
-    }
546
-
547
-
548
-    /**
549
-     * Implementing the screen options for the 'default' route.
550
-     *
551
-     * @throws InvalidArgumentException
552
-     * @throws InvalidDataTypeException
553
-     * @throws InvalidInterfaceException
554
-     */
555
-    protected function _add_screen_options_default()
556
-    {
557
-        $this->_per_page_screen_option();
558
-    }
559
-
560
-
561
-    /**
562
-     * Implementing screen options for the category list route.
563
-     *
564
-     * @throws InvalidArgumentException
565
-     * @throws InvalidDataTypeException
566
-     * @throws InvalidInterfaceException
567
-     */
568
-    protected function _add_screen_options_category_list()
569
-    {
570
-        $page_title              = $this->_admin_page_title;
571
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
572
-        $this->_per_page_screen_option();
573
-        $this->_admin_page_title = $page_title;
574
-    }
575
-
576
-
577
-    /**
578
-     * Used to register any global feature pointers for the admin page group.
579
-     */
580
-    protected function _add_feature_pointers()
581
-    {
582
-    }
583
-
584
-
585
-    /**
586
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
587
-     */
588
-    public function load_scripts_styles()
589
-    {
590
-        wp_register_style(
591
-            'events-admin-css',
592
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
593
-            [],
594
-            EVENT_ESPRESSO_VERSION
595
-        );
596
-        wp_register_style(
597
-            'ee-cat-admin',
598
-            EVENTS_ASSETS_URL . 'ee-cat-admin.css',
599
-            [],
600
-            EVENT_ESPRESSO_VERSION
601
-        );
602
-        wp_enqueue_style('events-admin-css');
603
-        wp_enqueue_style('ee-cat-admin');
604
-        // scripts
605
-        wp_register_script(
606
-            'event_editor_js',
607
-            EVENTS_ASSETS_URL . 'event_editor.js',
608
-            ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
609
-            EVENT_ESPRESSO_VERSION,
610
-            true
611
-        );
612
-    }
613
-
614
-
615
-    /**
616
-     * Enqueuing scripts and styles specific to this view
617
-     */
618
-    public function load_scripts_styles_create_new()
619
-    {
620
-        $this->load_scripts_styles_edit();
621
-    }
622
-
623
-
624
-    /**
625
-     * Enqueuing scripts and styles specific to this view
626
-     */
627
-    public function load_scripts_styles_edit()
628
-    {
629
-        // styles
630
-        wp_enqueue_style('espresso-ui-theme');
631
-        wp_register_style(
632
-            'event-editor-css',
633
-            EVENTS_ASSETS_URL . 'event-editor.css',
634
-            ['ee-admin-css'],
635
-            EVENT_ESPRESSO_VERSION
636
-        );
637
-        wp_enqueue_style('event-editor-css');
638
-        // scripts
639
-        if (! $this->admin_config->useAdvancedEditor()) {
640
-            wp_register_script(
641
-                'event-datetime-metabox',
642
-                EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
643
-                ['event_editor_js', 'ee-datepicker'],
644
-                EVENT_ESPRESSO_VERSION
645
-            );
646
-            wp_enqueue_script('event-datetime-metabox');
647
-        }
648
-    }
649
-
650
-
651
-    /**
652
-     * Populating the _views property for the category list table view.
653
-     */
654
-    protected function _set_list_table_views_category_list()
655
-    {
656
-        $this->_views = [
657
-            'all' => [
658
-                'slug'        => 'all',
659
-                'label'       => esc_html__('All', 'event_espresso'),
660
-                'count'       => 0,
661
-                'bulk_action' => [
662
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
663
-                ],
664
-            ],
665
-        ];
666
-    }
667
-
668
-
669
-    /**
670
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
671
-     */
672
-    public function admin_init()
673
-    {
674
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
675
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
676
-            'event_espresso'
677
-        );
678
-    }
679
-
680
-
681
-    /**
682
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
683
-     * group.
684
-     */
685
-    public function admin_notices()
686
-    {
687
-    }
688
-
689
-
690
-    /**
691
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
692
-     * this admin page group.
693
-     */
694
-    public function admin_footer_scripts()
695
-    {
696
-    }
697
-
698
-
699
-    /**
700
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
701
-     * warning (via EE_Error::add_error());
702
-     *
703
-     * @param EE_Event|null $event Event object
704
-     * @param string        $req_type
705
-     * @return void
706
-     * @throws EE_Error
707
-     * @throws ReflectionException
708
-     */
709
-    public function verify_event_edit(?EE_Base_Class $event = null, string $req_type = '')
710
-    {
711
-        // don't need to do this when processing
712
-        if (! empty($req_type)) {
713
-            return;
714
-        }
715
-        // no event?
716
-        if (! $event instanceof EE_Event) {
717
-            $event = $this->_cpt_model_obj;
718
-        }
719
-        // STILL no event?
720
-        if (! $event instanceof EE_Event) {
721
-            return;
722
-        }
723
-        // don't need to keep calling this
724
-        remove_action(
725
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
726
-            [$this, 'verify_event_edit']
727
-        );
728
-        $orig_status = $event->status();
729
-        // first check if event is active.
730
-        if (
731
-            $orig_status === EEM_Event::cancelled
732
-            || $orig_status === EEM_Event::postponed
733
-            || $event->is_expired()
734
-            || $event->is_inactive()
735
-        ) {
736
-            return;
737
-        }
738
-        // made it here so it IS active... next check that any of the tickets are sold.
739
-        if ($event->is_sold_out(true)) {
740
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
741
-                EE_Error::add_attention(
742
-                    sprintf(
743
-                        esc_html__(
744
-                            '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.',
745
-                            'event_espresso'
746
-                        ),
747
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
748
-                    )
749
-                );
750
-            }
751
-            return;
752
-        }
753
-        if ($orig_status === EEM_Event::sold_out) {
754
-            EE_Error::add_attention(
755
-                sprintf(
756
-                    esc_html__(
757
-                        '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.',
758
-                        'event_espresso'
759
-                    ),
760
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
761
-                )
762
-            );
763
-        }
764
-        // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
765
-        if (! $event->tickets_on_sale()) {
766
-            return;
767
-        }
768
-        // made it here so show warning
769
-        $this->_edit_event_warning();
770
-    }
771
-
772
-
773
-    /**
774
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
775
-     * When needed, hook this into a EE_Error::add_error() notice.
776
-     *
777
-     * @access protected
778
-     * @return void
779
-     */
780
-    protected function _edit_event_warning()
781
-    {
782
-        // we don't want to add warnings during these requests
783
-        if ($this->request->getRequestParam('action') === 'editpost') {
784
-            return;
785
-        }
786
-        EE_Error::add_attention(
787
-            sprintf(
788
-                esc_html__(
789
-                    'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
790
-                    'event_espresso'
791
-                ),
792
-                '<a class="espresso-help-tab-lnk ee-help-tab-link">',
793
-                '</a>'
794
-            )
795
-        );
796
-    }
797
-
798
-
799
-    /**
800
-     * When a user is creating a new event, notify them if they haven't set their timezone.
801
-     * Otherwise, do the normal logic
802
-     *
803
-     * @return void
804
-     * @throws EE_Error
805
-     * @throws InvalidArgumentException
806
-     * @throws InvalidDataTypeException
807
-     * @throws InvalidInterfaceException
808
-     * @throws ReflectionException
809
-     */
810
-    protected function _create_new_cpt_item()
811
-    {
812
-        $has_timezone_string = get_option('timezone_string');
813
-        // only nag them about setting their timezone if it's their first event, and they haven't already done it
814
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
815
-            EE_Error::add_attention(
816
-                sprintf(
817
-                    esc_html__(
818
-                        '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',
819
-                        'event_espresso'
820
-                    ),
821
-                    '<br>',
822
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
823
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
824
-                    . '</select>',
825
-                    '<button class="button button--secondary timezone-submit">',
826
-                    '</button><span class="spinner"></span>'
827
-                ),
828
-                __FILE__,
829
-                __FUNCTION__,
830
-                __LINE__
831
-            );
832
-        }
833
-        parent::_create_new_cpt_item();
834
-    }
835
-
836
-
837
-    /**
838
-     * Sets the _views property for the default route in this admin page group.
839
-     */
840
-    protected function _set_list_table_views_default()
841
-    {
842
-        $this->_views = [
843
-            'all'   => [
844
-                'slug'        => 'all',
845
-                'label'       => esc_html__('View All Events', 'event_espresso'),
846
-                'count'       => 0,
847
-                'bulk_action' => [
848
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
849
-                ],
850
-            ],
851
-            'draft' => [
852
-                'slug'        => 'draft',
853
-                'label'       => esc_html__('Draft', 'event_espresso'),
854
-                'count'       => 0,
855
-                'bulk_action' => [
856
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
857
-                ],
858
-            ],
859
-        ];
860
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
861
-            $this->_views['trash'] = [
862
-                'slug'        => 'trash',
863
-                'label'       => esc_html__('Trash', 'event_espresso'),
864
-                'count'       => 0,
865
-                'bulk_action' => [
866
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
867
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
868
-                ],
869
-            ];
870
-        }
871
-    }
872
-
873
-
874
-    /**
875
-     * Provides the legend item array for the default list table view.
876
-     *
877
-     * @return array
878
-     * @throws EE_Error
879
-     * @throws EE_Error
880
-     */
881
-    protected function _event_legend_items(): array
882
-    {
883
-        $items    = [
884
-            'view_details'   => [
885
-                'class' => 'dashicons dashicons-visibility',
886
-                'desc'  => esc_html__('View Event', 'event_espresso'),
887
-            ],
888
-            'edit_event'     => [
889
-                'class' => 'dashicons dashicons-calendar-alt',
890
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
891
-            ],
892
-            'view_attendees' => [
893
-                'class' => 'dashicons dashicons-groups',
894
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
895
-            ],
896
-        ];
897
-        $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
898
-        $statuses = [
899
-            'sold_out_status'  => [
900
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::sold_out,
901
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
902
-            ],
903
-            'active_status'    => [
904
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::active,
905
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
906
-            ],
907
-            'upcoming_status'  => [
908
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::upcoming,
909
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
910
-            ],
911
-            'postponed_status' => [
912
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::postponed,
913
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
914
-            ],
915
-            'cancelled_status' => [
916
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::cancelled,
917
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
918
-            ],
919
-            'expired_status'   => [
920
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::expired,
921
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
922
-            ],
923
-            'inactive_status'  => [
924
-                'class' => 'ee-status-legend ee-status-bg--' . EE_Datetime::inactive,
925
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
926
-            ],
927
-        ];
928
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
929
-        return array_merge($items, $statuses);
930
-    }
931
-
932
-
933
-    /**
934
-     * @return EEM_Event
935
-     * @throws EE_Error
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidDataTypeException
938
-     * @throws InvalidInterfaceException
939
-     * @throws ReflectionException
940
-     */
941
-    private function _event_model(): EEM_Event
942
-    {
943
-        if (! $this->_event_model instanceof EEM_Event) {
944
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
945
-        }
946
-        return $this->_event_model;
947
-    }
948
-
949
-
950
-    /**
951
-     * Adds extra buttons to the WP CPT permalink field row.
952
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
953
-     *
954
-     * @param string      $return    the current html
955
-     * @param int         $id        the post id for the page
956
-     * @param string|null $new_title What the title is
957
-     * @param string|null $new_slug  what the slug is
958
-     * @return string            The new html string for the permalink area
959
-     * @deprecated $VID:$
960
-     * @see TicketSelectorShortcodeButton::addButton
961
-     */
962
-    public function extra_permalink_field_buttons(
963
-        string $return,
964
-        int $id,
965
-        ?string $new_title,
966
-        ?string $new_slug
967
-    ): string {
968
-        return TicketSelectorShortcodeButton::addButton($return, $id, $new_title, $new_slug);
969
-    }
970
-
971
-
972
-    /**
973
-     * _events_overview_list_table
974
-     * This contains the logic for showing the events_overview list
975
-     *
976
-     * @access protected
977
-     * @return void
978
-     * @throws DomainException
979
-     * @throws EE_Error
980
-     * @throws InvalidArgumentException
981
-     * @throws InvalidDataTypeException
982
-     * @throws InvalidInterfaceException
983
-     */
984
-    protected function _events_overview_list_table()
985
-    {
986
-        $after_list_table = [];
987
-        $links_html       = EEH_HTML::div('', '', 'ee-admin-section ee-layout-stack');
988
-        $links_html       .= EEH_HTML::h3(esc_html__('Links', 'event_espresso'));
989
-        $links_html       .= EEH_HTML::div(
990
-            EEH_Template::get_button_or_link(
991
-                get_post_type_archive_link('espresso_events'),
992
-                esc_html__('View Event Archive Page', 'event_espresso'),
993
-                'button button--small button--secondary'
994
-            ),
995
-            '',
996
-            'ee-admin-button-row ee-admin-button-row--align-start'
997
-        );
998
-        $links_html       .= EEH_HTML::divx();
999
-
1000
-        $after_list_table['view_event_list_button'] = $links_html;
1001
-
1002
-        $after_list_table['legend'] = $this->_display_legend($this->_event_legend_items());
1003
-        $this->_admin_page_title    .= ' ' . $this->get_action_link_or_button(
1004
-            'create_new',
1005
-            'add',
1006
-            [],
1007
-            'add-new-h2'
1008
-        );
1009
-
1010
-        $this->_template_args['after_list_table'] = array_merge(
1011
-            (array) $this->_template_args['after_list_table'],
1012
-            $after_list_table
1013
-        );
1014
-        $this->display_admin_list_table_page_with_no_sidebar();
1015
-    }
1016
-
1017
-
1018
-    /**
1019
-     * this allows for extra misc actions in the default WP publish box
1020
-     *
1021
-     * @return void
1022
-     * @throws DomainException
1023
-     * @throws EE_Error
1024
-     * @throws InvalidArgumentException
1025
-     * @throws InvalidDataTypeException
1026
-     * @throws InvalidInterfaceException
1027
-     * @throws ReflectionException
1028
-     */
1029
-    public function extra_misc_actions_publish_box()
1030
-    {
1031
-        $this->_generate_publish_box_extra_content();
1032
-    }
1033
-
1034
-
1035
-    /**
1036
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1037
-     * saved.
1038
-     * Typically you would use this to save any additional data.
1039
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
1040
-     * ALSO very important.  When a post transitions from scheduled to published,
1041
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1042
-     * other meta saves. So MAKE sure that you handle this accordingly.
1043
-     *
1044
-     * @access protected
1045
-     * @abstract
1046
-     * @param string  $post_id The ID of the cpt that was saved (so you can link relationally)
1047
-     * @param WP_Post $post    The post object of the cpt that was saved.
1048
-     * @return void
1049
-     * @throws EE_Error
1050
-     * @throws InvalidArgumentException
1051
-     * @throws InvalidDataTypeException
1052
-     * @throws InvalidInterfaceException
1053
-     * @throws ReflectionException
1054
-     */
1055
-    protected function _insert_update_cpt_item($post_id, $post)
1056
-    {
1057
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1058
-            // get out we're not processing an event save.
1059
-            return;
1060
-        }
1061
-        $event_values = [
1062
-            'EVT_member_only'     => $this->request->getRequestParam('member_only', false, DataType::BOOL),
1063
-            'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, DataType::BOOL),
1064
-            'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1065
-        ];
1066
-        // check if the new EDTR reg options meta box is being used, and if so, don't run updates for legacy version
1067
-        if (! $this->admin_config->useAdvancedEditor() || ! $this->feature->allowed('use_reg_options_meta_box')) {
1068
-            $event_values['EVT_display_ticket_selector']     = $this->request->getRequestParam(
1069
-                'display_ticket_selector',
1070
-                false,
1071
-                'bool'
1072
-            );
1073
-            $event_values['EVT_additional_limit']            = min(
1074
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1075
-                $this->request->getRequestParam(
1076
-                    'additional_limit',
1077
-                    EEM_Event::get_default_additional_limit(),
1078
-                    'int'
1079
-                )
1080
-            );
1081
-            $event_values['EVT_default_registration_status'] = $this->request->getRequestParam(
1082
-                'EVT_default_registration_status',
1083
-                EE_Registry::instance()->CFG->registration->default_STS_ID
1084
-            );
1085
-
1086
-            $event_values['EVT_external_URL'] = $this->request->getRequestParam('externalURL');
1087
-            $event_values['EVT_phone']        = $this->request->getRequestParam('event_phone');
1088
-            $event_values['EVT_display_desc'] = $this->request->getRequestParam('display_desc', false, DataType::BOOL);
1089
-        } elseif ($post instanceof WP_Post) {
1090
-            $event_values['EVT_name'] = $post->post_title;
1091
-            $event_values['EVT_desc'] = $post->post_content;
1092
-        }
1093
-        // update event
1094
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1095
-        // get event_object for other metaboxes...
1096
-        // though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1097
-        // i have to setup where conditions to override the filters in the model
1098
-        // that filter out auto-draft and inherit statuses so we GET the inherit id!
1099
-        /** @var EE_Event $event */
1100
-        $event = $this->_event_model()->get_one(
1101
-            [
1102
-                [
1103
-                    $this->_event_model()->primary_key_name() => $post_id,
1104
-                    'OR'                                      => [
1105
-                        'status'   => $post->post_status,
1106
-                        // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1107
-                        // but the returned object here has a status of "publish", so use the original post status as well
1108
-                        'status*1' => $this->request->getRequestParam('original_post_status'),
1109
-                    ],
1110
-                ],
1111
-            ]
1112
-        );
1113
-
1114
-        // the following are default callbacks for event attachment updates
1115
-        // that can be overridden by caffeinated functionality and/or addons.
1116
-        $event_update_callbacks = [];
1117
-        if (! $this->admin_config->useAdvancedEditor()) {
1118
-            $event_update_callbacks['_default_venue_update']   = [$this, '_default_venue_update'];
1119
-            $event_update_callbacks['_default_tickets_update'] = [$this, '_default_tickets_update'];
1120
-        }
1121
-        $event_update_callbacks = apply_filters(
1122
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1123
-            $event_update_callbacks
1124
-        );
1125
-
1126
-        $att_success = true;
1127
-        foreach ($event_update_callbacks as $e_callback) {
1128
-            $_success = is_callable($e_callback)
1129
-                ? $e_callback($event, $this->request->requestParams())
1130
-                : false;
1131
-            // if ANY of these updates fail then we want the appropriate global error message
1132
-            $att_success = $_success !== false ? $att_success : false;
1133
-        }
1134
-        // any errors?
1135
-        if ($success && $att_success === false) {
1136
-            EE_Error::add_error(
1137
-                esc_html__(
1138
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1139
-                    'event_espresso'
1140
-                ),
1141
-                __FILE__,
1142
-                __FUNCTION__,
1143
-                __LINE__
1144
-            );
1145
-        } elseif ($success === false) {
1146
-            EE_Error::add_error(
1147
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1148
-                __FILE__,
1149
-                __FUNCTION__,
1150
-                __LINE__
1151
-            );
1152
-        }
1153
-    }
1154
-
1155
-
1156
-    /**
1157
-     * @param int $post_id
1158
-     * @param int $revision_id
1159
-     * @throws EE_Error
1160
-     * @throws EE_Error
1161
-     * @throws ReflectionException
1162
-     * @see parent::restore_item()
1163
-     */
1164
-    protected function _restore_cpt_item(int $post_id, int $revision_id)
1165
-    {
1166
-        // copy existing event meta to new post
1167
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1168
-        if ($post_evt instanceof EE_Event) {
1169
-            // meta revision restore
1170
-            $post_evt->restore_revision($revision_id);
1171
-            // related objs restore
1172
-            $post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1173
-        }
1174
-    }
1175
-
1176
-
1177
-    /**
1178
-     * Attach the venue to the Event
1179
-     *
1180
-     * @param EE_Event $event Event Object to add the venue to
1181
-     * @param array    $data  The request data from the form
1182
-     * @return bool           Success or fail.
1183
-     * @throws EE_Error
1184
-     * @throws ReflectionException
1185
-     */
1186
-    protected function _default_venue_update(EE_Event $event, array $data): bool
1187
-    {
1188
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1189
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1190
-        $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1191
-        // very important.  If we don't have a venue name...
1192
-        // then we'll get out because not necessary to create empty venue
1193
-        if (empty($data['venue_title'])) {
1194
-            return false;
1195
-        }
1196
-        $venue_array = [
1197
-            'VNU_wp_user'         => $event->get('EVT_wp_user'),
1198
-            'VNU_name'            => $data['venue_title'],
1199
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1200
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1201
-            'VNU_short_desc'      => ! empty($data['venue_short_description'])
1202
-                ? $data['venue_short_description']
1203
-                : null,
1204
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1205
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1206
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1207
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1208
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1209
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1210
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1211
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1212
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1213
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1214
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1215
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1216
-            'status'              => 'publish',
1217
-        ];
1218
-        // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1219
-        if (! empty($venue_id)) {
1220
-            $update_where  = [$venue_model->primary_key_name() => $venue_id];
1221
-            $rows_affected = $venue_model->update($venue_array, [$update_where]);
1222
-            // we've gotta make sure that the venue is always attached to a revision..
1223
-            // add_relation_to should take care of making sure that the relation is already present.
1224
-            $event->_add_relation_to($venue_id, 'Venue');
1225
-            return $rows_affected > 0;
1226
-        }
1227
-        // we insert the venue
1228
-        $venue_id = $venue_model->insert($venue_array);
1229
-        $event->_add_relation_to($venue_id, 'Venue');
1230
-        return ! empty($venue_id);
1231
-        // when we have the ancestor come in it's already been handled by the revision save.
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1237
-     *
1238
-     * @param EE_Event $event The Event object we're attaching data to
1239
-     * @param array    $data  The request data from the form
1240
-     * @return array
1241
-     * @throws EE_Error
1242
-     * @throws ReflectionException
1243
-     * @throws Exception
1244
-     */
1245
-    protected function _default_tickets_update(EE_Event $event, array $data): array
1246
-    {
1247
-        if ($this->admin_config->useAdvancedEditor()) {
1248
-            return [];
1249
-        }
1250
-        $datetime       = null;
1251
-        $saved_tickets  = [];
1252
-        $event_timezone = $event->get_timezone();
1253
-        $date_formats   = ['Y-m-d', 'h:i a'];
1254
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1255
-            // trim all values to ensure any excess whitespace is removed.
1256
-            $datetime_data                = array_map('trim', $datetime_data);
1257
-            $datetime_data['DTT_EVT_end'] =
1258
-                isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1259
-                    ? $datetime_data['DTT_EVT_end']
1260
-                    : $datetime_data['DTT_EVT_start'];
1261
-            $datetime_values              = [
1262
-                'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1263
-                'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1264
-                'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1265
-                'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1266
-                'DTT_order'     => $row,
1267
-            ];
1268
-            // if we have an id then let's get existing object first and then set the new values.
1269
-            //  Otherwise we instantiate a new object for save.
1270
-            if (! empty($datetime_data['DTT_ID'])) {
1271
-                $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1272
-                if (! $datetime instanceof EE_Datetime) {
1273
-                    throw new RuntimeException(
1274
-                        sprintf(
1275
-                            esc_html__(
1276
-                                'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1277
-                                'event_espresso'
1278
-                            ),
1279
-                            $datetime_data['DTT_ID']
1280
-                        )
1281
-                    );
1282
-                }
1283
-                $datetime->set_date_format($date_formats[0]);
1284
-                $datetime->set_time_format($date_formats[1]);
1285
-                foreach ($datetime_values as $field => $value) {
1286
-                    $datetime->set($field, $value);
1287
-                }
1288
-            } else {
1289
-                $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1290
-            }
1291
-            if (! $datetime instanceof EE_Datetime) {
1292
-                throw new RuntimeException(
1293
-                    sprintf(
1294
-                        esc_html__(
1295
-                            'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1296
-                            'event_espresso'
1297
-                        ),
1298
-                        print_r($datetime_values, true)
1299
-                    )
1300
-                );
1301
-            }
1302
-            // before going any further make sure our dates are setup correctly
1303
-            // so that the end date is always equal or greater than the start date.
1304
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1305
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1306
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1307
-            }
1308
-            $datetime->save();
1309
-            $event->_add_relation_to($datetime, 'Datetime');
1310
-        }
1311
-        // no datetimes get deleted so we don't do any of that logic here.
1312
-        // update tickets next
1313
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1314
-
1315
-        // set up some default start and end dates in case those are not present in the incoming data
1316
-        $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1317
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1318
-        // use the start date of the first datetime for the end date
1319
-        $first_datetime   = $event->first_datetime();
1320
-        $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1321
-
1322
-        // now process the incoming data
1323
-        foreach ($data['edit_tickets'] as $row => $ticket_data) {
1324
-            $update_prices = false;
1325
-            $ticket_price  = $data['edit_prices'][ $row ][1]['PRC_amount'] ?? 0;
1326
-            // trim inputs to ensure any excess whitespace is removed.
1327
-            $ticket_data   = array_map('trim', $ticket_data);
1328
-            $ticket_values = [
1329
-                'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1330
-                'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1331
-                'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1332
-                'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1333
-                'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1334
-                    ? $ticket_data['TKT_start_date']
1335
-                    : $default_start_date,
1336
-                'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1337
-                    ? $ticket_data['TKT_end_date']
1338
-                    : $default_end_date,
1339
-                'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1340
-                                     || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1341
-                    ? $ticket_data['TKT_qty']
1342
-                    : EE_INF,
1343
-                'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1344
-                                     || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1345
-                    ? $ticket_data['TKT_uses']
1346
-                    : EE_INF,
1347
-                'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1348
-                'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1349
-                'TKT_order'       => $ticket_data['TKT_order'] ?? $row,
1350
-                'TKT_price'       => $ticket_price,
1351
-                'TKT_row'         => $row,
1352
-            ];
1353
-            // if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1354
-            // which means in turn that the prices will become new prices as well.
1355
-            if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1356
-                $ticket_values['TKT_ID']         = 0;
1357
-                $ticket_values['TKT_is_default'] = 0;
1358
-                $update_prices                   = true;
1359
-            }
1360
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
1361
-            // we actually do our saves ahead of adding any relations because its entirely possible that this
1362
-            // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1363
-            // keep in mind that if the ticket has been sold (and we have changed pricing information),
1364
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1365
-            if (! empty($ticket_data['TKT_ID'])) {
1366
-                $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1367
-                if (! $existing_ticket instanceof EE_Ticket) {
1368
-                    throw new RuntimeException(
1369
-                        sprintf(
1370
-                            esc_html__(
1371
-                                'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1372
-                                'event_espresso'
1373
-                            ),
1374
-                            $ticket_data['TKT_ID']
1375
-                        )
1376
-                    );
1377
-                }
1378
-                $ticket_sold = $existing_ticket->count_related(
1379
-                    'Registration',
1380
-                    [
1381
-                            [
1382
-                                'STS_ID' => [
1383
-                                    'NOT IN',
1384
-                                    [EEM_Registration::status_id_incomplete],
1385
-                                ],
1386
-                            ],
1387
-                        ]
1388
-                ) > 0;
1389
-                // let's just check the total price for the existing ticket and determine if it matches the new total price.
1390
-                // if they are different then we create a new ticket (if $ticket_sold)
1391
-                // if they aren't different then we go ahead and modify existing ticket.
1392
-                $create_new_ticket = $ticket_sold
1393
-                                     && $ticket_price !== $existing_ticket->price()
1394
-                                     && ! $existing_ticket->deleted();
1395
-                $existing_ticket->set_date_format($date_formats[0]);
1396
-                $existing_ticket->set_time_format($date_formats[1]);
1397
-                // set new values
1398
-                foreach ($ticket_values as $field => $value) {
1399
-                    if ($field == 'TKT_qty') {
1400
-                        $existing_ticket->set_qty($value);
1401
-                    } elseif ($field == 'TKT_price') {
1402
-                        $existing_ticket->set('TKT_price', $ticket_price);
1403
-                    } else {
1404
-                        $existing_ticket->set($field, $value);
1405
-                    }
1406
-                }
1407
-                $ticket = $existing_ticket;
1408
-                // if $create_new_ticket is false then we can safely update the existing ticket.
1409
-                //  Otherwise we have to create a new ticket.
1410
-                if ($create_new_ticket) {
1411
-                    // archive the old ticket first
1412
-                    $existing_ticket->set('TKT_deleted', 1);
1413
-                    $existing_ticket->save();
1414
-                    // make sure this ticket is still recorded in our $saved_tickets
1415
-                    // so we don't run it through the regular trash routine.
1416
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1417
-                    // create new ticket that's a copy of the existing except,
1418
-                    // (a new id of course and not archived) AND has the new TKT_price associated with it.
1419
-                    $new_ticket = clone $existing_ticket;
1420
-                    $new_ticket->set('TKT_ID', 0);
1421
-                    $new_ticket->set('TKT_deleted', 0);
1422
-                    $new_ticket->set('TKT_sold', 0);
1423
-                    // now we need to make sure that $new prices are created as well and attached to new ticket.
1424
-                    $update_prices = true;
1425
-                    $ticket        = $new_ticket;
1426
-                }
1427
-            } else {
1428
-                // no TKT_id so a new ticket
1429
-                $ticket_values['TKT_price'] = $ticket_price;
1430
-                $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1431
-                $update_prices              = true;
1432
-            }
1433
-            if (! $ticket instanceof EE_Ticket) {
1434
-                throw new RuntimeException(
1435
-                    sprintf(
1436
-                        esc_html__(
1437
-                            'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1438
-                            'event_espresso'
1439
-                        ),
1440
-                        print_r($ticket_values, true)
1441
-                    )
1442
-                );
1443
-            }
1444
-            // cap ticket qty by datetime reg limits
1445
-            $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1446
-            // update ticket.
1447
-            $ticket->save();
1448
-            // before going any further make sure our dates are setup correctly
1449
-            // so that the end date is always equal or greater than the start date.
1450
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1451
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1452
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1453
-                $ticket->save();
1454
-            }
1455
-            // initially let's add the ticket to the datetime
1456
-            $datetime->_add_relation_to($ticket, 'Ticket');
1457
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1458
-            // add prices to ticket
1459
-            $prices_data = isset($data['edit_prices'][ $row ]) && is_array($data['edit_prices'][ $row ])
1460
-                ? $data['edit_prices'][ $row ]
1461
-                : [];
1462
-            $this->_add_prices_to_ticket($prices_data, $ticket, $update_prices);
1463
-        }
1464
-        // however now we need to handle permanently deleting tickets via the ui.
1465
-        // Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1466
-        // However, it does allow for deleting tickets that have no tickets sold,
1467
-        // in which case we want to get rid of permanently because there is no need to save in db.
1468
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? [] : $old_tickets;
1469
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1470
-        foreach ($tickets_removed as $id) {
1471
-            $id = absint($id);
1472
-            // get the ticket for this id
1473
-            $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1474
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1475
-                continue;
1476
-            }
1477
-            // need to get all the related datetimes on this ticket and remove from every single one of them
1478
-            // (remember this process can ONLY kick off if there are NO tickets sold)
1479
-            $related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1480
-            foreach ($related_datetimes as $related_datetime) {
1481
-                $ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1482
-            }
1483
-            // need to do the same for prices (except these prices can also be deleted because again,
1484
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1485
-            $ticket_to_remove->delete_related_permanently('Price');
1486
-            // finally let's delete this ticket
1487
-            // (which should not be blocked at this point b/c we've removed all our relationships)
1488
-            $ticket_to_remove->delete_permanently();
1489
-        }
1490
-        return [$datetime, $saved_tickets];
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * This attaches a list of given prices to a ticket.
1496
-     * Note we dont' have to worry about ever removing relationships (or archiving prices)
1497
-     * because if there is a change in price information on a ticket, a new ticket is created anyways
1498
-     * so the archived ticket will retain the old price info and prices are automatically "archived" via the ticket.
1499
-     *
1500
-     * @access  private
1501
-     * @param array     $prices_data Array of prices from the form.
1502
-     * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1503
-     * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1504
-     * @return  void
1505
-     * @throws EE_Error
1506
-     * @throws ReflectionException
1507
-     */
1508
-    private function _add_prices_to_ticket(array $prices_data, EE_Ticket $ticket, bool $new_prices = false)
1509
-    {
1510
-        $timezone = $ticket->get_timezone();
1511
-        foreach ($prices_data as $row => $price_data) {
1512
-            $price_values = [
1513
-                'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1514
-                'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1515
-                'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1516
-                'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1517
-                'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1518
-                'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1519
-                'PRC_order'      => $row,
1520
-            ];
1521
-            if ($new_prices || empty($price_values['PRC_ID'])) {
1522
-                $price_values['PRC_ID'] = 0;
1523
-                $price                  = EE_Price::new_instance($price_values, $timezone);
1524
-            } else {
1525
-                $price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1526
-                // update this price with new values
1527
-                foreach ($price_values as $field => $new_price) {
1528
-                    $price->set($field, $new_price);
1529
-                }
1530
-            }
1531
-            if (! $price instanceof EE_Price) {
1532
-                throw new RuntimeException(
1533
-                    sprintf(
1534
-                        esc_html__(
1535
-                            'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1536
-                            'event_espresso'
1537
-                        ),
1538
-                        print_r($price_values, true)
1539
-                    )
1540
-                );
1541
-            }
1542
-            $price->save();
1543
-            $ticket->_add_relation_to($price, 'Price');
1544
-        }
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * Add in our autosave ajax handlers
1550
-     *
1551
-     */
1552
-    protected function _ee_autosave_create_new()
1553
-    {
1554
-    }
1555
-
1556
-
1557
-    /**
1558
-     * More autosave handlers.
1559
-     */
1560
-    protected function _ee_autosave_edit()
1561
-    {
1562
-    }
1563
-
1564
-
1565
-    /**
1566
-     * @throws EE_Error
1567
-     * @throws ReflectionException
1568
-     */
1569
-    private function _generate_publish_box_extra_content()
1570
-    {
1571
-        // load formatter helper
1572
-        // args for getting related registrations
1573
-        $approved_query_args        = [
1574
-            [
1575
-                'REG_deleted' => 0,
1576
-                'STS_ID'      => EEM_Registration::status_id_approved,
1577
-            ],
1578
-        ];
1579
-        $not_approved_query_args    = [
1580
-            [
1581
-                'REG_deleted' => 0,
1582
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1583
-            ],
1584
-        ];
1585
-        $pending_payment_query_args = [
1586
-            [
1587
-                'REG_deleted' => 0,
1588
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1589
-            ],
1590
-        ];
1591
-        // publish box
1592
-        $publish_box_extra_args = [
1593
-            'view_approved_reg_url'        => add_query_arg(
1594
-                [
1595
-                    'action'      => 'default',
1596
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1597
-                    '_reg_status' => EEM_Registration::status_id_approved,
1598
-                    'use_filters' => true,
1599
-                ],
1600
-                REG_ADMIN_URL
1601
-            ),
1602
-            'view_not_approved_reg_url'    => add_query_arg(
1603
-                [
1604
-                    'action'      => 'default',
1605
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1606
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1607
-                    'use_filters' => true,
1608
-                ],
1609
-                REG_ADMIN_URL
1610
-            ),
1611
-            'view_pending_payment_reg_url' => add_query_arg(
1612
-                [
1613
-                    'action'      => 'default',
1614
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1615
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1616
-                    'use_filters' => true,
1617
-                ],
1618
-                REG_ADMIN_URL
1619
-            ),
1620
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1621
-                'Registration',
1622
-                $approved_query_args
1623
-            ),
1624
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1625
-                'Registration',
1626
-                $not_approved_query_args
1627
-            ),
1628
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1629
-                'Registration',
1630
-                $pending_payment_query_args
1631
-            ),
1632
-            'misc_pub_section_class'       => apply_filters(
1633
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1634
-                'misc-pub-section'
1635
-            ),
1636
-        ];
1637
-        ob_start();
1638
-        do_action(
1639
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1640
-            $this->_cpt_model_obj
1641
-        );
1642
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1643
-        // load template
1644
-        EEH_Template::display_template(
1645
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1646
-            $publish_box_extra_args
1647
-        );
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * @return EE_Event
1653
-     */
1654
-    public function get_event_object()
1655
-    {
1656
-        return $this->_cpt_model_obj;
1657
-    }
1658
-
1659
-
1660
-
1661
-
1662
-    /** METABOXES * */
1663
-    /**
1664
-     * _register_event_editor_meta_boxes
1665
-     * add all metaboxes related to the event_editor
1666
-     *
1667
-     * @return void
1668
-     * @throws EE_Error
1669
-     * @throws ReflectionException
1670
-     */
1671
-    protected function _register_event_editor_meta_boxes()
1672
-    {
1673
-        $this->verify_cpt_object();
1674
-        $use_advanced_editor = $this->admin_config->useAdvancedEditor();
1675
-        // check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
1676
-        if (! $use_advanced_editor || ! $this->feature->allowed('use_reg_options_meta_box')) {
1677
-            $this->addMetaBox(
1678
-                'espresso_event_editor_event_options',
1679
-                esc_html__('Event Registration Options', 'event_espresso'),
1680
-                [$this, 'registration_options_meta_box'],
1681
-                $this->page_slug,
1682
-                'side'
1683
-            );
1684
-        }
1685
-        if (! $use_advanced_editor) {
1686
-            $this->addMetaBox(
1687
-                'espresso_event_editor_tickets',
1688
-                esc_html__('Event Datetime & Ticket', 'event_espresso'),
1689
-                [$this, 'ticket_metabox'],
1690
-                $this->page_slug,
1691
-                'normal',
1692
-                'high'
1693
-            );
1694
-        } elseif ($this->feature->allowed('use_reg_options_meta_box')) {
1695
-            add_action(
1696
-                'add_meta_boxes_espresso_events',
1697
-                function () {
1698
-                    global $current_screen;
1699
-                    remove_meta_box('authordiv', $current_screen, 'normal');
1700
-                },
1701
-                99
1702
-            );
1703
-        }
1704
-        // NOTE: if you're looking for other metaboxes in here,
1705
-        // where a metabox has a related management page in the admin
1706
-        // you will find it setup in the related management page's "_Hooks" file.
1707
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1708
-    }
1709
-
1710
-
1711
-    /**
1712
-     * @throws DomainException
1713
-     * @throws EE_Error
1714
-     * @throws ReflectionException
1715
-     */
1716
-    public function ticket_metabox()
1717
-    {
1718
-        $existing_datetime_ids = $existing_ticket_ids = [];
1719
-        // defaults for template args
1720
-        $template_args = [
1721
-            'ticket_rows'       => '',
1722
-            'total_ticket_rows' => 1,
1723
-            'trash_icon'        => 'dashicons dashicons-lock',
1724
-            'disabled'          => '',
1725
-        ];
1726
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1727
-        /**
1728
-         * 1. Start with retrieving Datetimes
1729
-         * 2. Fore each datetime get related tickets
1730
-         * 3. For each ticket get related prices
1731
-         */
1732
-        /** @var EEM_Datetime $datetime_model */
1733
-        $datetime_model = EE_Registry::instance()->load_model('Datetime');
1734
-        /** @var EEM_Ticket $datetime_model */
1735
-        $ticket_model = EE_Registry::instance()->load_model('Ticket');
1736
-        $times        = $datetime_model->get_all_event_dates($event_id);
1737
-        /** @type EE_Datetime $first_datetime */
1738
-        $first_datetime = reset($times);
1739
-        // do we get related tickets?
1740
-        if (
1741
-            $first_datetime instanceof EE_Datetime
1742
-            && $first_datetime->ID() !== 0
1743
-        ) {
1744
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1745
-            $template_args['time']   = $first_datetime;
1746
-            $related_tickets         = $first_datetime->tickets(
1747
-                [
1748
-                    ['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1749
-                    'default_where_conditions' => 'none',
1750
-                ]
1751
-            );
1752
-            if (! empty($related_tickets)) {
1753
-                $template_args['total_ticket_rows'] = count($related_tickets);
1754
-                $row                                = 0;
1755
-                foreach ($related_tickets as $ticket) {
1756
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1757
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1758
-                    $row++;
1759
-                }
1760
-            } else {
1761
-                $template_args['total_ticket_rows'] = 1;
1762
-                /** @type EE_Ticket $ticket */
1763
-                $ticket                       = $ticket_model->create_default_object();
1764
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1765
-            }
1766
-        } else {
1767
-            $template_args['time'] = $times[0];
1768
-            /** @type EE_Ticket[] $tickets */
1769
-            $tickets                      = $ticket_model->get_all_default_tickets();
1770
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1771
-            // NOTE: we're just sending the first default row
1772
-            // (decaf can't manage default tickets so this should be sufficient);
1773
-        }
1774
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1775
-            'event_editor_event_datetimes_help_tab'
1776
-        );
1777
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1778
-        $template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1779
-        $template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1780
-        $template_args['ticket_js_structure']      = $this->_get_ticket_row(
1781
-            $ticket_model->create_default_object(),
1782
-            true
1783
-        );
1784
-        $template                                  = apply_filters(
1785
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1786
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1787
-        );
1788
-        EEH_Template::display_template($template, $template_args);
1789
-    }
1790
-
1791
-
1792
-    /**
1793
-     * Setup an individual ticket form for the decaf event editor page
1794
-     *
1795
-     * @access private
1796
-     * @param EE_Ticket $ticket   the ticket object
1797
-     * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1798
-     * @param int       $row
1799
-     * @return string generated html for the ticket row.
1800
-     * @throws EE_Error
1801
-     * @throws ReflectionException
1802
-     */
1803
-    private function _get_ticket_row(EE_Ticket $ticket, bool $skeleton = false, int $row = 0): string
1804
-    {
1805
-        $template_args = [
1806
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1807
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1808
-                : '',
1809
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1810
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1811
-            'TKT_name'            => $ticket->get('TKT_name'),
1812
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1813
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1814
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1815
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1816
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1817
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1818
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1819
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1820
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'dashicons dashicons-lock',
1821
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1822
-                : ' disabled=disabled',
1823
-        ];
1824
-        $price         = $ticket->ID() !== 0
1825
-            ? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1826
-            : null;
1827
-        $price         = $price instanceof EE_Price
1828
-            ? $price
1829
-            : EEM_Price::instance()->create_default_object();
1830
-        $price_args    = [
1831
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1832
-            'PRC_amount'            => $price->get('PRC_amount'),
1833
-            'PRT_ID'                => $price->get('PRT_ID'),
1834
-            'PRC_ID'                => $price->get('PRC_ID'),
1835
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1836
-        ];
1837
-        // make sure we have default start and end dates if skeleton
1838
-        // handle rows that should NOT be empty
1839
-        if (empty($template_args['TKT_start_date'])) {
1840
-            // if empty then the start date will be now.
1841
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1842
-        }
1843
-        if (empty($template_args['TKT_end_date'])) {
1844
-            // get the earliest datetime (if present);
1845
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1846
-                ? $this->_cpt_model_obj->get_first_related(
1847
-                    'Datetime',
1848
-                    ['order_by' => ['DTT_EVT_start' => 'ASC']]
1849
-                )
1850
-                : null;
1851
-            $template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1852
-                ? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1853
-                : date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1854
-        }
1855
-        $template_args = array_merge($template_args, $price_args);
1856
-        $template      = apply_filters(
1857
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1858
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1859
-            $ticket
1860
-        );
1861
-        return EEH_Template::display_template($template, $template_args, true);
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * @throws EE_Error
1867
-     * @throws ReflectionException
1868
-     */
1869
-    public function registration_options_meta_box()
1870
-    {
1871
-        $yes_no_values             = [
1872
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1873
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1874
-        ];
1875
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1876
-            [
1877
-                EEM_Registration::status_id_cancelled,
1878
-                EEM_Registration::status_id_declined,
1879
-                EEM_Registration::status_id_incomplete,
1880
-            ],
1881
-            true
1882
-        );
1883
-        // $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1884
-        $template_args['_event']                          = $this->_cpt_model_obj;
1885
-        $template_args['event']                           = $this->_cpt_model_obj;
1886
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1887
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1888
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1889
-            'default_reg_status',
1890
-            $default_reg_status_values,
1891
-            $this->_cpt_model_obj->default_registration_status()
1892
-        );
1893
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1894
-            'display_desc',
1895
-            $yes_no_values,
1896
-            $this->_cpt_model_obj->display_description()
1897
-        );
1898
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1899
-            'display_ticket_selector',
1900
-            $yes_no_values,
1901
-            $this->_cpt_model_obj->display_ticket_selector(),
1902
-            '',
1903
-            '',
1904
-            false
1905
-        );
1906
-        $template_args['additional_registration_options'] = apply_filters(
1907
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1908
-            '',
1909
-            $template_args,
1910
-            $yes_no_values,
1911
-            $default_reg_status_values
1912
-        );
1913
-        EEH_Template::display_template(
1914
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1915
-            $template_args
1916
-        );
1917
-    }
1918
-
1919
-
1920
-    /**
1921
-     * _get_events()
1922
-     * This method simply returns all the events (for the given _view and paging)
1923
-     *
1924
-     * @access public
1925
-     * @param int  $per_page     count of items per page (20 default);
1926
-     * @param int  $current_page what is the current page being viewed.
1927
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1928
-     *                           If FALSE then we return an array of event objects
1929
-     *                           that match the given _view and paging parameters.
1930
-     * @return array|int         an array of event objects or a count of them.
1931
-     * @throws Exception
1932
-     */
1933
-    public function get_events(int $per_page = 10, int $current_page = 1, bool $count = false)
1934
-    {
1935
-        $EEM_Event   = $this->_event_model();
1936
-        $offset      = ($current_page - 1) * $per_page;
1937
-        $limit       = $count ? null : $offset . ',' . $per_page;
1938
-        $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1939
-        $order       = $this->request->getRequestParam('order', 'DESC');
1940
-        $month_range = $this->request->getRequestParam('month_range');
1941
-        if ($month_range) {
1942
-            $pieces = explode(' ', $month_range, 3);
1943
-            // simulate the FIRST day of the month, that fixes issues for months like February
1944
-            // where PHP doesn't know what to assume for date.
1945
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1946
-            $month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1947
-            $year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1948
-        }
1949
-        $where  = [];
1950
-        $status = $this->request->getRequestParam('status');
1951
-        // determine what post_status our condition will have for the query.
1952
-        switch ($status) {
1953
-            case 'month':
1954
-            case 'today':
1955
-            case null:
1956
-            case 'all':
1957
-                break;
1958
-            case 'draft':
1959
-                $where['status'] = ['IN', ['draft', 'auto-draft']];
1960
-                break;
1961
-            default:
1962
-                $where['status'] = $status;
1963
-        }
1964
-        // categories? The default for all categories is -1
1965
-        $category = $this->request->getRequestParam('EVT_CAT', -1, DataType::INT);
1966
-        if ($category !== -1) {
1967
-            $where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1968
-            $where['Term_Taxonomy.term_id']  = $category;
1969
-        }
1970
-        // date where conditions
1971
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1972
-        if ($month_range) {
1973
-            $DateTime = new DateTime(
1974
-                $year_r . '-' . $month_r . '-01 00:00:00',
1975
-                new DateTimeZone('UTC')
1976
-            );
1977
-            $start    = $DateTime->getTimestamp();
1978
-            // set the datetime to be the end of the month
1979
-            $DateTime->setDate(
1980
-                $year_r,
1981
-                $month_r,
1982
-                $DateTime->format('t')
1983
-            )->setTime(23, 59, 59);
1984
-            $end                             = $DateTime->getTimestamp();
1985
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1986
-        } elseif ($status === 'today') {
1987
-            $DateTime                        =
1988
-                new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1989
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1990
-            $end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1991
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1992
-        } elseif ($status === 'month') {
1993
-            $now                             = date('Y-m-01');
1994
-            $DateTime                        =
1995
-                new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1996
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1997
-            $end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1998
-                                                        ->setTime(23, 59, 59)
1999
-                                                        ->format(implode(' ', $start_formats));
2000
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
2001
-        }
2002
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
2003
-            $where['EVT_wp_user'] = get_current_user_id();
2004
-        } else {
2005
-            if (! isset($where['status'])) {
2006
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
2007
-                    $where['OR'] = [
2008
-                        'status*restrict_private' => ['!=', 'private'],
2009
-                        'AND'                     => [
2010
-                            'status*inclusive' => ['=', 'private'],
2011
-                            'EVT_wp_user'      => get_current_user_id(),
2012
-                        ],
2013
-                    ];
2014
-                }
2015
-            }
2016
-        }
2017
-        $wp_user = $this->request->getRequestParam('EVT_wp_user', 0, DataType::INT);
2018
-        if (
2019
-            $wp_user
2020
-            && $wp_user !== get_current_user_id()
2021
-            && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
2022
-        ) {
2023
-            $where['EVT_wp_user'] = $wp_user;
2024
-        }
2025
-        // search query handling
2026
-        $search_term = $this->request->getRequestParam('s');
2027
-        if ($search_term) {
2028
-            $search_term = '%' . $search_term . '%';
2029
-            $where['OR'] = [
2030
-                'EVT_name'       => ['LIKE', $search_term],
2031
-                'EVT_desc'       => ['LIKE', $search_term],
2032
-                'EVT_short_desc' => ['LIKE', $search_term],
2033
-            ];
2034
-        }
2035
-        // filter events by venue.
2036
-        $venue = $this->request->getRequestParam('venue', 0, DataType::INT);
2037
-        if ($venue) {
2038
-            $where['Venue.VNU_ID'] = $venue;
2039
-        }
2040
-        $request_params = $this->request->requestParams();
2041
-        $where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
2042
-        $query_params   = apply_filters(
2043
-            'FHEE__Events_Admin_Page__get_events__query_params',
2044
-            [
2045
-                $where,
2046
-                'limit'    => $limit,
2047
-                'order_by' => $orderby,
2048
-                'order'    => $order,
2049
-                'group_by' => 'EVT_ID',
2050
-            ],
2051
-            $request_params
2052
-        );
2053
-
2054
-        // let's first check if we have special requests coming in.
2055
-        $active_status = $this->request->getRequestParam('active_status');
2056
-        if ($active_status) {
2057
-            switch ($active_status) {
2058
-                case 'upcoming':
2059
-                    return $EEM_Event->get_upcoming_events($query_params, $count);
2060
-                case 'expired':
2061
-                    return $EEM_Event->get_expired_events($query_params, $count);
2062
-                case 'active':
2063
-                    return $EEM_Event->get_active_events($query_params, $count);
2064
-                case 'inactive':
2065
-                    return $EEM_Event->get_inactive_events($query_params, $count);
2066
-            }
2067
-        }
2068
-
2069
-        return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * handling for WordPress CPT actions (trash, restore, delete)
2075
-     *
2076
-     * @param string $post_id
2077
-     * @throws EE_Error
2078
-     * @throws ReflectionException
2079
-     */
2080
-    public function trash_cpt_item($post_id)
2081
-    {
2082
-        $this->request->setRequestParam('EVT_ID', $post_id);
2083
-        $this->_trash_or_restore_event('trash', false);
2084
-    }
2085
-
2086
-
2087
-    /**
2088
-     * @param string $post_id
2089
-     * @throws EE_Error
2090
-     * @throws ReflectionException
2091
-     */
2092
-    public function restore_cpt_item($post_id)
2093
-    {
2094
-        $this->request->setRequestParam('EVT_ID', $post_id);
2095
-        $this->_trash_or_restore_event('draft', false);
2096
-    }
2097
-
2098
-
2099
-    /**
2100
-     * @param string $post_id
2101
-     * @throws EE_Error
2102
-     * @throws EE_Error
2103
-     */
2104
-    public function delete_cpt_item($post_id)
2105
-    {
2106
-        throw new EE_Error(
2107
-            esc_html__(
2108
-                'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2109
-                'event_espresso'
2110
-            )
2111
-        );
2112
-        // $this->request->setRequestParam('EVT_ID', $post_id);
2113
-        // $this->_delete_event();
2114
-    }
2115
-
2116
-
2117
-    /**
2118
-     * _trash_or_restore_event
2119
-     *
2120
-     * @access protected
2121
-     * @param string $event_status
2122
-     * @param bool   $redirect_after
2123
-     * @throws EE_Error
2124
-     * @throws EE_Error
2125
-     * @throws ReflectionException
2126
-     */
2127
-    protected function _trash_or_restore_event(string $event_status = 'trash', bool $redirect_after = true)
2128
-    {
2129
-        // determine the event id and set to array.
2130
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, DataType::INT);
2131
-        // loop thru events
2132
-        if ($EVT_ID) {
2133
-            // clean status
2134
-            $event_status = sanitize_key($event_status);
2135
-            // grab status
2136
-            if (! empty($event_status)) {
2137
-                $success = $this->_change_event_status($EVT_ID, $event_status);
2138
-            } else {
2139
-                $success = false;
2140
-                $msg     = esc_html__(
2141
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2142
-                    'event_espresso'
2143
-                );
2144
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2145
-            }
2146
-        } else {
2147
-            $success = false;
2148
-            $msg     = esc_html__(
2149
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2150
-                'event_espresso'
2151
-            );
2152
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2153
-        }
2154
-        $action = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2155
-        if ($redirect_after) {
2156
-            $this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2157
-        }
2158
-    }
2159
-
2160
-
2161
-    /**
2162
-     * _trash_or_restore_events
2163
-     *
2164
-     * @access protected
2165
-     * @param string $event_status
2166
-     * @return void
2167
-     * @throws EE_Error
2168
-     * @throws EE_Error
2169
-     * @throws ReflectionException
2170
-     */
2171
-    protected function _trash_or_restore_events(string $event_status = 'trash')
2172
-    {
2173
-        // clean status
2174
-        $event_status = sanitize_key($event_status);
2175
-        // grab status
2176
-        if (! empty($event_status)) {
2177
-            $success = true;
2178
-            // determine the event id and set to array.
2179
-            $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2180
-            // loop thru events
2181
-            foreach ($EVT_IDs as $EVT_ID) {
2182
-                if ($EVT_ID = absint($EVT_ID)) {
2183
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
2184
-                    $success = $results !== false ? $success : false;
2185
-                } else {
2186
-                    $msg = sprintf(
2187
-                        esc_html__(
2188
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2189
-                            'event_espresso'
2190
-                        ),
2191
-                        $EVT_ID
2192
-                    );
2193
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2194
-                    $success = false;
2195
-                }
2196
-            }
2197
-        } else {
2198
-            $success = false;
2199
-            $msg     = esc_html__(
2200
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2201
-                'event_espresso'
2202
-            );
2203
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2204
-        }
2205
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2206
-        $success = $success ? 2 : false;
2207
-        $action  = $event_status === 'trash' ? 'moved to the trash' : 'restored from the trash';
2208
-        $this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2209
-    }
2210
-
2211
-
2212
-    /**
2213
-     * @param int    $EVT_ID
2214
-     * @param string $event_status
2215
-     * @return bool
2216
-     * @throws EE_Error
2217
-     * @throws ReflectionException
2218
-     */
2219
-    private function _change_event_status(int $EVT_ID = 0, string $event_status = ''): bool
2220
-    {
2221
-        // grab event id
2222
-        if (! $EVT_ID) {
2223
-            $msg = esc_html__(
2224
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2225
-                'event_espresso'
2226
-            );
2227
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2228
-            return false;
2229
-        }
2230
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2231
-        // clean status
2232
-        $event_status = sanitize_key($event_status);
2233
-        // grab status
2234
-        if (empty($event_status)) {
2235
-            $msg = esc_html__(
2236
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2237
-                'event_espresso'
2238
-            );
2239
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2240
-            return false;
2241
-        }
2242
-        // was event trashed or restored ?
2243
-        switch ($event_status) {
2244
-            case 'draft':
2245
-                $action = 'restored from the trash';
2246
-                $hook   = 'AHEE_event_restored_from_trash';
2247
-                break;
2248
-            case 'trash':
2249
-                $action = 'moved to the trash';
2250
-                $hook   = 'AHEE_event_moved_to_trash';
2251
-                break;
2252
-            default:
2253
-                $action = 'updated';
2254
-                $hook   = false;
2255
-        }
2256
-        // use class to change status
2257
-        $this->_cpt_model_obj->set_status($event_status);
2258
-        $success = $this->_cpt_model_obj->save();
2259
-        if (! $success) {
2260
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2261
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2262
-            return false;
2263
-        }
2264
-        if ($hook) {
2265
-            do_action($hook);
2266
-            // fake the action hook in EE_Soft_Delete_Base_Class::delete_or_restore()
2267
-            // because events side step that and it otherwise won't get called
2268
-            do_action(
2269
-                'AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after',
2270
-                $this->_cpt_model_obj,
2271
-                $hook === 'AHEE_event_moved_to_trash',
2272
-                $success
2273
-            );
2274
-        }
2275
-        return true;
2276
-    }
2277
-
2278
-
2279
-    /**
2280
-     * @param array $event_ids
2281
-     * @return array
2282
-     * @since   4.10.23.p
2283
-     */
2284
-    private function cleanEventIds(array $event_ids): array
2285
-    {
2286
-        return array_map('absint', $event_ids);
2287
-    }
2288
-
2289
-
2290
-    /**
2291
-     * @return array
2292
-     * @since   4.10.23.p
2293
-     */
2294
-    private function getEventIdsFromRequest(): array
2295
-    {
2296
-        if ($this->request->requestParamIsSet('EVT_IDs')) {
2297
-            return $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2298
-        } else {
2299
-            return $this->request->getRequestParam('EVT_ID', [], 'int', true);
2300
-        }
2301
-    }
2302
-
2303
-
2304
-    /**
2305
-     * @param bool $preview_delete
2306
-     * @throws EE_Error
2307
-     * @throws ReflectionException
2308
-     */
2309
-    protected function _delete_event(bool $preview_delete = true)
2310
-    {
2311
-        $this->_delete_events($preview_delete);
2312
-    }
2313
-
2314
-
2315
-    /**
2316
-     * Gets the tree traversal batch persister.
2317
-     *
2318
-     * @return NodeGroupDao
2319
-     * @throws InvalidArgumentException
2320
-     * @throws InvalidDataTypeException
2321
-     * @throws InvalidInterfaceException
2322
-     * @since 4.10.12.p
2323
-     */
2324
-    protected function getModelObjNodeGroupPersister(): NodeGroupDao
2325
-    {
2326
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2327
-            $this->model_obj_node_group_persister =
2328
-                $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2329
-        }
2330
-        return $this->model_obj_node_group_persister;
2331
-    }
2332
-
2333
-
2334
-    /**
2335
-     * @param bool $preview_delete
2336
-     * @return void
2337
-     * @throws EE_Error
2338
-     * @throws ReflectionException
2339
-     */
2340
-    protected function _delete_events(bool $preview_delete = true)
2341
-    {
2342
-        $event_ids = $this->getEventIdsFromRequest();
2343
-        if ($preview_delete) {
2344
-            $this->generateDeletionPreview($event_ids);
2345
-        } else {
2346
-            foreach ($event_ids as $event_id) {
2347
-                $event = EEM_Event::instance()->get_one_by_ID($event_id);
2348
-                if ($event instanceof EE_Event) {
2349
-                    $event->delete_permanently();
2350
-                }
2351
-            }
2352
-        }
2353
-    }
2354
-
2355
-
2356
-    /**
2357
-     * @param array $event_ids
2358
-     */
2359
-    protected function generateDeletionPreview(array $event_ids)
2360
-    {
2361
-        $event_ids = $this->cleanEventIds($event_ids);
2362
-        // Set a code we can use to reference this deletion task in the batch jobs and preview page.
2363
-        $deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2364
-        $return_url        = EE_Admin_Page::add_query_args_and_nonce(
2365
-            [
2366
-                'action'            => 'preview_deletion',
2367
-                'deletion_job_code' => $deletion_job_code,
2368
-            ],
2369
-            $this->_admin_base_url
2370
-        );
2371
-        EEH_URL::safeRedirectAndExit(
2372
-            EE_Admin_Page::add_query_args_and_nonce(
2373
-                [
2374
-                    'page'              => EED_Batch::PAGE_SLUG,
2375
-                    'batch'             => EED_Batch::batch_job,
2376
-                    'EVT_IDs'           => $event_ids,
2377
-                    'deletion_job_code' => $deletion_job_code,
2378
-                    'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2379
-                    'return_url'        => urlencode($return_url),
2380
-                ],
2381
-                admin_url()
2382
-            )
2383
-        );
2384
-    }
2385
-
2386
-
2387
-    /**
2388
-     * Checks for a POST submission
2389
-     *
2390
-     * @since 4.10.12.p
2391
-     */
2392
-    protected function confirmDeletion()
2393
-    {
2394
-        $deletion_redirect_logic = $this->getLoader()->getShared(
2395
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'
2396
-        );
2397
-        $deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2398
-    }
2399
-
2400
-
2401
-    /**
2402
-     * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2403
-     *
2404
-     * @throws EE_Error
2405
-     * @since 4.10.12.p
2406
-     */
2407
-    protected function previewDeletion()
2408
-    {
2409
-        $preview_deletion_logic = $this->getLoader()->getShared(
2410
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'
2411
-        );
2412
-        $this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2413
-        $this->display_admin_page_with_no_sidebar();
2414
-    }
2415
-
2416
-
2417
-    /**
2418
-     * get total number of events
2419
-     *
2420
-     * @access public
2421
-     * @return int
2422
-     * @throws EE_Error
2423
-     * @throws EE_Error
2424
-     * @throws ReflectionException
2425
-     */
2426
-    public function total_events(): int
2427
-    {
2428
-        return EEM_Event::instance()->count(
2429
-            ['caps' => 'read_admin'],
2430
-            'EVT_ID',
2431
-            true
2432
-        );
2433
-    }
2434
-
2435
-
2436
-    /**
2437
-     * get total number of draft events
2438
-     *
2439
-     * @access public
2440
-     * @return int
2441
-     * @throws EE_Error
2442
-     * @throws EE_Error
2443
-     * @throws ReflectionException
2444
-     */
2445
-    public function total_events_draft(): int
2446
-    {
2447
-        return EEM_Event::instance()->count(
2448
-            [
2449
-                ['status' => ['IN', ['draft', 'auto-draft']]],
2450
-                'caps' => 'read_admin',
2451
-            ],
2452
-            'EVT_ID',
2453
-            true
2454
-        );
2455
-    }
2456
-
2457
-
2458
-    /**
2459
-     * get total number of trashed events
2460
-     *
2461
-     * @access public
2462
-     * @return int
2463
-     * @throws EE_Error
2464
-     * @throws EE_Error
2465
-     * @throws ReflectionException
2466
-     */
2467
-    public function total_trashed_events(): int
2468
-    {
2469
-        return EEM_Event::instance()->count(
2470
-            [
2471
-                ['status' => 'trash'],
2472
-                'caps' => 'read_admin',
2473
-            ],
2474
-            'EVT_ID',
2475
-            true
2476
-        );
2477
-    }
2478
-
2479
-
2480
-    /**
2481
-     *    _default_event_settings
2482
-     *    This generates the Default Settings Tab
2483
-     *
2484
-     * @return void
2485
-     * @throws DomainException
2486
-     * @throws EE_Error
2487
-     * @throws InvalidArgumentException
2488
-     * @throws InvalidDataTypeException
2489
-     * @throws InvalidInterfaceException
2490
-     */
2491
-    protected function _default_event_settings()
2492
-    {
2493
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2494
-        $this->_set_publish_post_box_vars();
2495
-        $this->_template_args['admin_page_content'] = EEH_HTML::div(
2496
-            $this->_default_event_settings_form()->get_html(),
2497
-            '',
2498
-            'padding'
2499
-        );
2500
-        $this->display_admin_page_with_sidebar();
2501
-    }
2502
-
2503
-
2504
-    /**
2505
-     * Return the form for event settings.
2506
-     *
2507
-     * @return EE_Form_Section_Proper
2508
-     * @throws EE_Error
2509
-     */
2510
-    protected function _default_event_settings_form(): EE_Form_Section_Proper
2511
-    {
2512
-        $registration_config              = EE_Registry::instance()->CFG->registration;
2513
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2514
-        // exclude
2515
-            [
2516
-                EEM_Registration::status_id_cancelled,
2517
-                EEM_Registration::status_id_declined,
2518
-                EEM_Registration::status_id_incomplete,
2519
-                EEM_Registration::status_id_wait_list,
2520
-            ],
2521
-            true
2522
-        );
2523
-        // setup Advanced Editor ???
2524
-        if (
2525
-            $this->raw_req_action === 'default_event_settings'
2526
-            || $this->raw_req_action === 'update_default_event_settings'
2527
-        ) {
2528
-            $this->advanced_editor_admin_form = $this->loader->getShared(AdvancedEditorAdminFormSection::class);
2529
-        }
2530
-        return new EE_Form_Section_Proper(
2531
-            [
2532
-                'name'            => 'update_default_event_settings',
2533
-                'html_id'         => 'update_default_event_settings',
2534
-                'html_class'      => 'form-table',
2535
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2536
-                'subsections'     => apply_filters(
2537
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2538
-                    [
2539
-                        'defaults_section_header' => new EE_Form_Section_HTML(
2540
-                            EEH_HTML::h2(
2541
-                                esc_html__('Default Settings', 'event_espresso'),
2542
-                                '',
2543
-                                'ee-admin-settings-hdr'
2544
-                            )
2545
-                        ),
2546
-                        'default_reg_status'      => new EE_Select_Input(
2547
-                            $registration_stati_for_selection,
2548
-                            [
2549
-                                'default'         => isset($registration_config->default_STS_ID)
2550
-                                                     && array_key_exists(
2551
-                                                         $registration_config->default_STS_ID,
2552
-                                                         $registration_stati_for_selection
2553
-                                                     )
2554
-                                    ? sanitize_text_field($registration_config->default_STS_ID)
2555
-                                    : EEM_Registration::status_id_pending_payment,
2556
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2557
-                                                     . EEH_Template::get_help_tab_link(
2558
-                                                         'default_settings_status_help_tab'
2559
-                                                     ),
2560
-                                'html_help_text'  => esc_html__(
2561
-                                    '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.',
2562
-                                    'event_espresso'
2563
-                                ),
2564
-                            ]
2565
-                        ),
2566
-                        'default_max_tickets'     => new EE_Integer_Input(
2567
-                            [
2568
-                                'default'         => $registration_config->default_maximum_number_of_tickets
2569
-                                                     ?? EEM_Event::get_default_additional_limit(),
2570
-                                'html_label_text' => esc_html__(
2571
-                                    'Default Maximum Tickets Allowed Per Order:',
2572
-                                    'event_espresso'
2573
-                                )
2574
-                                                     . EEH_Template::get_help_tab_link(
2575
-                                                         'default_maximum_tickets_help_tab"'
2576
-                                                     ),
2577
-                                'html_help_text'  => esc_html__(
2578
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2579
-                                    'event_espresso'
2580
-                                ),
2581
-                            ]
2582
-                        ),
2583
-                    ]
2584
-                ),
2585
-            ]
2586
-        );
2587
-    }
2588
-
2589
-
2590
-    /**
2591
-     * @return void
2592
-     * @throws EE_Error
2593
-     * @throws InvalidArgumentException
2594
-     * @throws InvalidDataTypeException
2595
-     * @throws InvalidInterfaceException
2596
-     */
2597
-    protected function _update_default_event_settings()
2598
-    {
2599
-        $form = $this->_default_event_settings_form();
2600
-        if ($form->was_submitted()) {
2601
-            $form->receive_form_submission();
2602
-            if ($form->is_valid()) {
2603
-                $registration_config = EE_Registry::instance()->CFG->registration;
2604
-                $valid_data          = $form->valid_data();
2605
-                if (isset($valid_data['default_reg_status'])) {
2606
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2607
-                }
2608
-                if (isset($valid_data['default_max_tickets'])) {
2609
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2610
-                }
2611
-                do_action(
2612
-                    'AHEE__Events_Admin_Page___update_default_event_settings',
2613
-                    $valid_data,
2614
-                    EE_Registry::instance()->CFG,
2615
-                    $this
2616
-                );
2617
-                // update because data was valid!
2618
-                EE_Registry::instance()->CFG->update_espresso_config();
2619
-                EE_Error::overwrite_success();
2620
-                EE_Error::add_success(
2621
-                    esc_html__('Default Event Settings were updated', 'event_espresso')
2622
-                );
2623
-            }
2624
-        }
2625
-        $this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2626
-    }
2627
-
2628
-
2629
-    /*************        Templates        *************
2630
-     *
2631
-     * @throws EE_Error
2632
-     */
2633
-    protected function _template_settings()
2634
-    {
2635
-        $this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2636
-        $this->_template_args['preview_img']  = '<img src="'
2637
-                                                . EVENTS_ASSETS_URL
2638
-                                                . '/images/'
2639
-                                                . 'caffeinated_template_features.jpg" alt="'
2640
-                                                . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2641
-                                                . '" />';
2642
-        $this->_template_args['preview_text'] = '<strong>'
2643
-                                                . esc_html__(
2644
-                                                    '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.',
2645
-                                                    'event_espresso'
2646
-                                                ) . '</strong>';
2647
-        $this->display_admin_caf_preview_page('template_settings_tab');
2648
-    }
2649
-
2650
-
2651
-    /** Event Category Stuff **/
2652
-    /**
2653
-     * set the _category property with the category object for the loaded page.
2654
-     *
2655
-     * @access private
2656
-     * @return void
2657
-     */
2658
-    private function _set_category_object()
2659
-    {
2660
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2661
-            return;
2662
-        } //already have the category object so get out.
2663
-        // set default category object
2664
-        $this->_set_empty_category_object();
2665
-        // only set if we've got an id
2666
-        $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
2667
-        if (! $category_ID) {
2668
-            return;
2669
-        }
2670
-        $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2671
-        if (! empty($term)) {
2672
-            $this->_category->category_name       = $term->name;
2673
-            $this->_category->category_identifier = $term->slug;
2674
-            $this->_category->category_desc       = $term->description;
2675
-            $this->_category->id                  = $term->term_id;
2676
-            $this->_category->parent              = $term->parent;
2677
-        }
2678
-    }
2679
-
2680
-
2681
-    /**
2682
-     * Clears out category properties.
2683
-     */
2684
-    private function _set_empty_category_object()
2685
-    {
2686
-        $this->_category                = new stdClass();
2687
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2688
-        $this->_category->id            = $this->_category->parent = 0;
2689
-    }
2690
-
2691
-
2692
-    /**
2693
-     * @throws DomainException
2694
-     * @throws EE_Error
2695
-     * @throws InvalidArgumentException
2696
-     * @throws InvalidDataTypeException
2697
-     * @throws InvalidInterfaceException
2698
-     */
2699
-    protected function _category_list_table()
2700
-    {
2701
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2702
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2703
-        $this->_admin_page_title .= ' ';
2704
-        $this->_admin_page_title .= $this->get_action_link_or_button(
2705
-            'add_category',
2706
-            'add_category',
2707
-            [],
2708
-            'add-new-h2'
2709
-        );
2710
-        $this->display_admin_list_table_page_with_sidebar();
2711
-    }
2712
-
2713
-
2714
-    /**
2715
-     * Output category details view.
2716
-     *
2717
-     * @throws EE_Error
2718
-     * @throws EE_Error
2719
-     */
2720
-    protected function _category_details($view)
2721
-    {
2722
-        $route = $view === 'edit' ? 'update_category' : 'insert_category';
2723
-        $this->_set_add_edit_form_tags($route);
2724
-        $this->_set_category_object();
2725
-        $id            = ! empty($this->_category->id) ? $this->_category->id : '';
2726
-        $delete_action = 'delete_category';
2727
-        // custom redirect
2728
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2729
-            ['action' => 'category_list'],
2730
-            $this->_admin_base_url
2731
-        );
2732
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect, true);
2733
-        // take care of contents
2734
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2735
-        $this->display_admin_page_with_sidebar();
2736
-    }
2737
-
2738
-
2739
-    /**
2740
-     * Output category details content.
2741
-     *
2742
-     * @throws DomainException
2743
-     */
2744
-    protected function _category_details_content(): string
2745
-    {
2746
-        $editor_args['category_desc'] = [
2747
-            'type'          => 'wp_editor',
2748
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2749
-            'class'         => 'my_editor_custom',
2750
-            'wpeditor_args' => ['media_buttons' => false],
2751
-        ];
2752
-        $_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2753
-        $all_terms                    = get_terms(
2754
-            [EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2755
-            ['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2756
-        );
2757
-        // setup category select for term parents.
2758
-        $category_select_values[] = [
2759
-            'text' => esc_html__('No Parent', 'event_espresso'),
2760
-            'id'   => 0,
2761
-        ];
2762
-        foreach ($all_terms as $term) {
2763
-            $category_select_values[] = [
2764
-                'text' => $term->name,
2765
-                'id'   => $term->term_id,
2766
-            ];
2767
-        }
2768
-        $category_select = EEH_Form_Fields::select_input(
2769
-            'category_parent',
2770
-            $category_select_values,
2771
-            $this->_category->parent
2772
-        );
2773
-        $template_args   = [
2774
-            'category'                 => $this->_category,
2775
-            'category_select'          => $category_select,
2776
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2777
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2778
-            'disable'                  => '',
2779
-            'disabled_message'         => false,
2780
-        ];
2781
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2782
-        return EEH_Template::display_template($template, $template_args, true);
2783
-    }
2784
-
2785
-
2786
-    /**
2787
-     * Handles deleting categories.
2788
-     *
2789
-     * @throws EE_Error
2790
-     */
2791
-    protected function _delete_categories()
2792
-    {
2793
-        $category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2794
-        foreach ($category_IDs as $category_ID) {
2795
-            $this->_delete_category($category_ID);
2796
-        }
2797
-        // doesn't matter what page we're coming from... we're going to the same place after delete.
2798
-        $query_args = [
2799
-            'action' => 'category_list',
2800
-        ];
2801
-        $this->_redirect_after_action(0, '', '', $query_args);
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Handles deleting specific category.
2807
-     *
2808
-     * @param int $cat_id
2809
-     */
2810
-    protected function _delete_category(int $cat_id)
2811
-    {
2812
-        $cat_id = absint($cat_id);
2813
-        wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2814
-    }
2815
-
2816
-
2817
-    /**
2818
-     * Handles triggering the update or insertion of a new category.
2819
-     *
2820
-     * @param bool $new_category true means we're triggering the insert of a new category.
2821
-     * @throws EE_Error
2822
-     * @throws EE_Error
2823
-     */
2824
-    protected function _insert_or_update_category(bool $new_category)
2825
-    {
2826
-        $cat_id  = $this->_insert_category($new_category);
2827
-        $success = 0; // we already have a success message so lets not send another.
2828
-        if ($cat_id) {
2829
-            $query_args = [
2830
-                'action'     => 'edit_category',
2831
-                'EVT_CAT_ID' => $cat_id,
2832
-            ];
2833
-        } else {
2834
-            $query_args = ['action' => 'add_category'];
2835
-        }
2836
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2837
-    }
2838
-
2839
-
2840
-    /**
2841
-     * Inserts or updates category
2842
-     *
2843
-     * @param bool $new_category (true indicates we're updating a category).
2844
-     * @return bool|mixed|string
2845
-     */
2846
-    private function _insert_category(bool $new_category)
2847
-    {
2848
-        $category_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
2849
-        $category_name       = $this->request->getRequestParam('category_name', '');
2850
-        $category_desc       = $this->request->getRequestParam('category_desc', '', DataType::HTML);
2851
-        $category_parent     = $this->request->getRequestParam('category_parent', 0, DataType::INT);
2852
-        $category_identifier = $this->request->getRequestParam('category_identifier', '');
2853
-
2854
-        if (empty($category_name)) {
2855
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2856
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2857
-            return 0;
2858
-        }
2859
-        $term_args = [
2860
-            'name'        => $category_name,
2861
-            'description' => $category_desc,
2862
-            'parent'      => $category_parent,
2863
-        ];
2864
-        // was the category_identifier input disabled?
2865
-        if ($category_identifier) {
2866
-            $term_args['slug'] = $category_identifier;
2867
-        }
2868
-        $insert_ids = $new_category
2869
-            ? wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2870
-            : wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2871
-
2872
-        if ($insert_ids instanceof WP_Error) {
2873
-            EE_Error::add_error($insert_ids->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
2874
-            return 0;
2875
-        }
2876
-        $category_ID = $insert_ids['term_id'] ?? 0;
2877
-        if (! $category_ID) {
2878
-            EE_Error::add_error(
2879
-                esc_html__(
2880
-                    'An error occurred and the category has not been saved to the database.',
2881
-                    'event_espresso'
2882
-                ),
2883
-                __FILE__,
2884
-                __FUNCTION__,
2885
-                __LINE__
2886
-            );
2887
-            return 0;
2888
-        }
2889
-        EE_Error::add_success(
2890
-            sprintf(
2891
-                esc_html__('The category %s was successfully saved', 'event_espresso'),
2892
-                $category_name
2893
-            )
2894
-        );
2895
-        return $category_ID;
2896
-    }
2897
-
2898
-
2899
-    /**
2900
-     * Gets categories or count of categories matching the arguments in the request.
2901
-     *
2902
-     * @param int  $per_page
2903
-     * @param int  $current_page
2904
-     * @param bool $count
2905
-     * @return EE_Term_Taxonomy[]|int
2906
-     * @throws EE_Error
2907
-     * @throws ReflectionException
2908
-     */
2909
-    public function get_categories(int $per_page = 10, int $current_page = 1, bool $count = false)
2910
-    {
2911
-        // testing term stuff
2912
-        $orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2913
-        $order       = $this->request->getRequestParam('order', 'DESC');
2914
-        $limit       = ($current_page - 1) * $per_page;
2915
-        $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2916
-        $search_term = $this->request->getRequestParam('s');
2917
-        if ($search_term) {
2918
-            $search_term = '%' . $search_term . '%';
2919
-            $where['OR'] = [
2920
-                'Term.name'   => ['LIKE', $search_term],
2921
-                'description' => ['LIKE', $search_term],
2922
-            ];
2923
-        }
2924
-        $query_params = [
2925
-            $where,
2926
-            'order_by'   => [$orderby => $order],
2927
-            'limit'      => $limit . ',' . $per_page,
2928
-            'force_join' => ['Term'],
2929
-        ];
2930
-        return $count
2931
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2932
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2933
-    }
2934
-
2935
-    /* end category stuff */
2936
-
2937
-
2938
-    /**************/
2939
-
2940
-
2941
-    /**
2942
-     * Callback for the `ee_save_timezone_setting` ajax action.
2943
-     *
2944
-     * @throws EE_Error
2945
-     * @throws InvalidArgumentException
2946
-     * @throws InvalidDataTypeException
2947
-     * @throws InvalidInterfaceException
2948
-     */
2949
-    public function saveTimezoneString()
2950
-    {
2951
-        $timezone_string = $this->request->getRequestParam('timezone_selected');
2952
-        if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2953
-            EE_Error::add_error(
2954
-                esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2955
-                __FILE__,
2956
-                __FUNCTION__,
2957
-                __LINE__
2958
-            );
2959
-            $this->_template_args['error'] = true;
2960
-            $this->_return_json();
2961
-        }
2962
-
2963
-        update_option('timezone_string', $timezone_string);
2964
-        EE_Error::add_success(
2965
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2966
-        );
2967
-        $this->_template_args['success'] = true;
2968
-        $this->_return_json(true, ['action' => 'create_new']);
2969
-    }
2970
-
2971
-
2972
-    /**
2973 2631
      * @throws EE_Error
2974
-     * @deprecated 4.10.25.p
2975 2632
      */
2976
-    public function save_timezonestring_setting()
2977
-    {
2978
-        $this->saveTimezoneString();
2979
-    }
2633
+	protected function _template_settings()
2634
+	{
2635
+		$this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2636
+		$this->_template_args['preview_img']  = '<img src="'
2637
+												. EVENTS_ASSETS_URL
2638
+												. '/images/'
2639
+												. 'caffeinated_template_features.jpg" alt="'
2640
+												. esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2641
+												. '" />';
2642
+		$this->_template_args['preview_text'] = '<strong>'
2643
+												. esc_html__(
2644
+													'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.',
2645
+													'event_espresso'
2646
+												) . '</strong>';
2647
+		$this->display_admin_caf_preview_page('template_settings_tab');
2648
+	}
2649
+
2650
+
2651
+	/** Event Category Stuff **/
2652
+	/**
2653
+	 * set the _category property with the category object for the loaded page.
2654
+	 *
2655
+	 * @access private
2656
+	 * @return void
2657
+	 */
2658
+	private function _set_category_object()
2659
+	{
2660
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2661
+			return;
2662
+		} //already have the category object so get out.
2663
+		// set default category object
2664
+		$this->_set_empty_category_object();
2665
+		// only set if we've got an id
2666
+		$category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
2667
+		if (! $category_ID) {
2668
+			return;
2669
+		}
2670
+		$term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2671
+		if (! empty($term)) {
2672
+			$this->_category->category_name       = $term->name;
2673
+			$this->_category->category_identifier = $term->slug;
2674
+			$this->_category->category_desc       = $term->description;
2675
+			$this->_category->id                  = $term->term_id;
2676
+			$this->_category->parent              = $term->parent;
2677
+		}
2678
+	}
2679
+
2680
+
2681
+	/**
2682
+	 * Clears out category properties.
2683
+	 */
2684
+	private function _set_empty_category_object()
2685
+	{
2686
+		$this->_category                = new stdClass();
2687
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2688
+		$this->_category->id            = $this->_category->parent = 0;
2689
+	}
2690
+
2691
+
2692
+	/**
2693
+	 * @throws DomainException
2694
+	 * @throws EE_Error
2695
+	 * @throws InvalidArgumentException
2696
+	 * @throws InvalidDataTypeException
2697
+	 * @throws InvalidInterfaceException
2698
+	 */
2699
+	protected function _category_list_table()
2700
+	{
2701
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2702
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2703
+		$this->_admin_page_title .= ' ';
2704
+		$this->_admin_page_title .= $this->get_action_link_or_button(
2705
+			'add_category',
2706
+			'add_category',
2707
+			[],
2708
+			'add-new-h2'
2709
+		);
2710
+		$this->display_admin_list_table_page_with_sidebar();
2711
+	}
2712
+
2713
+
2714
+	/**
2715
+	 * Output category details view.
2716
+	 *
2717
+	 * @throws EE_Error
2718
+	 * @throws EE_Error
2719
+	 */
2720
+	protected function _category_details($view)
2721
+	{
2722
+		$route = $view === 'edit' ? 'update_category' : 'insert_category';
2723
+		$this->_set_add_edit_form_tags($route);
2724
+		$this->_set_category_object();
2725
+		$id            = ! empty($this->_category->id) ? $this->_category->id : '';
2726
+		$delete_action = 'delete_category';
2727
+		// custom redirect
2728
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2729
+			['action' => 'category_list'],
2730
+			$this->_admin_base_url
2731
+		);
2732
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect, true);
2733
+		// take care of contents
2734
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2735
+		$this->display_admin_page_with_sidebar();
2736
+	}
2737
+
2738
+
2739
+	/**
2740
+	 * Output category details content.
2741
+	 *
2742
+	 * @throws DomainException
2743
+	 */
2744
+	protected function _category_details_content(): string
2745
+	{
2746
+		$editor_args['category_desc'] = [
2747
+			'type'          => 'wp_editor',
2748
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2749
+			'class'         => 'my_editor_custom',
2750
+			'wpeditor_args' => ['media_buttons' => false],
2751
+		];
2752
+		$_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2753
+		$all_terms                    = get_terms(
2754
+			[EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2755
+			['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2756
+		);
2757
+		// setup category select for term parents.
2758
+		$category_select_values[] = [
2759
+			'text' => esc_html__('No Parent', 'event_espresso'),
2760
+			'id'   => 0,
2761
+		];
2762
+		foreach ($all_terms as $term) {
2763
+			$category_select_values[] = [
2764
+				'text' => $term->name,
2765
+				'id'   => $term->term_id,
2766
+			];
2767
+		}
2768
+		$category_select = EEH_Form_Fields::select_input(
2769
+			'category_parent',
2770
+			$category_select_values,
2771
+			$this->_category->parent
2772
+		);
2773
+		$template_args   = [
2774
+			'category'                 => $this->_category,
2775
+			'category_select'          => $category_select,
2776
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2777
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2778
+			'disable'                  => '',
2779
+			'disabled_message'         => false,
2780
+		];
2781
+		$template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2782
+		return EEH_Template::display_template($template, $template_args, true);
2783
+	}
2784
+
2785
+
2786
+	/**
2787
+	 * Handles deleting categories.
2788
+	 *
2789
+	 * @throws EE_Error
2790
+	 */
2791
+	protected function _delete_categories()
2792
+	{
2793
+		$category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2794
+		foreach ($category_IDs as $category_ID) {
2795
+			$this->_delete_category($category_ID);
2796
+		}
2797
+		// doesn't matter what page we're coming from... we're going to the same place after delete.
2798
+		$query_args = [
2799
+			'action' => 'category_list',
2800
+		];
2801
+		$this->_redirect_after_action(0, '', '', $query_args);
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Handles deleting specific category.
2807
+	 *
2808
+	 * @param int $cat_id
2809
+	 */
2810
+	protected function _delete_category(int $cat_id)
2811
+	{
2812
+		$cat_id = absint($cat_id);
2813
+		wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2814
+	}
2815
+
2816
+
2817
+	/**
2818
+	 * Handles triggering the update or insertion of a new category.
2819
+	 *
2820
+	 * @param bool $new_category true means we're triggering the insert of a new category.
2821
+	 * @throws EE_Error
2822
+	 * @throws EE_Error
2823
+	 */
2824
+	protected function _insert_or_update_category(bool $new_category)
2825
+	{
2826
+		$cat_id  = $this->_insert_category($new_category);
2827
+		$success = 0; // we already have a success message so lets not send another.
2828
+		if ($cat_id) {
2829
+			$query_args = [
2830
+				'action'     => 'edit_category',
2831
+				'EVT_CAT_ID' => $cat_id,
2832
+			];
2833
+		} else {
2834
+			$query_args = ['action' => 'add_category'];
2835
+		}
2836
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2837
+	}
2838
+
2839
+
2840
+	/**
2841
+	 * Inserts or updates category
2842
+	 *
2843
+	 * @param bool $new_category (true indicates we're updating a category).
2844
+	 * @return bool|mixed|string
2845
+	 */
2846
+	private function _insert_category(bool $new_category)
2847
+	{
2848
+		$category_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, DataType::INT);
2849
+		$category_name       = $this->request->getRequestParam('category_name', '');
2850
+		$category_desc       = $this->request->getRequestParam('category_desc', '', DataType::HTML);
2851
+		$category_parent     = $this->request->getRequestParam('category_parent', 0, DataType::INT);
2852
+		$category_identifier = $this->request->getRequestParam('category_identifier', '');
2853
+
2854
+		if (empty($category_name)) {
2855
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2856
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2857
+			return 0;
2858
+		}
2859
+		$term_args = [
2860
+			'name'        => $category_name,
2861
+			'description' => $category_desc,
2862
+			'parent'      => $category_parent,
2863
+		];
2864
+		// was the category_identifier input disabled?
2865
+		if ($category_identifier) {
2866
+			$term_args['slug'] = $category_identifier;
2867
+		}
2868
+		$insert_ids = $new_category
2869
+			? wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2870
+			: wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2871
+
2872
+		if ($insert_ids instanceof WP_Error) {
2873
+			EE_Error::add_error($insert_ids->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
2874
+			return 0;
2875
+		}
2876
+		$category_ID = $insert_ids['term_id'] ?? 0;
2877
+		if (! $category_ID) {
2878
+			EE_Error::add_error(
2879
+				esc_html__(
2880
+					'An error occurred and the category has not been saved to the database.',
2881
+					'event_espresso'
2882
+				),
2883
+				__FILE__,
2884
+				__FUNCTION__,
2885
+				__LINE__
2886
+			);
2887
+			return 0;
2888
+		}
2889
+		EE_Error::add_success(
2890
+			sprintf(
2891
+				esc_html__('The category %s was successfully saved', 'event_espresso'),
2892
+				$category_name
2893
+			)
2894
+		);
2895
+		return $category_ID;
2896
+	}
2897
+
2898
+
2899
+	/**
2900
+	 * Gets categories or count of categories matching the arguments in the request.
2901
+	 *
2902
+	 * @param int  $per_page
2903
+	 * @param int  $current_page
2904
+	 * @param bool $count
2905
+	 * @return EE_Term_Taxonomy[]|int
2906
+	 * @throws EE_Error
2907
+	 * @throws ReflectionException
2908
+	 */
2909
+	public function get_categories(int $per_page = 10, int $current_page = 1, bool $count = false)
2910
+	{
2911
+		// testing term stuff
2912
+		$orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2913
+		$order       = $this->request->getRequestParam('order', 'DESC');
2914
+		$limit       = ($current_page - 1) * $per_page;
2915
+		$where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2916
+		$search_term = $this->request->getRequestParam('s');
2917
+		if ($search_term) {
2918
+			$search_term = '%' . $search_term . '%';
2919
+			$where['OR'] = [
2920
+				'Term.name'   => ['LIKE', $search_term],
2921
+				'description' => ['LIKE', $search_term],
2922
+			];
2923
+		}
2924
+		$query_params = [
2925
+			$where,
2926
+			'order_by'   => [$orderby => $order],
2927
+			'limit'      => $limit . ',' . $per_page,
2928
+			'force_join' => ['Term'],
2929
+		];
2930
+		return $count
2931
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2932
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2933
+	}
2934
+
2935
+	/* end category stuff */
2936
+
2937
+
2938
+	/**************/
2939
+
2940
+
2941
+	/**
2942
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2943
+	 *
2944
+	 * @throws EE_Error
2945
+	 * @throws InvalidArgumentException
2946
+	 * @throws InvalidDataTypeException
2947
+	 * @throws InvalidInterfaceException
2948
+	 */
2949
+	public function saveTimezoneString()
2950
+	{
2951
+		$timezone_string = $this->request->getRequestParam('timezone_selected');
2952
+		if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2953
+			EE_Error::add_error(
2954
+				esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2955
+				__FILE__,
2956
+				__FUNCTION__,
2957
+				__LINE__
2958
+			);
2959
+			$this->_template_args['error'] = true;
2960
+			$this->_return_json();
2961
+		}
2962
+
2963
+		update_option('timezone_string', $timezone_string);
2964
+		EE_Error::add_success(
2965
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2966
+		);
2967
+		$this->_template_args['success'] = true;
2968
+		$this->_return_json(true, ['action' => 'create_new']);
2969
+	}
2970
+
2971
+
2972
+	/**
2973
+	 * @throws EE_Error
2974
+	 * @deprecated 4.10.25.p
2975
+	 */
2976
+	public function save_timezonestring_setting()
2977
+	{
2978
+		$this->saveTimezoneString();
2979
+	}
2980 2980
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -37,120 +37,120 @@
 block discarded – undo
37 37
  * @since           4.0
38 38
  */
39 39
 if (function_exists('espresso_version')) {
40
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
-        /**
42
-         *    espresso_duplicate_plugin_error
43
-         *    displays if more than one version of EE is activated at the same time.
44
-         */
45
-        function espresso_duplicate_plugin_error()
46
-        {
47
-            ?>
40
+	if (! function_exists('espresso_duplicate_plugin_error')) {
41
+		/**
42
+		 *    espresso_duplicate_plugin_error
43
+		 *    displays if more than one version of EE is activated at the same time.
44
+		 */
45
+		function espresso_duplicate_plugin_error()
46
+		{
47
+			?>
48 48
             <div class="error">
49 49
                 <p>
50 50
                     <?php
51
-                    echo esc_html__(
52
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
-                        'event_espresso'
54
-                    ); ?>
51
+					echo esc_html__(
52
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
+						'event_espresso'
54
+					); ?>
55 55
                 </p>
56 56
             </div>
57 57
             <?php
58
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
59
-        }
60
-    }
61
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
58
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
59
+		}
60
+	}
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 } else {
63
-    define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
-        /**
66
-         * espresso_minimum_php_version_error
67
-         *
68
-         * @return void
69
-         */
70
-        function espresso_minimum_php_version_error()
71
-        {
72
-            ?>
63
+	define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
+		/**
66
+		 * espresso_minimum_php_version_error
67
+		 *
68
+		 * @return void
69
+		 */
70
+		function espresso_minimum_php_version_error()
71
+		{
72
+			?>
73 73
             <div class="error">
74 74
                 <p>
75 75
                     <?php
76
-                    printf(
77
-                        esc_html__(
78
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
-                            'event_espresso'
80
-                        ),
81
-                        EE_MIN_PHP_VER_REQUIRED,
82
-                        PHP_VERSION,
83
-                        '<br/>',
84
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
-                    );
86
-                    ?>
76
+					printf(
77
+						esc_html__(
78
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
+							'event_espresso'
80
+						),
81
+						EE_MIN_PHP_VER_REQUIRED,
82
+						PHP_VERSION,
83
+						'<br/>',
84
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
+					);
86
+					?>
87 87
                 </p>
88 88
             </div>
89 89
             <?php
90
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
91
-        }
90
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
91
+		}
92 92
 
93
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
-    } else {
95
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
93
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
+	} else {
95
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
96 96
 
97
-        require_once __DIR__ . '/vendor/autoload.php';
98
-        require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
97
+		require_once __DIR__ . '/vendor/autoload.php';
98
+		require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
99 99
 
100
-        /**
101
-         * espresso_version
102
-         * Returns the plugin version
103
-         *
104
-         * @return string
105
-         */
106
-        function espresso_version()
107
-        {
108
-            return apply_filters('FHEE__espresso__espresso_version', '5.0.0.rc.015');
109
-        }
100
+		/**
101
+		 * espresso_version
102
+		 * Returns the plugin version
103
+		 *
104
+		 * @return string
105
+		 */
106
+		function espresso_version()
107
+		{
108
+			return apply_filters('FHEE__espresso__espresso_version', '5.0.0.rc.015');
109
+		}
110 110
 
111
-        /**
112
-         * espresso_plugin_activation
113
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
-         */
115
-        function espresso_plugin_activation()
116
-        {
117
-            update_option('ee_espresso_activation', true);
118
-            // Run WP GraphQL activation callback
119
-            graphql_activation_callback();
120
-        }
111
+		/**
112
+		 * espresso_plugin_activation
113
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
+		 */
115
+		function espresso_plugin_activation()
116
+		{
117
+			update_option('ee_espresso_activation', true);
118
+			// Run WP GraphQL activation callback
119
+			graphql_activation_callback();
120
+		}
121 121
 
122
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
122
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
123 123
 
124
-        /**
125
-         * espresso_plugin_deactivation
126
-         */
127
-        function espresso_plugin_deactivation()
128
-        {
129
-            // Run WP GraphQL deactivation callback
130
-            graphql_deactivation_callback();
131
-        }
132
-        register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
124
+		/**
125
+		 * espresso_plugin_deactivation
126
+		 */
127
+		function espresso_plugin_deactivation()
128
+		{
129
+			// Run WP GraphQL deactivation callback
130
+			graphql_deactivation_callback();
131
+		}
132
+		register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
133 133
 
134
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
135
-        bootstrap_espresso();
136
-    }
134
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
135
+		bootstrap_espresso();
136
+	}
137 137
 }
138 138
 
139 139
 if (! function_exists('espresso_deactivate_plugin')) {
140
-    /**
141
-     *    deactivate_plugin
142
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
143
-     *
144
-     * @access public
145
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
146
-     * @return    void
147
-     */
148
-    function espresso_deactivate_plugin($plugin_basename = '')
149
-    {
150
-        if (! function_exists('deactivate_plugins')) {
151
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
152
-        }
153
-        unset($_GET['activate'], $_REQUEST['activate']);
154
-        deactivate_plugins($plugin_basename);
155
-    }
140
+	/**
141
+	 *    deactivate_plugin
142
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
143
+	 *
144
+	 * @access public
145
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
146
+	 * @return    void
147
+	 */
148
+	function espresso_deactivate_plugin($plugin_basename = '')
149
+	{
150
+		if (! function_exists('deactivate_plugins')) {
151
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
152
+		}
153
+		unset($_GET['activate'], $_REQUEST['activate']);
154
+		deactivate_plugins($plugin_basename);
155
+	}
156 156
 }
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegistrantForm.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -17,197 +17,197 @@
 block discarded – undo
17 17
 
18 18
 class RegistrantForm extends EE_Form_Section_Proper
19 19
 {
20
-    /**
21
-     * @var EE_SPCO_Reg_Step_Attendee_Information
22
-     */
23
-    public $reg_step;
24
-
25
-    /**
26
-     * @var EEM_Event_Question_Group
27
-     */
28
-    public $event_question_group_model;
29
-
30
-    /**
31
-     * @var bool
32
-     */
33
-    private $has_questions = false;
34
-
35
-
36
-    /**
37
-     * RegistrantForm constructor.
38
-     *
39
-     * @param EE_Registration          $registration
40
-     * @param bool                     $copy_attendee_info
41
-     * @param callable                 $enablePrintCopyInfo
42
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
43
-     * @param EEM_Event_Question_Group $event_question_group_model
44
-     * @throws EE_Error
45
-     * @throws ReflectionException
46
-     */
47
-    public function __construct(
48
-        EE_Registration $registration,
49
-        bool $copy_attendee_info,
50
-        callable $enablePrintCopyInfo,
51
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
52
-        EEM_Event_Question_Group $event_question_group_model
53
-    ) {
54
-        $this->reg_step = $reg_step;
55
-        $this->event_question_group_model = $event_question_group_model;
56
-        parent::__construct(
57
-            $this->generateFormArgs($registration, $copy_attendee_info, $enablePrintCopyInfo)
58
-        );
59
-    }
60
-
61
-
62
-    /**
63
-     * @return bool
64
-     */
65
-    public function hasQuestions(): bool
66
-    {
67
-        return $this->has_questions;
68
-    }
69
-
70
-
71
-    /**
72
-     * @param EE_Registration $registration
73
-     * @param bool            $copy_attendee_info
74
-     * @param callable        $enablePrintCopyInfo
75
-     * @return array
76
-     * @throws EE_Error
77
-     * @throws ReflectionException
78
-     */
79
-    private function generateFormArgs(
80
-        EE_Registration $registration,
81
-        bool $copy_attendee_info,
82
-        callable $enablePrintCopyInfo
83
-    ): array {
84
-        static $attendee_nmbr = 1;
85
-        $form_args = [];
86
-        // verify that registration has valid event
87
-        if ($registration->event() instanceof EE_Event) {
88
-            $field_name      = 'Event_Question_Group.' . $this->event_question_group_model->fieldNameForContext(
89
-                $registration->is_primary_registrant()
90
-            );
91
-            $question_groups = $registration->event()->question_groups(
92
-                apply_filters(
93
-                    'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__question_groups_query_parameters',
94
-                    [
95
-                        [
96
-                            'Event.EVT_ID' => $registration->event()->ID(),
97
-                            $field_name    => true,
98
-                            'QSG_deleted'  => false,
99
-                        ],
100
-                        'order_by' => ['QSG_order' => 'ASC'],
101
-                    ],
102
-                    $registration,
103
-                    $this
104
-                )
105
-            );
106
-            if ($question_groups) {
107
-                // array of params to pass to parent constructor
108
-                $form_args = [
109
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
110
-                    'html_class'      => 'ee-reg-form-attendee-dv',
111
-                    'html_style'      => $this->reg_step->checkout->admin_request
112
-                        ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
113
-                        : '',
114
-                    'subsections'     => [],
115
-                    'layout_strategy' => new EE_Fieldset_Section_Layout(
116
-                        [
117
-                            'legend_class' => 'spco-attendee-lgnd',
118
-                            'legend_text'  => sprintf(
119
-                                esc_html_x(
120
-                                    'Attendee %d',
121
-                                    'Attendee 123',
122
-                                    'event_espresso'
123
-                                ),
124
-                                $attendee_nmbr
125
-                            ),
126
-                        ]
127
-                    ),
128
-                ];
129
-                foreach ($question_groups as $question_group) {
130
-                    if ($question_group instanceof EE_Question_Group) {
131
-                        $question_group_reg_form = LoaderFactory::getNew(
132
-                            RegFormQuestionGroup::class,
133
-                            [$registration, $question_group, $this->reg_step]
134
-                        );
135
-                        $form_args['subsections'][ $question_group->identifier() ] = apply_filters(
136
-                            'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__question_group_reg_form',
137
-                            $question_group_reg_form,
138
-                            $registration,
139
-                            $question_group,
140
-                            $this
141
-                        );
142
-                    }
143
-                }
144
-                // add hidden input
145
-                $form_args['subsections']['additional_attendee_reg_info'] = $this->additionalAttendeeRegInfoInput(
146
-                    $registration
147
-                );
148
-
149
-                // If we have question groups for additional attendees, then display the copy options
150
-                $printCopyInfo = apply_filters(
151
-                    'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__printCopyInfo',
152
-                    $attendee_nmbr > 1 && $copy_attendee_info,
153
-                    $attendee_nmbr,
154
-                    $registration,
155
-                    $this
156
-                );
157
-                if ($printCopyInfo) {
158
-                    $enablePrintCopyInfo();
159
-                }
160
-
161
-
162
-                if ($registration->is_primary_registrant()) {
163
-                    // generate hidden input
164
-                    $form_args['subsections']['primary_registrant'] = $this->additionalPrimaryRegistrantInputs(
165
-                        $registration
166
-                    );
167
-                }
168
-            }
169
-        }
170
-        $attendee_nmbr++;
171
-
172
-        // Increment the reg forms number if form is valid.
173
-        if (! empty($form_args)) {
174
-            $this->has_questions = true;
175
-        }
176
-
177
-        return $form_args;
178
-    }
179
-
180
-
181
-    /**
182
-     * @param EE_Registration $registration
183
-     * @return EE_Form_Input_Base
184
-     * @throws EE_Error
185
-     */
186
-    private function additionalAttendeeRegInfoInput(EE_Registration $registration)
187
-    {
188
-        // generate hidden input
189
-        return new EE_Hidden_Input(
190
-            [
191
-                'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
192
-                'default' => true,
193
-            ]
194
-        );
195
-    }
196
-
197
-
198
-    /**
199
-     * @param EE_Registration $registration
200
-     * @return    EE_Form_Input_Base
201
-     * @throws EE_Error
202
-     */
203
-    private function additionalPrimaryRegistrantInputs(EE_Registration $registration)
204
-    {
205
-        // generate hidden input
206
-        return new EE_Hidden_Input(
207
-            [
208
-                'html_id' => 'primary_registrant',
209
-                'default' => $registration->reg_url_link(),
210
-            ]
211
-        );
212
-    }
20
+	/**
21
+	 * @var EE_SPCO_Reg_Step_Attendee_Information
22
+	 */
23
+	public $reg_step;
24
+
25
+	/**
26
+	 * @var EEM_Event_Question_Group
27
+	 */
28
+	public $event_question_group_model;
29
+
30
+	/**
31
+	 * @var bool
32
+	 */
33
+	private $has_questions = false;
34
+
35
+
36
+	/**
37
+	 * RegistrantForm constructor.
38
+	 *
39
+	 * @param EE_Registration          $registration
40
+	 * @param bool                     $copy_attendee_info
41
+	 * @param callable                 $enablePrintCopyInfo
42
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
43
+	 * @param EEM_Event_Question_Group $event_question_group_model
44
+	 * @throws EE_Error
45
+	 * @throws ReflectionException
46
+	 */
47
+	public function __construct(
48
+		EE_Registration $registration,
49
+		bool $copy_attendee_info,
50
+		callable $enablePrintCopyInfo,
51
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
52
+		EEM_Event_Question_Group $event_question_group_model
53
+	) {
54
+		$this->reg_step = $reg_step;
55
+		$this->event_question_group_model = $event_question_group_model;
56
+		parent::__construct(
57
+			$this->generateFormArgs($registration, $copy_attendee_info, $enablePrintCopyInfo)
58
+		);
59
+	}
60
+
61
+
62
+	/**
63
+	 * @return bool
64
+	 */
65
+	public function hasQuestions(): bool
66
+	{
67
+		return $this->has_questions;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param EE_Registration $registration
73
+	 * @param bool            $copy_attendee_info
74
+	 * @param callable        $enablePrintCopyInfo
75
+	 * @return array
76
+	 * @throws EE_Error
77
+	 * @throws ReflectionException
78
+	 */
79
+	private function generateFormArgs(
80
+		EE_Registration $registration,
81
+		bool $copy_attendee_info,
82
+		callable $enablePrintCopyInfo
83
+	): array {
84
+		static $attendee_nmbr = 1;
85
+		$form_args = [];
86
+		// verify that registration has valid event
87
+		if ($registration->event() instanceof EE_Event) {
88
+			$field_name      = 'Event_Question_Group.' . $this->event_question_group_model->fieldNameForContext(
89
+				$registration->is_primary_registrant()
90
+			);
91
+			$question_groups = $registration->event()->question_groups(
92
+				apply_filters(
93
+					'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__question_groups_query_parameters',
94
+					[
95
+						[
96
+							'Event.EVT_ID' => $registration->event()->ID(),
97
+							$field_name    => true,
98
+							'QSG_deleted'  => false,
99
+						],
100
+						'order_by' => ['QSG_order' => 'ASC'],
101
+					],
102
+					$registration,
103
+					$this
104
+				)
105
+			);
106
+			if ($question_groups) {
107
+				// array of params to pass to parent constructor
108
+				$form_args = [
109
+					'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
110
+					'html_class'      => 'ee-reg-form-attendee-dv',
111
+					'html_style'      => $this->reg_step->checkout->admin_request
112
+						? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
113
+						: '',
114
+					'subsections'     => [],
115
+					'layout_strategy' => new EE_Fieldset_Section_Layout(
116
+						[
117
+							'legend_class' => 'spco-attendee-lgnd',
118
+							'legend_text'  => sprintf(
119
+								esc_html_x(
120
+									'Attendee %d',
121
+									'Attendee 123',
122
+									'event_espresso'
123
+								),
124
+								$attendee_nmbr
125
+							),
126
+						]
127
+					),
128
+				];
129
+				foreach ($question_groups as $question_group) {
130
+					if ($question_group instanceof EE_Question_Group) {
131
+						$question_group_reg_form = LoaderFactory::getNew(
132
+							RegFormQuestionGroup::class,
133
+							[$registration, $question_group, $this->reg_step]
134
+						);
135
+						$form_args['subsections'][ $question_group->identifier() ] = apply_filters(
136
+							'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__question_group_reg_form',
137
+							$question_group_reg_form,
138
+							$registration,
139
+							$question_group,
140
+							$this
141
+						);
142
+					}
143
+				}
144
+				// add hidden input
145
+				$form_args['subsections']['additional_attendee_reg_info'] = $this->additionalAttendeeRegInfoInput(
146
+					$registration
147
+				);
148
+
149
+				// If we have question groups for additional attendees, then display the copy options
150
+				$printCopyInfo = apply_filters(
151
+					'FHEE__EventEspresso_core_domain_services_registration_form_v1_RegistrantForm__generateFormArgs__printCopyInfo',
152
+					$attendee_nmbr > 1 && $copy_attendee_info,
153
+					$attendee_nmbr,
154
+					$registration,
155
+					$this
156
+				);
157
+				if ($printCopyInfo) {
158
+					$enablePrintCopyInfo();
159
+				}
160
+
161
+
162
+				if ($registration->is_primary_registrant()) {
163
+					// generate hidden input
164
+					$form_args['subsections']['primary_registrant'] = $this->additionalPrimaryRegistrantInputs(
165
+						$registration
166
+					);
167
+				}
168
+			}
169
+		}
170
+		$attendee_nmbr++;
171
+
172
+		// Increment the reg forms number if form is valid.
173
+		if (! empty($form_args)) {
174
+			$this->has_questions = true;
175
+		}
176
+
177
+		return $form_args;
178
+	}
179
+
180
+
181
+	/**
182
+	 * @param EE_Registration $registration
183
+	 * @return EE_Form_Input_Base
184
+	 * @throws EE_Error
185
+	 */
186
+	private function additionalAttendeeRegInfoInput(EE_Registration $registration)
187
+	{
188
+		// generate hidden input
189
+		return new EE_Hidden_Input(
190
+			[
191
+				'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
192
+				'default' => true,
193
+			]
194
+		);
195
+	}
196
+
197
+
198
+	/**
199
+	 * @param EE_Registration $registration
200
+	 * @return    EE_Form_Input_Base
201
+	 * @throws EE_Error
202
+	 */
203
+	private function additionalPrimaryRegistrantInputs(EE_Registration $registration)
204
+	{
205
+		// generate hidden input
206
+		return new EE_Hidden_Input(
207
+			[
208
+				'html_id' => 'primary_registrant',
209
+				'default' => $registration->reg_url_link(),
210
+			]
211
+		);
212
+	}
213 213
 }
Please login to merge, or discard this patch.
core/libraries/messages/EE_messenger.lib.php 2 patches
Indentation   +765 added lines, -765 removed lines patch added patch discarded remove patch
@@ -16,182 +16,182 @@  discard block
 block discarded – undo
16 16
  */
17 17
 abstract class EE_messenger extends EE_Messages_Base
18 18
 {
19
-    /**
20
-     * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
21
-     * This property gets set by the _set_default_message_types() method.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $_default_message_types = array();
19
+	/**
20
+	 * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
21
+	 * This property gets set by the _set_default_message_types() method.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $_default_message_types = array();
26 26
 
27 27
 
28 28
 
29 29
 
30
-    /**
31
-     * This property holds the message types that are valid for use with this messenger.
32
-     * It gets set by the _set_valid_message_types() method.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_valid_message_types = array();
30
+	/**
31
+	 * This property holds the message types that are valid for use with this messenger.
32
+	 * It gets set by the _set_valid_message_types() method.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_valid_message_types = array();
37 37
 
38 38
 
39 39
 
40
-    /**
41
-     * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
42
-     *
43
-     * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
44
-     *
45
-     * Array should be in this format:
46
-     *
47
-     * array(
48
-     *  'field_name(i.e.to)' => array(
49
-     *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
50
-     *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
51
-     *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
52
-     *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
53
-     *  )
54
-     * )
55
-     *
56
-     * @var array
57
-     */
58
-    protected $_validator_config = array();
40
+	/**
41
+	 * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
42
+	 *
43
+	 * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
44
+	 *
45
+	 * Array should be in this format:
46
+	 *
47
+	 * array(
48
+	 *  'field_name(i.e.to)' => array(
49
+	 *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
50
+	 *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
51
+	 *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
52
+	 *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
53
+	 *  )
54
+	 * )
55
+	 *
56
+	 * @var array
57
+	 */
58
+	protected $_validator_config = array();
59 59
 
60 60
 
61 61
 
62
-    /**
63
-     * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
64
-     * @var object
65
-     */
66
-    protected $_EEM_data;
62
+	/**
63
+	 * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
64
+	 * @var object
65
+	 */
66
+	protected $_EEM_data;
67 67
 
68 68
 
69 69
 
70
-    /**
71
-     * this property just holds an array of the various template refs.
72
-     * @var array
73
-     */
74
-    protected $_template_fields = array();
70
+	/**
71
+	 * this property just holds an array of the various template refs.
72
+	 * @var array
73
+	 */
74
+	protected $_template_fields = array();
75 75
 
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     * This holds an array of the arguments used in parsing a template for the sender.
81
-     * @var array
82
-     */
83
-    protected $_template_args = array();
79
+	/**
80
+	 * This holds an array of the arguments used in parsing a template for the sender.
81
+	 * @var array
82
+	 */
83
+	protected $_template_args = array();
84 84
 
85 85
 
86 86
 
87 87
 
88 88
 
89 89
 
90
-    /**
91
-     * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
92
-     *
93
-     * @protected
94
-     * @var array
95
-     */
96
-    protected $_test_settings_fields = array();
90
+	/**
91
+	 * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
92
+	 *
93
+	 * @protected
94
+	 * @var array
95
+	 */
96
+	protected $_test_settings_fields = array();
97 97
 
98 98
 
99 99
 
100 100
 
101 101
 
102 102
 
103
-    /**
104
-     * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
105
-     *
106
-     * @since 4.5.0
107
-     *
108
-     * @var EE_Messages_Template_Pack
109
-     */
110
-    protected $_tmp_pack;
103
+	/**
104
+	 * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
105
+	 *
106
+	 * @since 4.5.0
107
+	 *
108
+	 * @var EE_Messages_Template_Pack
109
+	 */
110
+	protected $_tmp_pack;
111 111
 
112 112
 
113 113
 
114 114
 
115
-    /**
116
-     * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
117
-     *
118
-     * @since 4.5.0
119
-     *
120
-     * @var string
121
-     */
122
-    protected $_variation;
115
+	/**
116
+	 * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
117
+	 *
118
+	 * @since 4.5.0
119
+	 *
120
+	 * @var string
121
+	 */
122
+	protected $_variation;
123 123
 
124 124
 
125 125
 
126 126
 
127 127
 
128
-    /**
129
-     * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
130
-     *
131
-     *  - template pack
132
-     *  - template variation
133
-     *
134
-     * @since 4.5.0
135
-     *
136
-     * @var stdClass
137
-     */
138
-    protected $_supports_labels;
128
+	/**
129
+	 * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
130
+	 *
131
+	 *  - template pack
132
+	 *  - template variation
133
+	 *
134
+	 * @since 4.5.0
135
+	 *
136
+	 * @var stdClass
137
+	 */
138
+	protected $_supports_labels;
139 139
 
140 140
 
141 141
 
142 142
 
143 143
 
144
-    /**
145
-     * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
146
-     *
147
-     * @var EE_message_type
148
-     */
149
-    protected $_incoming_message_type;
144
+	/**
145
+	 * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
146
+	 *
147
+	 * @var EE_message_type
148
+	 */
149
+	protected $_incoming_message_type;
150 150
 
151 151
 
152 152
 
153
-    /**
154
-     * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
155
-     *
156
-     * @var bool
157
-     */
158
-    public $activate_on_install = false;
153
+	/**
154
+	 * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
155
+	 *
156
+	 * @var bool
157
+	 */
158
+	public $activate_on_install = false;
159 159
 
160 160
 
161 161
 
162 162
 
163 163
 
164
-    public function __construct()
165
-    {
166
-        $this->_EEM_data = EEM_Message_Template_Group::instance();
167
-        $this->_messages_item_type = 'messenger';
164
+	public function __construct()
165
+	{
166
+		$this->_EEM_data = EEM_Message_Template_Group::instance();
167
+		$this->_messages_item_type = 'messenger';
168 168
 
169
-        parent::__construct();
169
+		parent::__construct();
170 170
 
171
-        $this->_set_test_settings_fields();
172
-        $this->_set_template_fields();
173
-        $this->_set_default_message_types();
174
-        $this->_set_valid_message_types();
175
-        $this->_set_validator_config();
171
+		$this->_set_test_settings_fields();
172
+		$this->_set_template_fields();
173
+		$this->_set_default_message_types();
174
+		$this->_set_valid_message_types();
175
+		$this->_set_validator_config();
176 176
 
177 177
 
178
-        $this->_supports_labels = new stdClass();
179
-        $this->_set_supports_labels();
180
-    }
178
+		$this->_supports_labels = new stdClass();
179
+		$this->_set_supports_labels();
180
+	}
181 181
 
182 182
 
183 183
 
184 184
 
185 185
 
186
-    /**
187
-     * _set_template_fields
188
-     * This sets up the fields that a messenger requires for the message to go out.
189
-     *
190
-     * @abstract
191
-     * @access  protected
192
-     * @return void
193
-     */
194
-    abstract protected function _set_template_fields();
186
+	/**
187
+	 * _set_template_fields
188
+	 * This sets up the fields that a messenger requires for the message to go out.
189
+	 *
190
+	 * @abstract
191
+	 * @access  protected
192
+	 * @return void
193
+	 */
194
+	abstract protected function _set_template_fields();
195 195
 
196 196
 
197 197
 
@@ -201,14 +201,14 @@  discard block
 block discarded – undo
201 201
 
202 202
 
203 203
 
204
-    /**
205
-     * This method sets the _default_message_type property (see definition in docs attached to property)
206
-     *
207
-     * @abstract
208
-     * @access protected
209
-     * @return void
210
-     */
211
-    abstract protected function _set_default_message_types();
204
+	/**
205
+	 * This method sets the _default_message_type property (see definition in docs attached to property)
206
+	 *
207
+	 * @abstract
208
+	 * @access protected
209
+	 * @return void
210
+	 */
211
+	abstract protected function _set_default_message_types();
212 212
 
213 213
 
214 214
 
@@ -216,15 +216,15 @@  discard block
 block discarded – undo
216 216
 
217 217
 
218 218
 
219
-    /**
220
-     * Sets the _valid_message_types property (see definition in cods attached to property)
221
-     *
222
-     * @since 4.5.0
223
-     *
224
-     * @abstract
225
-     * @return void
226
-     */
227
-    abstract protected function _set_valid_message_types();
219
+	/**
220
+	 * Sets the _valid_message_types property (see definition in cods attached to property)
221
+	 *
222
+	 * @since 4.5.0
223
+	 *
224
+	 * @abstract
225
+	 * @return void
226
+	 */
227
+	abstract protected function _set_valid_message_types();
228 228
 
229 229
 
230 230
 
@@ -232,171 +232,171 @@  discard block
 block discarded – undo
232 232
 
233 233
 
234 234
 
235
-    /**
236
-     * Child classes must declare the $_validator_config property using this method.
237
-     * See comments for $_validator_config for details on what it is used for.
238
-     *
239
-     * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
240
-     *
241
-     * @access protected
242
-     * @return void
243
-     */
244
-    abstract protected function _set_validator_config();
235
+	/**
236
+	 * Child classes must declare the $_validator_config property using this method.
237
+	 * See comments for $_validator_config for details on what it is used for.
238
+	 *
239
+	 * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
240
+	 *
241
+	 * @access protected
242
+	 * @return void
243
+	 */
244
+	abstract protected function _set_validator_config();
245 245
 
246 246
 
247 247
 
248 248
 
249 249
 
250 250
 
251
-    /**
252
-     * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
253
-     *
254
-     * @return bool|WP_Error
255
-     * @throw \Exception
256
-     */
257
-    abstract protected function _send_message();
251
+	/**
252
+	 * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
253
+	 *
254
+	 * @return bool|WP_Error
255
+	 * @throw \Exception
256
+	 */
257
+	abstract protected function _send_message();
258 258
 
259 259
 
260 260
 
261 261
 
262
-    /**
263
-     * We give you pretty previews of the messages!
264
-     * @return string html body for message content.
265
-     */
266
-    abstract protected function _preview();
262
+	/**
263
+	 * We give you pretty previews of the messages!
264
+	 * @return string html body for message content.
265
+	 */
266
+	abstract protected function _preview();
267 267
 
268 268
 
269 269
 
270 270
 
271
-    /**
272
-     * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
273
-     *
274
-     * @since 4.5.0
275
-     *
276
-     * @return void
277
-     */
278
-    public function enqueue_scripts_styles()
279
-    {
280
-        do_action('AHEE__EE_messenger__enqueue_scripts_styles');
281
-    }
271
+	/**
272
+	 * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
273
+	 *
274
+	 * @since 4.5.0
275
+	 *
276
+	 * @return void
277
+	 */
278
+	public function enqueue_scripts_styles()
279
+	{
280
+		do_action('AHEE__EE_messenger__enqueue_scripts_styles');
281
+	}
282 282
 
283 283
 
284 284
 
285 285
 
286 286
 
287
-    /**
288
-     * This is used to indicate whether a messenger must be sent immediately or not.
289
-     * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
290
-     * away.  The PDF messenger is similar.
291
-     *
292
-     * This flag thus overrides any priorities that may be set on the message type used to generate the message.
293
-     *
294
-     * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
295
-     *
296
-     * @since  4.9.0
297
-     * @return bool
298
-     */
299
-    public function send_now()
300
-    {
301
-        return false;
302
-    }
287
+	/**
288
+	 * This is used to indicate whether a messenger must be sent immediately or not.
289
+	 * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
290
+	 * away.  The PDF messenger is similar.
291
+	 *
292
+	 * This flag thus overrides any priorities that may be set on the message type used to generate the message.
293
+	 *
294
+	 * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
295
+	 *
296
+	 * @since  4.9.0
297
+	 * @return bool
298
+	 */
299
+	public function send_now()
300
+	{
301
+		return false;
302
+	}
303 303
 
304 304
 
305 305
 
306 306
 
307 307
 
308
-    /**
309
-     * This is a way for a messenger to indicate whether it allows an empty to field or not.
310
-     * Note: If the generated message is a for a preview, this value is ignored.
311
-     * @since 4.9.0
312
-     * @return bool
313
-     */
314
-    public function allow_empty_to_field()
315
-    {
316
-        return false;
317
-    }
308
+	/**
309
+	 * This is a way for a messenger to indicate whether it allows an empty to field or not.
310
+	 * Note: If the generated message is a for a preview, this value is ignored.
311
+	 * @since 4.9.0
312
+	 * @return bool
313
+	 */
314
+	public function allow_empty_to_field()
315
+	{
316
+		return false;
317
+	}
318 318
 
319 319
 
320 320
 
321 321
 
322 322
 
323
-    /**
324
-     * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
325
-     * @see property definition for info on how its formatted.
326
-     *
327
-     * @since 4.5.0;
328
-     * @return void
329
-     */
330
-    protected function _set_supports_labels()
331
-    {
332
-        $this->_set_supports_labels_defaults();
333
-    }
323
+	/**
324
+	 * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
325
+	 * @see property definition for info on how its formatted.
326
+	 *
327
+	 * @since 4.5.0;
328
+	 * @return void
329
+	 */
330
+	protected function _set_supports_labels()
331
+	{
332
+		$this->_set_supports_labels_defaults();
333
+	}
334 334
 
335 335
 
336 336
 
337 337
 
338 338
 
339
-    /**
340
-     * Sets the defaults for the _supports_labels property.
341
-     *
342
-     * @since 4.5.0
343
-     *
344
-     * @return void
345
-     */
346
-    private function _set_supports_labels_defaults()
347
-    {
348
-        $this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
349
-        $this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
350
-        $this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
339
+	/**
340
+	 * Sets the defaults for the _supports_labels property.
341
+	 *
342
+	 * @since 4.5.0
343
+	 *
344
+	 * @return void
345
+	 */
346
+	private function _set_supports_labels_defaults()
347
+	{
348
+		$this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
349
+		$this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
350
+		$this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
351 351
 
352
-        $this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
352
+		$this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
353 353
 
354
-        $this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
355
-    }
354
+		$this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
355
+	}
356 356
 
357 357
 
358 358
 
359 359
 
360 360
 
361
-    /**
362
-     * This returns the _supports_labels property.
363
-     *
364
-     * @since 4.5.0
365
-     *
366
-     * @return stdClass
367
-     */
368
-    public function get_supports_labels()
369
-    {
370
-        if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
371
-            $this->_set_supports_labels_defaults();
372
-        }
373
-        return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
374
-    }
361
+	/**
362
+	 * This returns the _supports_labels property.
363
+	 *
364
+	 * @since 4.5.0
365
+	 *
366
+	 * @return stdClass
367
+	 */
368
+	public function get_supports_labels()
369
+	{
370
+		if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
371
+			$this->_set_supports_labels_defaults();
372
+		}
373
+		return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
374
+	}
375 375
 
376 376
 
377 377
 
378 378
 
379
-    /**
380
-     * Used to retrieve a variation (typically the path/url to a css file)
381
-     *
382
-     * @since 4.5.0
383
-     *
384
-     * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
385
-     * @param string                    $message_type_name The name property of the message type that we need the variation for.
386
-     * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
387
-     * @param string                    $type What variation type to return. Default is 'main'.
388
-     * @param string               $variation What variation for the template pack
389
-     * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
390
-     *
391
-     * @return string                    path or url for the requested variation.
392
-     */
393
-    public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
394
-    {
395
-        $this->_tmp_pack = $pack;
396
-        $variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
397
-        $variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
398
-        return $variation_path;
399
-    }
379
+	/**
380
+	 * Used to retrieve a variation (typically the path/url to a css file)
381
+	 *
382
+	 * @since 4.5.0
383
+	 *
384
+	 * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
385
+	 * @param string                    $message_type_name The name property of the message type that we need the variation for.
386
+	 * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
387
+	 * @param string                    $type What variation type to return. Default is 'main'.
388
+	 * @param string               $variation What variation for the template pack
389
+	 * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
390
+	 *
391
+	 * @return string                    path or url for the requested variation.
392
+	 */
393
+	public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
394
+	{
395
+		$this->_tmp_pack = $pack;
396
+		$variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
397
+		$variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
398
+		return $variation_path;
399
+	}
400 400
 
401 401
 
402 402
 
@@ -404,194 +404,194 @@  discard block
 block discarded – undo
404 404
 
405 405
 
406 406
 
407
-    /**
408
-     * This just returns the default message types associated with this messenger when it is first activated.
409
-     *
410
-     * @access public
411
-     * @return array
412
-     */
413
-    public function get_default_message_types()
414
-    {
415
-        $class = get_class($this);
407
+	/**
408
+	 * This just returns the default message types associated with this messenger when it is first activated.
409
+	 *
410
+	 * @access public
411
+	 * @return array
412
+	 */
413
+	public function get_default_message_types()
414
+	{
415
+		$class = get_class($this);
416 416
 
417
-        // messenger specific filter
418
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
417
+		// messenger specific filter
418
+		$default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
419 419
 
420
-        // all messengers filter
421
-        $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
422
-        return $default_types;
423
-    }
420
+		// all messengers filter
421
+		$default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
422
+		return $default_types;
423
+	}
424 424
 
425 425
 
426 426
 
427 427
 
428
-    /**
429
-     * Returns the valid message types associated with this messenger.
430
-     *
431
-     * @since 4.5.0
432
-     *
433
-     * @return array
434
-     */
435
-    public function get_valid_message_types()
436
-    {
437
-        $class = get_class($this);
438
-
439
-        // messenger specific filter
440
-        // messenger specific filter
441
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
442
-
443
-        // all messengers filter
444
-        $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
445
-        return $valid_types;
446
-    }
447
-
448
-
449
-
450
-
451
-
452
-    /**
453
-     * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
454
-     *
455
-     * @access public
456
-     * @param array $new_config Whatever is put in here will reset the _validator_config property
457
-     */
458
-    public function set_validator_config($new_config)
459
-    {
460
-        $this->_validator_config = $new_config;
461
-    }
462
-
463
-
464
-
465
-
466
-    /**
467
-     * This returns the _validator_config property
468
-     *
469
-     * @access public
470
-     * @return array
471
-     */
472
-    public function get_validator_config()
473
-    {
474
-        $class = get_class($this);
475
-
476
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
477
-        $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
478
-        return $config;
479
-    }
480
-
481
-
482
-
483
-
484
-    /**
485
-     * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
486
-     *
487
-     * @param string $page the slug of the EE admin page
488
-     * @param array $message_types an array of active message type objects
489
-     * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
490
-     * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
491
-     * @access public
492
-     * @return string content for page
493
-     */
494
-    public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
495
-    {
496
-        return $this->_get_admin_page_content($page, $action, $extra, $message_types);
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * @param $message_types
503
-     * @param array $extra
504
-     * @return mixed|string
505
-     */
506
-    protected function _get_admin_content_events_edit($message_types, $extra)
507
-    {
508
-        // defaults
509
-        $template_args = array();
510
-        $selector_rows = '';
511
-
512
-        // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
513
-        $event_id = isset($extra['event']) ? $extra['event'] : null;
514
-
515
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
517
-
518
-        // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
519
-        $global_templates = EEM_Message_Template_Group::instance()->get_all(
520
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
521
-        );
522
-        $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
523
-            $event_id,
524
-            array(
525
-                'MTP_messenger' => $this->name,
526
-                'MTP_is_active' => true
527
-            )
528
-        );
529
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
530
-
531
-        // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
532
-        foreach ($global_templates as $mtpgID => $mtpg) {
533
-            if ($mtpg instanceof EE_Message_Template_Group) {
534
-                // verify this message type is supposed to show on this page
535
-                $mtp_obj = $mtpg->message_type_obj();
536
-                if (! $mtp_obj instanceof EE_message_type) {
537
-                    continue;
538
-                }
539
-                $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
540
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
541
-                    continue;
542
-                }
543
-                $select_values = array();
544
-                $select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
545
-                $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
546
-                // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
547
-                if (! $mtpg->get('MTP_is_override')) {
548
-                    // any custom templates for this message type?
549
-                    $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
550
-                    foreach ($custom_templates as $cmtpgID => $cmtpg) {
551
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
552
-                        $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
553
-                    }
554
-                }
555
-                // if there is no $default_value then we set it as the global
556
-                $default_value = empty($default_value) ? $mtpgID : $default_value;
557
-                $c_config = $mtpg->contexts_config();
558
-                $edit_context = key(array_slice($c_config, -1));
559
-                $edit_url_query_args = [
560
-                    'page' => 'espresso_messages',
561
-                    'action' => 'edit_message_template',
562
-                    'id' => $default_value,
563
-                    'evt_id' => $event_id,
564
-                    'context' => $edit_context,
565
-                ];
566
-                $edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
567
-                $create_url_query_args = [
568
-                    'page' => 'espresso_messages',
569
-                    'action' => 'add_new_message_template',
570
-                    'GRP_ID' => $default_value,
571
-                    'message_type' => $mtpg->message_type(),
572
-                    'messenger' => $this->name
573
-                ];
574
-                $mt_slug = $mtpg->message_type();
575
-                $create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
576
-                $st_args['mtpgID'] = $mtpgID;
577
-                $st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
578
-                $st_args['mt_slug'] = $mt_slug;
579
-                $st_args['messenger_slug'] = $this->name;
580
-                $st_args['selector'] = EEH_Form_Fields::select_input(
581
-                    'event_message_templates_relation[' . $mtpgID . ']',
582
-                    $select_values,
583
-                    $default_value,
584
-                    'data-messenger="' . $this->name . '" data-messagetype="' . $mt_slug . '"',
585
-                    'message-template-selector'
586
-                );
587
-                $new_template_name = sprintf(
588
-                    esc_html__('Custom %1$s', 'event_espresso'),
589
-                    $st_args['mt_name'] ?? esc_html__('Template', 'event_espresso')
590
-                );
591
-                // note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
592
-                $st_args['create_button'] = $mtpg->get('MTP_is_override')
593
-                    ? ''
594
-                    : '
428
+	/**
429
+	 * Returns the valid message types associated with this messenger.
430
+	 *
431
+	 * @since 4.5.0
432
+	 *
433
+	 * @return array
434
+	 */
435
+	public function get_valid_message_types()
436
+	{
437
+		$class = get_class($this);
438
+
439
+		// messenger specific filter
440
+		// messenger specific filter
441
+		$valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
442
+
443
+		// all messengers filter
444
+		$valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
445
+		return $valid_types;
446
+	}
447
+
448
+
449
+
450
+
451
+
452
+	/**
453
+	 * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
454
+	 *
455
+	 * @access public
456
+	 * @param array $new_config Whatever is put in here will reset the _validator_config property
457
+	 */
458
+	public function set_validator_config($new_config)
459
+	{
460
+		$this->_validator_config = $new_config;
461
+	}
462
+
463
+
464
+
465
+
466
+	/**
467
+	 * This returns the _validator_config property
468
+	 *
469
+	 * @access public
470
+	 * @return array
471
+	 */
472
+	public function get_validator_config()
473
+	{
474
+		$class = get_class($this);
475
+
476
+		$config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
477
+		$config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
478
+		return $config;
479
+	}
480
+
481
+
482
+
483
+
484
+	/**
485
+	 * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
486
+	 *
487
+	 * @param string $page the slug of the EE admin page
488
+	 * @param array $message_types an array of active message type objects
489
+	 * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
490
+	 * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
491
+	 * @access public
492
+	 * @return string content for page
493
+	 */
494
+	public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
495
+	{
496
+		return $this->_get_admin_page_content($page, $action, $extra, $message_types);
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * @param $message_types
503
+	 * @param array $extra
504
+	 * @return mixed|string
505
+	 */
506
+	protected function _get_admin_content_events_edit($message_types, $extra)
507
+	{
508
+		// defaults
509
+		$template_args = array();
510
+		$selector_rows = '';
511
+
512
+		// we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
513
+		$event_id = isset($extra['event']) ? $extra['event'] : null;
514
+
515
+		$template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
+		$template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
517
+
518
+		// array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
519
+		$global_templates = EEM_Message_Template_Group::instance()->get_all(
520
+			array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
521
+		);
522
+		$templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
523
+			$event_id,
524
+			array(
525
+				'MTP_messenger' => $this->name,
526
+				'MTP_is_active' => true
527
+			)
528
+		);
529
+		$templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
530
+
531
+		// so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
532
+		foreach ($global_templates as $mtpgID => $mtpg) {
533
+			if ($mtpg instanceof EE_Message_Template_Group) {
534
+				// verify this message type is supposed to show on this page
535
+				$mtp_obj = $mtpg->message_type_obj();
536
+				if (! $mtp_obj instanceof EE_message_type) {
537
+					continue;
538
+				}
539
+				$mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
540
+				if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
541
+					continue;
542
+				}
543
+				$select_values = array();
544
+				$select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
545
+				$default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
546
+				// if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
547
+				if (! $mtpg->get('MTP_is_override')) {
548
+					// any custom templates for this message type?
549
+					$custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
550
+					foreach ($custom_templates as $cmtpgID => $cmtpg) {
551
+						$select_values[ $cmtpgID ] = $cmtpg->name();
552
+						$default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
553
+					}
554
+				}
555
+				// if there is no $default_value then we set it as the global
556
+				$default_value = empty($default_value) ? $mtpgID : $default_value;
557
+				$c_config = $mtpg->contexts_config();
558
+				$edit_context = key(array_slice($c_config, -1));
559
+				$edit_url_query_args = [
560
+					'page' => 'espresso_messages',
561
+					'action' => 'edit_message_template',
562
+					'id' => $default_value,
563
+					'evt_id' => $event_id,
564
+					'context' => $edit_context,
565
+				];
566
+				$edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
567
+				$create_url_query_args = [
568
+					'page' => 'espresso_messages',
569
+					'action' => 'add_new_message_template',
570
+					'GRP_ID' => $default_value,
571
+					'message_type' => $mtpg->message_type(),
572
+					'messenger' => $this->name
573
+				];
574
+				$mt_slug = $mtpg->message_type();
575
+				$create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
576
+				$st_args['mtpgID'] = $mtpgID;
577
+				$st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
578
+				$st_args['mt_slug'] = $mt_slug;
579
+				$st_args['messenger_slug'] = $this->name;
580
+				$st_args['selector'] = EEH_Form_Fields::select_input(
581
+					'event_message_templates_relation[' . $mtpgID . ']',
582
+					$select_values,
583
+					$default_value,
584
+					'data-messenger="' . $this->name . '" data-messagetype="' . $mt_slug . '"',
585
+					'message-template-selector'
586
+				);
587
+				$new_template_name = sprintf(
588
+					esc_html__('Custom %1$s', 'event_espresso'),
589
+					$st_args['mt_name'] ?? esc_html__('Template', 'event_espresso')
590
+				);
591
+				// note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
592
+				$st_args['create_button'] = $mtpg->get('MTP_is_override')
593
+					? ''
594
+					: '
595 595
                     <a data-messenger="' . $this->name . '"
596 596
                        data-messagetype="' . $mt_slug . '"
597 597
                        data-new_template_name="' . $new_template_name . '"
@@ -602,18 +602,18 @@  discard block
 block discarded – undo
602 602
                     >
603 603
                         ' . esc_html__('Create New Custom', 'event_espresso') . '
604 604
                     </a>';
605
-                $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can(
606
-                    'ee_edit_messages',
607
-                    'espresso_messages_add_new_message_template'
608
-                )
609
-                    ? $st_args['create_button']
610
-                    : '';
611
-                $st_args['edit_button']   = EE_Registry::instance()->CAP->current_user_can(
612
-                    'ee_edit_message',
613
-                    'espresso_messages_edit_message_template',
614
-                    $mtpgID
615
-                )
616
-                    ? '
605
+				$st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can(
606
+					'ee_edit_messages',
607
+					'espresso_messages_add_new_message_template'
608
+				)
609
+					? $st_args['create_button']
610
+					: '';
611
+				$st_args['edit_button']   = EE_Registry::instance()->CAP->current_user_can(
612
+					'ee_edit_message',
613
+					'espresso_messages_edit_message_template',
614
+					$mtpgID
615
+				)
616
+					? '
617 617
                     <a data-messagetype="' . $mt_slug . '"
618 618
                        data-grpid="' . $default_value . '"
619 619
                        target="_blank"
@@ -622,322 +622,322 @@  discard block
 block discarded – undo
622 622
                     >
623 623
                         ' . esc_html__('Edit', 'event_espresso') . '
624 624
                     </a>'
625
-                    : '';
626
-                $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
627
-            }
628
-        }
629
-
630
-        // if no selectors present then get out.
631
-        if (empty($selector_rows)) {
632
-            return '';
633
-        }
634
-
635
-        $template_args['selector_rows'] = $selector_rows;
636
-        return EEH_Template::display_template($template_wrapper_path, $template_args, true);
637
-    }
638
-
639
-
640
-
641
-
642
-
643
-
644
-    /**
645
-     * get_template_fields
646
-     *
647
-     * @access public
648
-     * @return array $this->_template_fields
649
-     */
650
-    public function get_template_fields()
651
-    {
652
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
653
-        $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
654
-        return $template_fields;
655
-    }
656
-
657
-
658
-
659
-
660
-    /** SETUP METHODS **/
661
-    /**
662
-     * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
663
-     * @param string $item
664
-     * @param mixed $value
665
-     */
666
-    protected function _set_template_value($item, $value)
667
-    {
668
-        if (array_key_exists($item, $this->_template_fields)) {
669
-            $prop = '_' . $item;
670
-            $this->{$prop} = $value;
671
-        }
672
-    }
673
-
674
-    /**
675
-     * Sets up the message for sending.
676
-     *
677
-     * @param  EE_message $message the message object that contains details about the message.
678
-     * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
679
-     *
680
-     * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
681
-     *              added to EE_Error.
682
-     *              true = message sent successfully
683
-     *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
684
-     *              Throwing a SendMessageException means the message failed sending and cannot be retried.
685
-     *
686
-     * @throws SendMessageException
687
-     */
688
-    final public function send_message($message, EE_message_type $message_type)
689
-    {
690
-        try {
691
-            $this->_validate_and_setup($message);
692
-            $this->_incoming_message_type = $message_type;
693
-            $response = $this->_send_message();
694
-            if ($response instanceof WP_Error) {
695
-                EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
696
-                $response = false;
697
-            }
698
-        } catch (\Exception $e) {
699
-            // convert to an instance of SendMessageException
700
-            throw new SendMessageException($e->getMessage());
701
-        }
702
-        return $response;
703
-    }
704
-
705
-
706
-
707
-    /**
708
-     * Sets up and returns message preview
709
-     * @param  EE_Message $message incoming message object
710
-     * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
711
-     * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
712
-     * @return string          return the message html content
713
-     */
714
-    public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
715
-    {
716
-        $this->_validate_and_setup($message);
717
-
718
-        $this->_incoming_message_type = $message_type;
719
-
720
-        if ($send) {
721
-            // are we overriding any existing template fields?
722
-            $settings = apply_filters(
723
-                'FHEE__EE_messenger__get_preview__messenger_test_settings',
724
-                $this->get_existing_test_settings(),
725
-                $this,
726
-                $send,
727
-                $message,
728
-                $message_type
729
-            );
730
-            if (! empty($settings)) {
731
-                foreach ($settings as $field => $value) {
732
-                    $this->_set_template_value($field, $value);
733
-                }
734
-            }
735
-        }
736
-
737
-        // enqueue preview js so that any links/buttons on the page are disabled.
738
-        if (! $send) {
739
-            // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
740
-            // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
741
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
742
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
743
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
744
-        }
745
-
746
-        return $send ? $this->_send_message() : $this->_preview();
747
-    }
748
-
749
-
750
-
751
-
752
-    /**
753
-     * Callback for enqueue_scripts so that we setup the preview script for all previews.
754
-     *
755
-     * @since 4.5.0
756
-     *
757
-     * @return void
758
-     */
759
-    public function add_preview_script()
760
-    {
761
-        // error message
762
-        EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
763
-            __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
764
-        );
765
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
766
-        wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
767
-        wp_enqueue_script('ee-messages-preview-js');
768
-    }
769
-
770
-
771
-
772
-
773
-    /**
774
-     * simply validates the incoming message object and then sets up the properties for the messenger
775
-     * @param  EE_Message $message
776
-     * @throws EE_Error
777
-     */
778
-    protected function _validate_and_setup(EE_Message $message)
779
-    {
780
-        $template_pack = $message->get_template_pack();
781
-        $variation = $message->get_template_pack_variation();
782
-
783
-        // verify we have the required template pack value on the $message object.
784
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
785
-            throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
786
-        }
787
-
788
-        $this->_tmp_pack = $template_pack;
789
-
790
-        $this->_variation = $variation ? $variation : 'default';
791
-
792
-        $template_fields = $this->get_template_fields();
793
-
794
-        foreach ($template_fields as $template => $value) {
795
-            if ($template !== 'extra') {
796
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
797
-                $message_template_value = $column_value ? $column_value : null;
798
-                $this->_set_template_value($template, $message_template_value);
799
-            }
800
-        }
801
-    }
802
-
803
-
804
-
805
-    /**
806
-     * Utility method for child classes to get the contents of a template file and return
807
-     *
808
-     * We're assuming the child messenger class has already setup template args!
809
-     * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
810
-     * @return string
811
-     * @throws \EE_Error
812
-     */
813
-    protected function _get_main_template($preview = false)
814
-    {
815
-        $type = $preview ? 'preview' : 'main';
816
-
817
-        $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
818
-
819
-        // check file exists and is readable
820
-        if (!is_readable($wrapper_template)) {
821
-            throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
822
-        }
823
-
824
-        // add message type to template args
825
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
826
-
827
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
828
-    }
829
-
830
-
831
-
832
-    /**
833
-     * set the _test_settings_fields property
834
-     *
835
-     * @access protected
836
-     * @return void
837
-     */
838
-    protected function _set_test_settings_fields()
839
-    {
840
-        $this->_test_settings_fields = array();
841
-    }
842
-
843
-
844
-
845
-    /**
846
-     * return the _test_settings_fields property
847
-     * @return array
848
-     */
849
-    public function get_test_settings_fields()
850
-    {
851
-        return $this->_test_settings_fields;
852
-    }
853
-
854
-
855
-
856
-
857
-    /**
858
-     * This just returns any existing test settings that might be saved in the database
859
-     *
860
-     * @access public
861
-     * @return array
862
-     */
863
-    public function get_existing_test_settings()
864
-    {
865
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
866
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
867
-        $settings = $Message_Resource_Manager->get_active_messengers_option();
868
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
869
-    }
870
-
871
-
872
-
873
-    /**
874
-     * All this does is set the existing test settings (in the db) for the messenger
875
-     *
876
-     * @access public
877
-     * @param $settings
878
-     * @return bool success/fail
879
-     */
880
-    public function set_existing_test_settings($settings)
881
-    {
882
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
883
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
884
-        $existing = $Message_Resource_Manager->get_active_messengers_option();
885
-        $existing[ $this->name ]['test_settings'] = $settings;
886
-        return $Message_Resource_Manager->update_active_messengers_option($existing);
887
-    }
888
-
889
-
890
-
891
-    /**
892
-     * This just returns the field label for a given field setup in the _template_fields property.
893
-     *
894
-     * @since   4.3.0
895
-     *
896
-     * @param string $field The field to retrieve the label for
897
-     * @return string             The label
898
-     */
899
-    public function get_field_label($field)
900
-    {
901
-        // first let's see if the field requests is in the top level array.
902
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
903
-            return $this->_template[ $field ]['label'];
904
-        }
905
-
906
-        // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
907
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
908
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
909
-        }
910
-
911
-        // now it's possible this field may just be existing in any of the extra array items.
912
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
913
-            foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
914
-                if (!is_array($subfields)) {
915
-                    continue;
916
-                }
917
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
918
-                    return $subfields[ $field ]['label'];
919
-                }
920
-            }
921
-        }
922
-
923
-        // if we made it here then there's no label set so let's just return the $field.
924
-        return $field;
925
-    }
926
-
927
-
928
-
929
-
930
-    /**
931
-     * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
932
-     *
933
-     * @since 4.5.0
934
-     *
935
-     * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
936
-     *
937
-     * @return void
938
-     */
939
-    public function do_secondary_messenger_hooks($sending_messenger_name)
940
-    {
941
-        return;
942
-    }
625
+					: '';
626
+				$selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
627
+			}
628
+		}
629
+
630
+		// if no selectors present then get out.
631
+		if (empty($selector_rows)) {
632
+			return '';
633
+		}
634
+
635
+		$template_args['selector_rows'] = $selector_rows;
636
+		return EEH_Template::display_template($template_wrapper_path, $template_args, true);
637
+	}
638
+
639
+
640
+
641
+
642
+
643
+
644
+	/**
645
+	 * get_template_fields
646
+	 *
647
+	 * @access public
648
+	 * @return array $this->_template_fields
649
+	 */
650
+	public function get_template_fields()
651
+	{
652
+		$template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
653
+		$template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
654
+		return $template_fields;
655
+	}
656
+
657
+
658
+
659
+
660
+	/** SETUP METHODS **/
661
+	/**
662
+	 * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
663
+	 * @param string $item
664
+	 * @param mixed $value
665
+	 */
666
+	protected function _set_template_value($item, $value)
667
+	{
668
+		if (array_key_exists($item, $this->_template_fields)) {
669
+			$prop = '_' . $item;
670
+			$this->{$prop} = $value;
671
+		}
672
+	}
673
+
674
+	/**
675
+	 * Sets up the message for sending.
676
+	 *
677
+	 * @param  EE_message $message the message object that contains details about the message.
678
+	 * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
679
+	 *
680
+	 * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
681
+	 *              added to EE_Error.
682
+	 *              true = message sent successfully
683
+	 *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
684
+	 *              Throwing a SendMessageException means the message failed sending and cannot be retried.
685
+	 *
686
+	 * @throws SendMessageException
687
+	 */
688
+	final public function send_message($message, EE_message_type $message_type)
689
+	{
690
+		try {
691
+			$this->_validate_and_setup($message);
692
+			$this->_incoming_message_type = $message_type;
693
+			$response = $this->_send_message();
694
+			if ($response instanceof WP_Error) {
695
+				EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
696
+				$response = false;
697
+			}
698
+		} catch (\Exception $e) {
699
+			// convert to an instance of SendMessageException
700
+			throw new SendMessageException($e->getMessage());
701
+		}
702
+		return $response;
703
+	}
704
+
705
+
706
+
707
+	/**
708
+	 * Sets up and returns message preview
709
+	 * @param  EE_Message $message incoming message object
710
+	 * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
711
+	 * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
712
+	 * @return string          return the message html content
713
+	 */
714
+	public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
715
+	{
716
+		$this->_validate_and_setup($message);
717
+
718
+		$this->_incoming_message_type = $message_type;
719
+
720
+		if ($send) {
721
+			// are we overriding any existing template fields?
722
+			$settings = apply_filters(
723
+				'FHEE__EE_messenger__get_preview__messenger_test_settings',
724
+				$this->get_existing_test_settings(),
725
+				$this,
726
+				$send,
727
+				$message,
728
+				$message_type
729
+			);
730
+			if (! empty($settings)) {
731
+				foreach ($settings as $field => $value) {
732
+					$this->_set_template_value($field, $value);
733
+				}
734
+			}
735
+		}
736
+
737
+		// enqueue preview js so that any links/buttons on the page are disabled.
738
+		if (! $send) {
739
+			// the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
740
+			// it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
741
+			add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
742
+			add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
743
+			add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
744
+		}
745
+
746
+		return $send ? $this->_send_message() : $this->_preview();
747
+	}
748
+
749
+
750
+
751
+
752
+	/**
753
+	 * Callback for enqueue_scripts so that we setup the preview script for all previews.
754
+	 *
755
+	 * @since 4.5.0
756
+	 *
757
+	 * @return void
758
+	 */
759
+	public function add_preview_script()
760
+	{
761
+		// error message
762
+		EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
763
+			__('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
764
+		);
765
+		wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
766
+		wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
767
+		wp_enqueue_script('ee-messages-preview-js');
768
+	}
769
+
770
+
771
+
772
+
773
+	/**
774
+	 * simply validates the incoming message object and then sets up the properties for the messenger
775
+	 * @param  EE_Message $message
776
+	 * @throws EE_Error
777
+	 */
778
+	protected function _validate_and_setup(EE_Message $message)
779
+	{
780
+		$template_pack = $message->get_template_pack();
781
+		$variation = $message->get_template_pack_variation();
782
+
783
+		// verify we have the required template pack value on the $message object.
784
+		if (! $template_pack instanceof EE_Messages_Template_Pack) {
785
+			throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
786
+		}
787
+
788
+		$this->_tmp_pack = $template_pack;
789
+
790
+		$this->_variation = $variation ? $variation : 'default';
791
+
792
+		$template_fields = $this->get_template_fields();
793
+
794
+		foreach ($template_fields as $template => $value) {
795
+			if ($template !== 'extra') {
796
+				$column_value = $message->get_field_or_extra_meta('MSG_' . $template);
797
+				$message_template_value = $column_value ? $column_value : null;
798
+				$this->_set_template_value($template, $message_template_value);
799
+			}
800
+		}
801
+	}
802
+
803
+
804
+
805
+	/**
806
+	 * Utility method for child classes to get the contents of a template file and return
807
+	 *
808
+	 * We're assuming the child messenger class has already setup template args!
809
+	 * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
810
+	 * @return string
811
+	 * @throws \EE_Error
812
+	 */
813
+	protected function _get_main_template($preview = false)
814
+	{
815
+		$type = $preview ? 'preview' : 'main';
816
+
817
+		$wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
818
+
819
+		// check file exists and is readable
820
+		if (!is_readable($wrapper_template)) {
821
+			throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
822
+		}
823
+
824
+		// add message type to template args
825
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
826
+
827
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
828
+	}
829
+
830
+
831
+
832
+	/**
833
+	 * set the _test_settings_fields property
834
+	 *
835
+	 * @access protected
836
+	 * @return void
837
+	 */
838
+	protected function _set_test_settings_fields()
839
+	{
840
+		$this->_test_settings_fields = array();
841
+	}
842
+
843
+
844
+
845
+	/**
846
+	 * return the _test_settings_fields property
847
+	 * @return array
848
+	 */
849
+	public function get_test_settings_fields()
850
+	{
851
+		return $this->_test_settings_fields;
852
+	}
853
+
854
+
855
+
856
+
857
+	/**
858
+	 * This just returns any existing test settings that might be saved in the database
859
+	 *
860
+	 * @access public
861
+	 * @return array
862
+	 */
863
+	public function get_existing_test_settings()
864
+	{
865
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
866
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
867
+		$settings = $Message_Resource_Manager->get_active_messengers_option();
868
+		return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
869
+	}
870
+
871
+
872
+
873
+	/**
874
+	 * All this does is set the existing test settings (in the db) for the messenger
875
+	 *
876
+	 * @access public
877
+	 * @param $settings
878
+	 * @return bool success/fail
879
+	 */
880
+	public function set_existing_test_settings($settings)
881
+	{
882
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
883
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
884
+		$existing = $Message_Resource_Manager->get_active_messengers_option();
885
+		$existing[ $this->name ]['test_settings'] = $settings;
886
+		return $Message_Resource_Manager->update_active_messengers_option($existing);
887
+	}
888
+
889
+
890
+
891
+	/**
892
+	 * This just returns the field label for a given field setup in the _template_fields property.
893
+	 *
894
+	 * @since   4.3.0
895
+	 *
896
+	 * @param string $field The field to retrieve the label for
897
+	 * @return string             The label
898
+	 */
899
+	public function get_field_label($field)
900
+	{
901
+		// first let's see if the field requests is in the top level array.
902
+		if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
903
+			return $this->_template[ $field ]['label'];
904
+		}
905
+
906
+		// nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
907
+		if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
908
+			return $this->_template_fields['extra'][ $field ]['main']['label'];
909
+		}
910
+
911
+		// now it's possible this field may just be existing in any of the extra array items.
912
+		if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
913
+			foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
914
+				if (!is_array($subfields)) {
915
+					continue;
916
+				}
917
+				if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
918
+					return $subfields[ $field ]['label'];
919
+				}
920
+			}
921
+		}
922
+
923
+		// if we made it here then there's no label set so let's just return the $field.
924
+		return $field;
925
+	}
926
+
927
+
928
+
929
+
930
+	/**
931
+	 * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
932
+	 *
933
+	 * @since 4.5.0
934
+	 *
935
+	 * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
936
+	 *
937
+	 * @return void
938
+	 */
939
+	public function do_secondary_messenger_hooks($sending_messenger_name)
940
+	{
941
+		return;
942
+	}
943 943
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
         $class = get_class($this);
416 416
 
417 417
         // messenger specific filter
418
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
418
+        $default_types = apply_filters('FHEE__'.$class.'__get_default_message_types__default_types', $this->_default_message_types, $this);
419 419
 
420 420
         // all messengers filter
421 421
         $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 
439 439
         // messenger specific filter
440 440
         // messenger specific filter
441
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
441
+        $valid_types = apply_filters('FHEE__'.$class.'__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
442 442
 
443 443
         // all messengers filter
444 444
         $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
     {
474 474
         $class = get_class($this);
475 475
 
476
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
476
+        $config = apply_filters('FHEE__'.$class.'__get_validator_config', $this->_validator_config, $this);
477 477
         $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
478 478
         return $config;
479 479
     }
@@ -512,12 +512,12 @@  discard block
 block discarded – undo
512 512
         // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
513 513
         $event_id = isset($extra['event']) ? $extra['event'] : null;
514 514
 
515
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
515
+        $template_wrapper_path = EE_LIBRARIES.'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
+        $template_row_path = EE_LIBRARIES.'messages/messenger/admin_templates/event_switcher_row.template.php';
517 517
 
518 518
         // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
519 519
         $global_templates = EEM_Message_Template_Group::instance()->get_all(
520
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
520
+            array(array('MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true))
521 521
         );
522 522
         $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
523 523
             $event_id,
@@ -526,29 +526,29 @@  discard block
 block discarded – undo
526 526
                 'MTP_is_active' => true
527 527
             )
528 528
         );
529
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
529
+        $templates_for_event = ! empty($templates_for_event) ? $templates_for_event : array();
530 530
 
531 531
         // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
532 532
         foreach ($global_templates as $mtpgID => $mtpg) {
533 533
             if ($mtpg instanceof EE_Message_Template_Group) {
534 534
                 // verify this message type is supposed to show on this page
535 535
                 $mtp_obj = $mtpg->message_type_obj();
536
-                if (! $mtp_obj instanceof EE_message_type) {
536
+                if ( ! $mtp_obj instanceof EE_message_type) {
537 537
                     continue;
538 538
                 }
539 539
                 $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
540
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
540
+                if ( ! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
541 541
                     continue;
542 542
                 }
543 543
                 $select_values = array();
544
-                $select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
544
+                $select_values[$mtpgID] = esc_html__('Global', 'event_espresso');
545 545
                 $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
546 546
                 // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
547
-                if (! $mtpg->get('MTP_is_override')) {
547
+                if ( ! $mtpg->get('MTP_is_override')) {
548 548
                     // any custom templates for this message type?
549 549
                     $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
550 550
                     foreach ($custom_templates as $cmtpgID => $cmtpg) {
551
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
551
+                        $select_values[$cmtpgID] = $cmtpg->name();
552 552
                         $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
553 553
                     }
554 554
                 }
@@ -578,10 +578,10 @@  discard block
 block discarded – undo
578 578
                 $st_args['mt_slug'] = $mt_slug;
579 579
                 $st_args['messenger_slug'] = $this->name;
580 580
                 $st_args['selector'] = EEH_Form_Fields::select_input(
581
-                    'event_message_templates_relation[' . $mtpgID . ']',
581
+                    'event_message_templates_relation['.$mtpgID.']',
582 582
                     $select_values,
583 583
                     $default_value,
584
-                    'data-messenger="' . $this->name . '" data-messagetype="' . $mt_slug . '"',
584
+                    'data-messenger="'.$this->name.'" data-messagetype="'.$mt_slug.'"',
585 585
                     'message-template-selector'
586 586
                 );
587 587
                 $new_template_name = sprintf(
@@ -592,15 +592,15 @@  discard block
 block discarded – undo
592 592
                 $st_args['create_button'] = $mtpg->get('MTP_is_override')
593 593
                     ? ''
594 594
                     : '
595
-                    <a data-messenger="' . $this->name . '"
596
-                       data-messagetype="' . $mt_slug . '"
597
-                       data-new_template_name="' . $new_template_name . '"
598
-                       data-grpid="' . $default_value . '"
595
+                    <a data-messenger="' . $this->name.'"
596
+                       data-messagetype="' . $mt_slug.'"
597
+                       data-new_template_name="' . $new_template_name.'"
598
+                       data-grpid="' . $default_value.'"
599 599
                        target="_blank"
600
-                       href="' . $create_url . '"
600
+                       href="' . $create_url.'"
601 601
                        class="button button--secondary create-mtpg-button"
602 602
                     >
603
-                        ' . esc_html__('Create New Custom', 'event_espresso') . '
603
+                        ' . esc_html__('Create New Custom', 'event_espresso').'
604 604
                     </a>';
605 605
                 $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can(
606 606
                     'ee_edit_messages',
@@ -608,19 +608,19 @@  discard block
 block discarded – undo
608 608
                 )
609 609
                     ? $st_args['create_button']
610 610
                     : '';
611
-                $st_args['edit_button']   = EE_Registry::instance()->CAP->current_user_can(
611
+                $st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can(
612 612
                     'ee_edit_message',
613 613
                     'espresso_messages_edit_message_template',
614 614
                     $mtpgID
615 615
                 )
616 616
                     ? '
617
-                    <a data-messagetype="' . $mt_slug . '"
618
-                       data-grpid="' . $default_value . '"
617
+                    <a data-messagetype="' . $mt_slug.'"
618
+                       data-grpid="' . $default_value.'"
619 619
                        target="_blank"
620
-                       href="' . $edit_url . '"
620
+                       href="' . $edit_url.'"
621 621
                        class="button button--secondary edit-mtpg-button"
622 622
                     >
623
-                        ' . esc_html__('Edit', 'event_espresso') . '
623
+                        ' . esc_html__('Edit', 'event_espresso').'
624 624
                     </a>'
625 625
                     : '';
626 626
                 $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
      */
650 650
     public function get_template_fields()
651 651
     {
652
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
652
+        $template_fields = apply_filters('FHEE__'.get_class($this).'__get_template_fields', $this->_template_fields, $this);
653 653
         $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
654 654
         return $template_fields;
655 655
     }
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
     protected function _set_template_value($item, $value)
667 667
     {
668 668
         if (array_key_exists($item, $this->_template_fields)) {
669
-            $prop = '_' . $item;
669
+            $prop = '_'.$item;
670 670
             $this->{$prop} = $value;
671 671
         }
672 672
     }
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
                 $message,
728 728
                 $message_type
729 729
             );
730
-            if (! empty($settings)) {
730
+            if ( ! empty($settings)) {
731 731
                 foreach ($settings as $field => $value) {
732 732
                     $this->_set_template_value($field, $value);
733 733
                 }
@@ -735,12 +735,12 @@  discard block
 block discarded – undo
735 735
         }
736 736
 
737 737
         // enqueue preview js so that any links/buttons on the page are disabled.
738
-        if (! $send) {
738
+        if ( ! $send) {
739 739
             // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
740 740
             // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
741
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
742
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
743
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
741
+            add_action('admin_enqueue_scripts', array($this, 'add_preview_script'), 10);
742
+            add_action('wp_enqueue_scripts', array($this, 'add_preview_script'), 10);
743
+            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array($this, 'add_preview_script'), 10);
744 744
         }
745 745
 
746 746
         return $send ? $this->_send_message() : $this->_preview();
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
         EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
763 763
             __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
764 764
         );
765
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
765
+        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL.'messages/messenger/assets/js/ee-messages-preview.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
766 766
         wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
767 767
         wp_enqueue_script('ee-messages-preview-js');
768 768
     }
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
         $variation = $message->get_template_pack_variation();
782 782
 
783 783
         // verify we have the required template pack value on the $message object.
784
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
784
+        if ( ! $template_pack instanceof EE_Messages_Template_Pack) {
785 785
             throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
786 786
         }
787 787
 
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
 
794 794
         foreach ($template_fields as $template => $value) {
795 795
             if ($template !== 'extra') {
796
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
796
+                $column_value = $message->get_field_or_extra_meta('MSG_'.$template);
797 797
                 $message_template_value = $column_value ? $column_value : null;
798 798
                 $this->_set_template_value($template, $message_template_value);
799 799
             }
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
         $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
818 818
 
819 819
         // check file exists and is readable
820
-        if (!is_readable($wrapper_template)) {
820
+        if ( ! is_readable($wrapper_template)) {
821 821
             throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
822 822
         }
823 823
 
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
         /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
866 866
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
867 867
         $settings = $Message_Resource_Manager->get_active_messengers_option();
868
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
868
+        return isset($settings[$this->name]['test_settings']) ? $settings[$this->name]['test_settings'] : array();
869 869
     }
870 870
 
871 871
 
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
         /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
883 883
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
884 884
         $existing = $Message_Resource_Manager->get_active_messengers_option();
885
-        $existing[ $this->name ]['test_settings'] = $settings;
885
+        $existing[$this->name]['test_settings'] = $settings;
886 886
         return $Message_Resource_Manager->update_active_messengers_option($existing);
887 887
     }
888 888
 
@@ -899,23 +899,23 @@  discard block
 block discarded – undo
899 899
     public function get_field_label($field)
900 900
     {
901 901
         // first let's see if the field requests is in the top level array.
902
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
903
-            return $this->_template[ $field ]['label'];
902
+        if (isset($this->_template_fields[$field]) && ! empty($this->_template_fields[$field]['label'])) {
903
+            return $this->_template[$field]['label'];
904 904
         }
905 905
 
906 906
         // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
907
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
908
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
907
+        if (isset($this->_template_fields['extra']) && ! empty($this->_template_fields['extra'][$field]) && ! empty($this->_template_fields['extra'][$field]['main']['label'])) {
908
+            return $this->_template_fields['extra'][$field]['main']['label'];
909 909
         }
910 910
 
911 911
         // now it's possible this field may just be existing in any of the extra array items.
912
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
912
+        if ( ! empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
913 913
             foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
914
-                if (!is_array($subfields)) {
914
+                if ( ! is_array($subfields)) {
915 915
                     continue;
916 916
                 }
917
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
918
-                    return $subfields[ $field ]['label'];
917
+                if (isset($subfields[$field]) && ! empty($subfields[$field]['label'])) {
918
+                    return $subfields[$field]['label'];
919 919
                 }
920 920
             }
921 921
         }
Please login to merge, or discard this patch.
core/helpers/EEH_Maps.helper.php 2 patches
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -11,68 +11,68 @@  discard block
 block discarded – undo
11 11
  */
12 12
 class EEH_Maps
13 13
 {
14
-    // array of map settings
15
-    public static $gmap_vars = [];
16
-
17
-
18
-    /**
19
-     * google_map - creates a Google Map Link
20
-     *
21
-     * @param array $ee_gmaps_opts array of attributes required for the map link generation
22
-     * @return string (link to map!)
23
-     */
24
-    public static function google_map(array $ee_gmaps_opts): string
25
-    {
26
-        $ee_map_width = ! empty($ee_gmaps_opts['ee_map_width'])
27
-            ? absint($ee_gmaps_opts['ee_map_width'])
28
-            : 300;
29
-
30
-        $ee_map_height = ! empty($ee_gmaps_opts['ee_map_height'])
31
-            ? absint($ee_gmaps_opts['ee_map_height'])
32
-            : 185;
33
-
34
-        $ee_map_zoom = ! empty($ee_gmaps_opts['ee_map_zoom'])
35
-            ? absint($ee_gmaps_opts['ee_map_zoom'])
36
-            : 12;
37
-
38
-        $ee_map_nav_display = ! empty($ee_gmaps_opts['ee_map_nav_display']) ? 'true' : 'false';
39
-
40
-        $ee_map_nav_size = ! empty($ee_gmaps_opts['ee_map_nav_size'])
41
-            ? sanitize_text_field($ee_gmaps_opts['ee_map_nav_size'])
42
-            : 'default';
43
-
44
-        $ee_map_type_control = ! empty($ee_gmaps_opts['ee_map_type_control'])
45
-            ? sanitize_text_field($ee_gmaps_opts['ee_map_type_control'])
46
-            : 'default';
47
-
48
-        $static_url = ! empty($ee_gmaps_opts['ee_static_url'])
49
-            ? esc_url_raw($ee_gmaps_opts['ee_static_url'])
50
-            : false;
51
-
52
-        if (! empty($ee_gmaps_opts['ee_map_align'])) {
53
-            switch ($ee_gmaps_opts['ee_map_align']) {
54
-                case "left":
55
-                    $map_align = 'ee-gmap-align-left left';
56
-                    break;
57
-                case "right":
58
-                    $map_align = 'ee-gmap-align-right right';
59
-                    break;
60
-                case "center":
61
-                    $map_align = 'ee-gmap-align-center center';
62
-                    break;
63
-                case "none":
64
-                default:
65
-                    $map_align = 'ee-gmap-align-none';
66
-            }
67
-        } else {
68
-            $map_align = 'ee-gmap-align-none';
69
-        }
70
-
71
-
72
-        // Determine whether user has set a hardcoded url to use and
73
-        // if so display a Google static iframe map else run V3 api
74
-        if ($static_url) {
75
-            $html = '
14
+	// array of map settings
15
+	public static $gmap_vars = [];
16
+
17
+
18
+	/**
19
+	 * google_map - creates a Google Map Link
20
+	 *
21
+	 * @param array $ee_gmaps_opts array of attributes required for the map link generation
22
+	 * @return string (link to map!)
23
+	 */
24
+	public static function google_map(array $ee_gmaps_opts): string
25
+	{
26
+		$ee_map_width = ! empty($ee_gmaps_opts['ee_map_width'])
27
+			? absint($ee_gmaps_opts['ee_map_width'])
28
+			: 300;
29
+
30
+		$ee_map_height = ! empty($ee_gmaps_opts['ee_map_height'])
31
+			? absint($ee_gmaps_opts['ee_map_height'])
32
+			: 185;
33
+
34
+		$ee_map_zoom = ! empty($ee_gmaps_opts['ee_map_zoom'])
35
+			? absint($ee_gmaps_opts['ee_map_zoom'])
36
+			: 12;
37
+
38
+		$ee_map_nav_display = ! empty($ee_gmaps_opts['ee_map_nav_display']) ? 'true' : 'false';
39
+
40
+		$ee_map_nav_size = ! empty($ee_gmaps_opts['ee_map_nav_size'])
41
+			? sanitize_text_field($ee_gmaps_opts['ee_map_nav_size'])
42
+			: 'default';
43
+
44
+		$ee_map_type_control = ! empty($ee_gmaps_opts['ee_map_type_control'])
45
+			? sanitize_text_field($ee_gmaps_opts['ee_map_type_control'])
46
+			: 'default';
47
+
48
+		$static_url = ! empty($ee_gmaps_opts['ee_static_url'])
49
+			? esc_url_raw($ee_gmaps_opts['ee_static_url'])
50
+			: false;
51
+
52
+		if (! empty($ee_gmaps_opts['ee_map_align'])) {
53
+			switch ($ee_gmaps_opts['ee_map_align']) {
54
+				case "left":
55
+					$map_align = 'ee-gmap-align-left left';
56
+					break;
57
+				case "right":
58
+					$map_align = 'ee-gmap-align-right right';
59
+					break;
60
+				case "center":
61
+					$map_align = 'ee-gmap-align-center center';
62
+					break;
63
+				case "none":
64
+				default:
65
+					$map_align = 'ee-gmap-align-none';
66
+			}
67
+		} else {
68
+			$map_align = 'ee-gmap-align-none';
69
+		}
70
+
71
+
72
+		// Determine whether user has set a hardcoded url to use and
73
+		// if so display a Google static iframe map else run V3 api
74
+		if ($static_url) {
75
+			$html = '
76 76
             <div class="ee-gmap-iframewrap ee-gmap-wrapper ' . $map_align . '">
77 77
                 <iframe src="' . $static_url . '&output=embed"
78 78
                         style="width: ' . $ee_map_width . 'px; height: ' . $ee_map_height . 'px;"
@@ -82,18 +82,18 @@  discard block
 block discarded – undo
82 82
                 </iframe>
83 83
                 <a href="' . $static_url . '">' . esc_html__('View Large map', 'event_espresso') . '</a>
84 84
             </div>';
85
-        } else {
86
-            EEH_Maps::$gmap_vars[ $ee_gmaps_opts['map_ID'] ] = [
87
-                'map_ID'              => $ee_gmaps_opts['map_ID'],
88
-                'ee_map_zoom'         => $ee_map_zoom,
89
-                'ee_map_nav_display'  => $ee_map_nav_display,
90
-                'ee_map_nav_size'     => $ee_map_nav_size,
91
-                'ee_map_type_control' => $ee_map_type_control,
92
-                'location'            => $ee_gmaps_opts['location'],
93
-            ];
94
-
95
-            $style = 'width: ' . $ee_map_width . 'px; height: ' . $ee_map_height . 'px;';
96
-            $html  = '
85
+		} else {
86
+			EEH_Maps::$gmap_vars[ $ee_gmaps_opts['map_ID'] ] = [
87
+				'map_ID'              => $ee_gmaps_opts['map_ID'],
88
+				'ee_map_zoom'         => $ee_map_zoom,
89
+				'ee_map_nav_display'  => $ee_map_nav_display,
90
+				'ee_map_nav_size'     => $ee_map_nav_size,
91
+				'ee_map_type_control' => $ee_map_type_control,
92
+				'location'            => $ee_gmaps_opts['location'],
93
+			];
94
+
95
+			$style = 'width: ' . $ee_map_width . 'px; height: ' . $ee_map_height . 'px;';
96
+			$html  = '
97 97
             <div class="ee-gmap-wrapper ' . esc_attr($map_align) . '">
98 98
                 <div class="ee-gmap" 
99 99
                      id="map_canvas_' . esc_attr($ee_gmaps_opts['map_ID']) . '"
@@ -101,111 +101,111 @@  discard block
 block discarded – undo
101 101
                  ></div>
102 102
             </div>';
103 103
 
104
-            wp_enqueue_script('gmap_api');
105
-            wp_enqueue_script('ee_gmap');
106
-            add_action('wp_footer', ['EEH_Maps', 'footer_enqueue_script']);
107
-        }
108
-        return $html; // end auto map or static url map check
109
-    }
110
-
111
-
112
-    /**
113
-     * enqueue_script
114
-     *
115
-     * @return void
116
-     */
117
-    public static function footer_enqueue_script(): void
118
-    {
119
-        wp_localize_script('ee_gmap', 'ee_gmap_vars', EEH_Maps::$gmap_vars);
120
-    }
121
-
122
-
123
-    /**
124
-     * registers scripts for maps
125
-     *
126
-     * @return void
127
-     */
128
-    public static function espresso_google_map_js(): void
129
-    {
130
-        $api_url = sprintf(
131
-            "https://maps.googleapis.com/maps/api/js?callback=ee_gmap_callback&key=%s",
132
-            apply_filters(
133
-                'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
134
-                EE_Registry::instance()->CFG->map_settings->google_map_api_key
135
-            )
136
-        );
137
-        wp_register_script(
138
-            'ee_gmap',
139
-            plugin_dir_url(__FILE__) . 'assets/ee_gmap.js',
140
-            ['jquery'],
141
-            '1.1',
142
-            true
143
-        );
144
-        wp_register_script(
145
-            'gmap_api',
146
-            esc_url_raw($api_url),
147
-            ['ee_gmap'],
148
-            null,
149
-            true
150
-        );
151
-    }
152
-
153
-
154
-    /**
155
-     * creates a Google Map Link
156
-     *
157
-     * @param array $atts array of attributes required for the map link generation
158
-     * @return string (link to map!)
159
-     */
160
-    public static function google_map_link(array $atts): string
161
-    {
162
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
163
-        extract($atts);
164
-        /** @var string $address */
165
-        /** @var string $city */
166
-        /** @var string $state */
167
-        /** @var string $zip */
168
-        /** @var string $country */
169
-        $address         = "$address";
170
-        $city            = "$city";
171
-        $state           = "$state";
172
-        $zip             = "$zip";
173
-        $country         = "$country";
174
-        $text            = isset($text) ? "$text" : "";
175
-        $type            = isset($type) ? "$type" : "";
176
-        $map_w           = isset($map_w) ? "$map_w" : 400;
177
-        $map_h           = isset($map_h) ? "$map_h" : 400;
178
-        $id              = $id ?? 'not_set';
179
-        $map_image_class = $map_image_class ?? 'ee_google_map_view';
180
-
181
-        $address_string = ($address != '' ? $address : '')
182
-                          . ($city != '' ? ',' . $city : '')
183
-                          . ($state != '' ? ',' . $state : '')
184
-                          . ($zip != '' ? ',' . $zip : '')
185
-                          . ($country != '' ? ',' . $country : '');
186
-
187
-        $google_map = htmlentities2('https://maps.google.com/maps?q=' . urlencode($address_string));
188
-
189
-        switch ($type) {
190
-            case 'text':
191
-            default:
192
-                $text = $text == '' ? esc_html__('Map and Directions', 'event_espresso') : $text;
193
-                break;
194
-
195
-            case 'url_only':
196
-            case 'url':
197
-                $text = $google_map;
198
-                break;
199
-
200
-            case 'map':
201
-                $scheme = is_ssl() ? 'https://' : 'http://';
202
-
203
-                $api_key = apply_filters(
204
-                    'FHEE__EEH_Maps__espresso_google_maps_link__api_key',
205
-                    EE_Registry::instance()->CFG->map_settings->google_map_api_key
206
-                );
207
-
208
-                return '
104
+			wp_enqueue_script('gmap_api');
105
+			wp_enqueue_script('ee_gmap');
106
+			add_action('wp_footer', ['EEH_Maps', 'footer_enqueue_script']);
107
+		}
108
+		return $html; // end auto map or static url map check
109
+	}
110
+
111
+
112
+	/**
113
+	 * enqueue_script
114
+	 *
115
+	 * @return void
116
+	 */
117
+	public static function footer_enqueue_script(): void
118
+	{
119
+		wp_localize_script('ee_gmap', 'ee_gmap_vars', EEH_Maps::$gmap_vars);
120
+	}
121
+
122
+
123
+	/**
124
+	 * registers scripts for maps
125
+	 *
126
+	 * @return void
127
+	 */
128
+	public static function espresso_google_map_js(): void
129
+	{
130
+		$api_url = sprintf(
131
+			"https://maps.googleapis.com/maps/api/js?callback=ee_gmap_callback&key=%s",
132
+			apply_filters(
133
+				'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
134
+				EE_Registry::instance()->CFG->map_settings->google_map_api_key
135
+			)
136
+		);
137
+		wp_register_script(
138
+			'ee_gmap',
139
+			plugin_dir_url(__FILE__) . 'assets/ee_gmap.js',
140
+			['jquery'],
141
+			'1.1',
142
+			true
143
+		);
144
+		wp_register_script(
145
+			'gmap_api',
146
+			esc_url_raw($api_url),
147
+			['ee_gmap'],
148
+			null,
149
+			true
150
+		);
151
+	}
152
+
153
+
154
+	/**
155
+	 * creates a Google Map Link
156
+	 *
157
+	 * @param array $atts array of attributes required for the map link generation
158
+	 * @return string (link to map!)
159
+	 */
160
+	public static function google_map_link(array $atts): string
161
+	{
162
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
163
+		extract($atts);
164
+		/** @var string $address */
165
+		/** @var string $city */
166
+		/** @var string $state */
167
+		/** @var string $zip */
168
+		/** @var string $country */
169
+		$address         = "$address";
170
+		$city            = "$city";
171
+		$state           = "$state";
172
+		$zip             = "$zip";
173
+		$country         = "$country";
174
+		$text            = isset($text) ? "$text" : "";
175
+		$type            = isset($type) ? "$type" : "";
176
+		$map_w           = isset($map_w) ? "$map_w" : 400;
177
+		$map_h           = isset($map_h) ? "$map_h" : 400;
178
+		$id              = $id ?? 'not_set';
179
+		$map_image_class = $map_image_class ?? 'ee_google_map_view';
180
+
181
+		$address_string = ($address != '' ? $address : '')
182
+						  . ($city != '' ? ',' . $city : '')
183
+						  . ($state != '' ? ',' . $state : '')
184
+						  . ($zip != '' ? ',' . $zip : '')
185
+						  . ($country != '' ? ',' . $country : '');
186
+
187
+		$google_map = htmlentities2('https://maps.google.com/maps?q=' . urlencode($address_string));
188
+
189
+		switch ($type) {
190
+			case 'text':
191
+			default:
192
+				$text = $text == '' ? esc_html__('Map and Directions', 'event_espresso') : $text;
193
+				break;
194
+
195
+			case 'url_only':
196
+			case 'url':
197
+				$text = $google_map;
198
+				break;
199
+
200
+			case 'map':
201
+				$scheme = is_ssl() ? 'https://' : 'http://';
202
+
203
+				$api_key = apply_filters(
204
+					'FHEE__EEH_Maps__espresso_google_maps_link__api_key',
205
+					EE_Registry::instance()->CFG->map_settings->google_map_api_key
206
+				);
207
+
208
+				return '
209 209
                 <a class="a_map_image_link" 
210 210
                    href="' . esc_url_raw($google_map) . '" 
211 211
                    target="_blank" 
@@ -215,23 +215,23 @@  discard block
 block discarded – undo
215 215
                          class="map_image_link" 
216 216
                          id="venue_map_' . $id . '" ' . $map_image_class . ' 
217 217
                          src="'
218
-                       . htmlentities2(
219
-                           $scheme
220
-                           . 'maps.googleapis.com/maps/api/staticmap?center='
221
-                           . urlencode($address_string)
222
-                           . '&amp;zoom=14&amp;size='
223
-                           . $map_w . 'x' . $map_h
224
-                           . '&amp;markers=color:green|label:|'
225
-                           . urlencode($address_string)
226
-                           . '&amp;sensor=false&amp;key='
227
-                           . $api_key
228
-                       ) . '"
218
+					   . htmlentities2(
219
+						   $scheme
220
+						   . 'maps.googleapis.com/maps/api/staticmap?center='
221
+						   . urlencode($address_string)
222
+						   . '&amp;zoom=14&amp;size='
223
+						   . $map_w . 'x' . $map_h
224
+						   . '&amp;markers=color:green|label:|'
225
+						   . urlencode($address_string)
226
+						   . '&amp;sensor=false&amp;key='
227
+						   . $api_key
228
+					   ) . '"
229 229
                      />
230 230
                  </a>';
231
-        }
231
+		}
232 232
 
233
-        return $type === 'url_only'
234
-            ? $text
235
-            : '<a href="' . esc_url_raw($google_map) . '" target="_blank" rel="noopener noreferrer">' . $text . '</a>';
236
-    }
233
+		return $type === 'url_only'
234
+			? $text
235
+			: '<a href="' . esc_url_raw($google_map) . '" target="_blank" rel="noopener noreferrer">' . $text . '</a>';
236
+	}
237 237
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
             ? esc_url_raw($ee_gmaps_opts['ee_static_url'])
50 50
             : false;
51 51
 
52
-        if (! empty($ee_gmaps_opts['ee_map_align'])) {
52
+        if ( ! empty($ee_gmaps_opts['ee_map_align'])) {
53 53
             switch ($ee_gmaps_opts['ee_map_align']) {
54 54
                 case "left":
55 55
                     $map_align = 'ee-gmap-align-left left';
@@ -73,17 +73,17 @@  discard block
 block discarded – undo
73 73
         // if so display a Google static iframe map else run V3 api
74 74
         if ($static_url) {
75 75
             $html = '
76
-            <div class="ee-gmap-iframewrap ee-gmap-wrapper ' . $map_align . '">
77
-                <iframe src="' . $static_url . '&output=embed"
78
-                        style="width: ' . $ee_map_width . 'px; height: ' . $ee_map_height . 'px;"
76
+            <div class="ee-gmap-iframewrap ee-gmap-wrapper ' . $map_align.'">
77
+                <iframe src="' . $static_url.'&output=embed"
78
+                        style="width: ' . $ee_map_width.'px; height: '.$ee_map_height.'px;"
79 79
                         frameborder="0" 
80 80
                         scrolling="no"
81 81
                     >
82 82
                 </iframe>
83
-                <a href="' . $static_url . '">' . esc_html__('View Large map', 'event_espresso') . '</a>
83
+                <a href="' . $static_url.'">'.esc_html__('View Large map', 'event_espresso').'</a>
84 84
             </div>';
85 85
         } else {
86
-            EEH_Maps::$gmap_vars[ $ee_gmaps_opts['map_ID'] ] = [
86
+            EEH_Maps::$gmap_vars[$ee_gmaps_opts['map_ID']] = [
87 87
                 'map_ID'              => $ee_gmaps_opts['map_ID'],
88 88
                 'ee_map_zoom'         => $ee_map_zoom,
89 89
                 'ee_map_nav_display'  => $ee_map_nav_display,
@@ -92,12 +92,12 @@  discard block
 block discarded – undo
92 92
                 'location'            => $ee_gmaps_opts['location'],
93 93
             ];
94 94
 
95
-            $style = 'width: ' . $ee_map_width . 'px; height: ' . $ee_map_height . 'px;';
95
+            $style = 'width: '.$ee_map_width.'px; height: '.$ee_map_height.'px;';
96 96
             $html  = '
97
-            <div class="ee-gmap-wrapper ' . esc_attr($map_align) . '">
97
+            <div class="ee-gmap-wrapper ' . esc_attr($map_align).'">
98 98
                 <div class="ee-gmap" 
99
-                     id="map_canvas_' . esc_attr($ee_gmaps_opts['map_ID']) . '"
100
-                     style="' . esc_attr($style) . '"
99
+                     id="map_canvas_' . esc_attr($ee_gmaps_opts['map_ID']).'"
100
+                     style="' . esc_attr($style).'"
101 101
                  ></div>
102 102
             </div>';
103 103
 
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
         );
137 137
         wp_register_script(
138 138
             'ee_gmap',
139
-            plugin_dir_url(__FILE__) . 'assets/ee_gmap.js',
139
+            plugin_dir_url(__FILE__).'assets/ee_gmap.js',
140 140
             ['jquery'],
141 141
             '1.1',
142 142
             true
@@ -179,12 +179,12 @@  discard block
 block discarded – undo
179 179
         $map_image_class = $map_image_class ?? 'ee_google_map_view';
180 180
 
181 181
         $address_string = ($address != '' ? $address : '')
182
-                          . ($city != '' ? ',' . $city : '')
183
-                          . ($state != '' ? ',' . $state : '')
184
-                          . ($zip != '' ? ',' . $zip : '')
185
-                          . ($country != '' ? ',' . $country : '');
182
+                          . ($city != '' ? ','.$city : '')
183
+                          . ($state != '' ? ','.$state : '')
184
+                          . ($zip != '' ? ','.$zip : '')
185
+                          . ($country != '' ? ','.$country : '');
186 186
 
187
-        $google_map = htmlentities2('https://maps.google.com/maps?q=' . urlencode($address_string));
187
+        $google_map = htmlentities2('https://maps.google.com/maps?q='.urlencode($address_string));
188 188
 
189 189
         switch ($type) {
190 190
             case 'text':
@@ -207,31 +207,31 @@  discard block
 block discarded – undo
207 207
 
208 208
                 return '
209 209
                 <a class="a_map_image_link" 
210
-                   href="' . esc_url_raw($google_map) . '" 
210
+                   href="' . esc_url_raw($google_map).'" 
211 211
                    target="_blank" 
212 212
                    rel="noopener noreferrer"
213 213
                 >
214
-                    <img alt="' . esc_html__('Map and Directions', 'event_espresso') . '"
214
+                    <img alt="' . esc_html__('Map and Directions', 'event_espresso').'"
215 215
                          class="map_image_link" 
216
-                         id="venue_map_' . $id . '" ' . $map_image_class . ' 
216
+                         id="venue_map_' . $id.'" '.$map_image_class.' 
217 217
                          src="'
218 218
                        . htmlentities2(
219 219
                            $scheme
220 220
                            . 'maps.googleapis.com/maps/api/staticmap?center='
221 221
                            . urlencode($address_string)
222 222
                            . '&amp;zoom=14&amp;size='
223
-                           . $map_w . 'x' . $map_h
223
+                           . $map_w.'x'.$map_h
224 224
                            . '&amp;markers=color:green|label:|'
225 225
                            . urlencode($address_string)
226 226
                            . '&amp;sensor=false&amp;key='
227 227
                            . $api_key
228
-                       ) . '"
228
+                       ).'"
229 229
                      />
230 230
                  </a>';
231 231
         }
232 232
 
233 233
         return $type === 'url_only'
234 234
             ? $text
235
-            : '<a href="' . esc_url_raw($google_map) . '" target="_blank" rel="noopener noreferrer">' . $text . '</a>';
235
+            : '<a href="'.esc_url_raw($google_map).'" target="_blank" rel="noopener noreferrer">'.$text.'</a>';
236 236
     }
237 237
 }
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 1 patch
Indentation   +1252 added lines, -1252 removed lines patch added patch discarded remove patch
@@ -13,1259 +13,1259 @@
 block discarded – undo
13 13
  */
14 14
 class EEH_MSG_Template
15 15
 {
16
-    /**
17
-     * Holds a collection of EE_Message_Template_Pack objects.
18
-     * @type EE_Messages_Template_Pack_Collection
19
-     */
20
-    protected static $_template_pack_collection;
21
-
22
-
23
-    /**
24
-     * @throws EE_Error
25
-     */
26
-    private static function _set_autoloader()
27
-    {
28
-        EED_Messages::set_autoloaders();
29
-    }
30
-
31
-
32
-    /**
33
-     * generate_new_templates
34
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
35
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
36
-     * for the event.
37
-     *
38
-     * @access protected
39
-     * @param string $messenger     the messenger we are generating templates for
40
-     * @param array  $message_types array of message types that the templates are generated for.
41
-     * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
42
-     *                              to use as the base for the new generated template.
43
-     * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
44
-     *                              for event specific template generation.
45
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
46
-     *                for templates that are generated.  If this is an empty array then it means no templates were
47
-     *                generated which usually means there was an error.  Anything in the array with an empty value for
48
-     *                `MTP_context` means that it was not a new generated template but just reactivated (which only
49
-     *                happens for global templates that already exist in the database.
50
-     * @throws EE_Error
51
-     * @throws ReflectionException
52
-     */
53
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
54
-    {
55
-        // make sure message_type is an array.
56
-        $message_types = (array) $message_types;
57
-        $templates = array();
58
-
59
-        if (empty($messenger)) {
60
-            throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
61
-        }
62
-
63
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
64
-        if (empty($message_types)) {
65
-            throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
66
-        }
67
-
68
-        EEH_MSG_Template::_set_autoloader();
69
-        foreach ($message_types as $message_type) {
70
-            // if this is global template generation.
71
-            if ($global) {
72
-                // let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
-                if (empty($GRP_ID)) {
74
-                    $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
-                        array(
76
-                            array(
77
-                                'MTP_messenger'    => $messenger,
78
-                                'MTP_message_type' => $message_type,
79
-                                'MTP_is_global'    => true,
80
-                            ),
81
-                        )
82
-                    );
83
-                    $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
-                }
85
-                // First let's determine if we already HAVE global templates for this messenger and message_type combination.
86
-                //  If we do then NO generation!!
87
-                if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
88
-                    $templates[] = array(
89
-                        'GRP_ID' => $GRP_ID,
90
-                        'MTP_context' => '',
91
-                    );
92
-                    // we already have generated templates for this so let's go to the next message type.
93
-                    continue;
94
-                }
95
-            }
96
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
-
98
-            if (! $new_message_template_group) {
99
-                continue;
100
-            }
101
-            $templates[] = $new_message_template_group;
102
-        }
103
-
104
-        return $templates;
105
-    }
106
-
107
-
108
-    /**
109
-     * The purpose of this method is to determine if there are already generated templates in the database for the
110
-     * given variables.
111
-     *
112
-     * @param string $messenger    messenger
113
-     * @param string $message_type message type
114
-     * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
-     *                             template check)
116
-     * @return bool                true = generated, false = hasn't been generated.
117
-     * @throws EE_Error
118
-     */
119
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
-    {
121
-        EEH_MSG_Template::_set_autoloader();
122
-        // what method we use depends on whether we have an GRP_ID or not
123
-        $count = empty($GRP_ID)
124
-            ? EEM_Message_Template::instance()->count(
125
-                array(
126
-                    array(
127
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
128
-                        'Message_Template_Group.MTP_message_type' => $message_type,
129
-                        'Message_Template_Group.MTP_is_global'    => true
130
-                    )
131
-                )
132
-            )
133
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
-
135
-        return $count > 0;
136
-    }
137
-
138
-
139
-    /**
140
-     * Updates all message templates matching the incoming messengers and message types to active status.
141
-     *
142
-     * @static
143
-     * @param array $messenger_names    Messenger slug
144
-     * @param array $message_type_names Message type slug
145
-     * @return  int                         count of updated records.
146
-     * @throws EE_Error
147
-     */
148
-    public static function update_to_active($messenger_names, $message_type_names)
149
-    {
150
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
-        return EEM_Message_Template_Group::instance()->update(
153
-            array( 'MTP_is_active' => 1 ),
154
-            array(
155
-                array(
156
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
157
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
158
-                )
159
-            )
160
-        );
161
-    }
162
-
163
-
164
-    /**
165
-     * Updates all message template groups matching the incoming arguments to inactive status.
166
-     *
167
-     * @static
168
-     * @param array $messenger_names    The messenger slugs.
169
-     *                                  If empty then all templates matching the message types are marked inactive.
170
-     *                                  Otherwise only templates matching the messengers and message types.
171
-     * @param array $message_type_names The message type slugs.
172
-     *                                  If empty then all templates matching the messengers are marked inactive.
173
-     *                                  Otherwise only templates matching the messengers and message types.
174
-     *
175
-     * @return int  count of updated records.
176
-     * @throws EE_Error
177
-     */
178
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
-    {
180
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
-            $messenger_names,
182
-            $message_type_names
183
-        );
184
-    }
185
-
186
-
187
-    /**
188
-     * The purpose of this function is to return all installed message objects
189
-     * (messengers and message type regardless of whether they are ACTIVE or not)
190
-     *
191
-     * @param string $type
192
-     * @return array array consisting of installed messenger objects and installed message type objects.
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     * @deprecated 4.9.0
196
-     * @static
197
-     */
198
-    public static function get_installed_message_objects($type = 'all')
199
-    {
200
-        self::_set_autoloader();
201
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
-        return array(
203
-            'messenger' => $message_resource_manager->installed_messengers(),
204
-            'message_type' => $message_resource_manager->installed_message_types()
205
-        );
206
-    }
207
-
208
-
209
-    /**
210
-     * This will return an array of shortcodes => labels from the
211
-     * messenger and message_type objects associated with this
212
-     * template.
213
-     *
214
-     * @param string $message_type
215
-     * @param string $messenger
216
-     * @param array  $fields                        What fields we're returning valid shortcodes for.
217
-     *                                              If empty then we assume all fields are to be returned. Optional.
218
-     * @param string $context                       What context we're going to return shortcodes for. Optional.
219
-     * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
-     *                                              but instead an array of the unique shortcodes for all the given (
221
-     *                                              or all) fields. Optional.
222
-     * @return array                                an array of shortcodes in the format
223
-     *                                              array( '[shortcode] => 'label')
224
-     *                                              OR
225
-     *                                              FALSE if no shortcodes found.
226
-     * @throws ReflectionException
227
-     * @throws EE_Error*@since 4.3.0
228
-     *
229
-     */
230
-    public static function get_shortcodes(
231
-        $message_type,
232
-        $messenger,
233
-        $fields = array(),
234
-        $context = 'admin',
235
-        $merged = false
236
-    ) {
237
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
240
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
-        // convert slug to object
242
-        $messenger = $message_resource_manager->get_messenger($messenger);
243
-
244
-        // if messenger isn't a EE_messenger resource then bail.
245
-        if (! $messenger instanceof EE_messenger) {
246
-            return array();
247
-        }
248
-
249
-        // validate class for getting our list of shortcodes
250
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
-        if (! class_exists($classname)) {
252
-            $msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
-            $msg[] = sprintf(
254
-                esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
-                $classname
256
-            );
257
-            throw new EE_Error(implode('||', $msg));
258
-        }
259
-
260
-        /** @type EE_Messages_Validator $_VLD */
261
-        $_VLD = new $classname(array(), $context);
262
-        $valid_shortcodes = $_VLD->get_validators();
263
-
264
-        // let's make sure we're only getting the shortcode part of the validators
265
-        $shortcodes = array();
266
-        foreach ($valid_shortcodes as $field => $validators) {
267
-            $shortcodes[ $field ] = $validators['shortcodes'];
268
-        }
269
-        $valid_shortcodes = $shortcodes;
270
-
271
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
-        if (! empty($fields)) {
273
-            $specified_shortcodes = array();
274
-            foreach ($fields as $field) {
275
-                if (isset($valid_shortcodes[ $field ])) {
276
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
-                }
278
-            }
279
-            $valid_shortcodes = $specified_shortcodes;
280
-        }
281
-
282
-        // if not merged then let's replace the fields with the localized fields
283
-        if (! $merged) {
284
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
-            $field_settings = $messenger->get_template_fields();
286
-            $localized = array();
287
-            foreach ($valid_shortcodes as $field => $shortcodes) {
288
-                // get localized field label
289
-                if (isset($field_settings[ $field ])) {
290
-                    // possible that this is used as a main field.
291
-                    if (empty($field_settings[ $field ])) {
292
-                        if (isset($field_settings['extra'][ $field ])) {
293
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
294
-                        } else {
295
-                            $_field = $field;
296
-                        }
297
-                    } else {
298
-                        $_field = $field_settings[ $field ]['label'];
299
-                    }
300
-                } elseif (isset($field_settings['extra'])) {
301
-                    // loop through extra "main fields" and see if any of their children have our field
302
-                    foreach ($field_settings['extra'] as $fields) {
303
-                        if (isset($fields[ $field ])) {
304
-                            $_field = $fields[ $field ]['label'];
305
-                        } else {
306
-                            $_field = $field;
307
-                        }
308
-                    }
309
-                } else {
310
-                    $_field = $field;
311
-                }
312
-                if (isset($_field)) {
313
-                    $localized[ (string) $_field ] = $shortcodes;
314
-                }
315
-            }
316
-            $valid_shortcodes = $localized;
317
-        }
318
-
319
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
-        if ($merged) {
321
-            $merged_codes = array();
322
-            foreach ($valid_shortcodes as $shortcode) {
323
-                foreach ($shortcode as $code => $label) {
324
-                    if (isset($merged_codes[ $code ])) {
325
-                        continue;
326
-                    } else {
327
-                        $merged_codes[ $code ] = $label;
328
-                    }
329
-                }
330
-            }
331
-            $valid_shortcodes = $merged_codes;
332
-        }
333
-
334
-        return $valid_shortcodes;
335
-    }
336
-
337
-
338
-    /**
339
-     * Get Messenger object.
340
-     *
341
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
-     * @return EE_messenger
343
-     * @throws ReflectionException
344
-     * @throws EE_Error*@since 4.3.0
345
-     * @deprecated 4.9.0
346
-     */
347
-    public static function messenger_obj($messenger)
348
-    {
349
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
-        return $Message_Resource_Manager->get_messenger($messenger);
352
-    }
353
-
354
-
355
-    /**
356
-     * get Message type object
357
-     *
358
-     * @param string $message_type the slug for the message type object to retrieve
359
-     * @return EE_message_type
360
-     * @throws ReflectionException
361
-     * @throws EE_Error*@since 4.3.0
362
-     * @deprecated 4.9.0
363
-     */
364
-    public static function message_type_obj($message_type)
365
-    {
366
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
-        return $Message_Resource_Manager->get_message_type($message_type);
369
-    }
370
-
371
-
372
-    /**
373
-     * Given a message_type slug, will return whether that message type is active in the system or not.
374
-     *
375
-     * @since    4.3.0
376
-     * @param string $message_type message type to check for.
377
-     * @return boolean
378
-     * @throws EE_Error
379
-     * @throws ReflectionException
380
-     */
381
-    public static function is_mt_active($message_type)
382
-    {
383
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
-        return in_array($message_type, $active_mts);
387
-    }
388
-
389
-
390
-    /**
391
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
392
-     *
393
-     * @since    4.3.0
394
-     *
395
-     * @param string $messenger slug for messenger to check.
396
-     * @return boolean
397
-     * @throws EE_Error
398
-     * @throws ReflectionException
399
-     */
400
-    public static function is_messenger_active($messenger)
401
-    {
402
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
-        return $active_messenger instanceof EE_messenger;
406
-    }
407
-
408
-
409
-    /**
410
-     * Used to return active messengers array stored in the wp options table.
411
-     * If no value is present in the option then an empty array is returned.
412
-     *
413
-     * @deprecated 4.9
414
-     * @since      4.3.1
415
-     *
416
-     * @return array
417
-     * @throws EE_Error
418
-     * @throws ReflectionException
419
-     */
420
-    public static function get_active_messengers_in_db()
421
-    {
422
-        EE_Error::doing_it_wrong(
423
-            __METHOD__,
424
-            esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
-            '4.9.0'
426
-        );
427
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
-        return $Message_Resource_Manager->get_active_messengers_option();
430
-    }
431
-
432
-
433
-    /**
434
-     * Used to update the active messengers array stored in the wp options table.
435
-     *
436
-     * @since      4.3.1
437
-     * @deprecated 4.9.0
438
-     *
439
-     * @param array $data_to_save Incoming data to save.
440
-     *
441
-     * @return bool FALSE if not updated, TRUE if updated.
442
-     * @throws EE_Error
443
-     * @throws ReflectionException
444
-     */
445
-    public static function update_active_messengers_in_db($data_to_save)
446
-    {
447
-        EE_Error::doing_it_wrong(
448
-            __METHOD__,
449
-            esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
-            '4.9.0'
451
-        );
452
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
-    }
456
-
457
-
458
-    /**
459
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
-     * appropriate url trigger
461
-     *
462
-     * @param EE_message_type $message_type
463
-     * @param EE_Message $message
464
-     * @param EE_Registration | null $registration  The registration object must be included if this
465
-     *                                              is going to be a registration trigger url.
466
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
467
-     *
468
-     * @return string
469
-     * @throws EE_Error
470
-     */
471
-    public static function get_url_trigger(
472
-        EE_message_type $message_type,
473
-        EE_Message $message,
474
-        $registration = null,
475
-        $sending_messenger = ''
476
-    ) {
477
-        // first determine if the url can be to the EE_Message object.
478
-        if (! $message_type->always_generate()) {
479
-            return EEH_MSG_Template::generate_browser_trigger($message);
480
-        }
481
-
482
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
483
-        if (! $registration instanceof EE_Registration) {
484
-            throw new EE_Error(
485
-                esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
-            );
487
-        }
488
-
489
-        // validate given context
490
-        $contexts = $message_type->get_contexts();
491
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
-            throw new EE_Error(
493
-                sprintf(
494
-                    esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
-                    $message->context(),
496
-                    get_class($message_type)
497
-                )
498
-            );
499
-        }
500
-
501
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
-        if (! empty($sending_messenger)) {
503
-            $with_messengers = $message_type->with_messengers();
504
-            if (
505
-                ! isset($with_messengers[ $message->messenger() ])
506
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
-            ) {
508
-                throw new EE_Error(
509
-                    sprintf(
510
-                        esc_html__(
511
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
-                            'event_espresso'
513
-                        ),
514
-                        $sending_messenger,
515
-                        get_class($message_type)
516
-                    )
517
-                );
518
-            }
519
-        } else {
520
-            $sending_messenger = $message->messenger();
521
-        }
522
-        return EEH_MSG_Template::generate_url_trigger(
523
-            $sending_messenger,
524
-            $message->messenger(),
525
-            $message->context(),
526
-            $message->message_type(),
527
-            $registration,
528
-            $message->GRP_ID()
529
-        );
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
535
-     * @param EE_Message $message
536
-     * @return string.
537
-     */
538
-    public static function generate_browser_trigger(EE_Message $message)
539
-    {
540
-        $query_args = array(
541
-            'ee' => 'msg_browser_trigger',
542
-            'token' => $message->MSG_token()
543
-        );
544
-        return apply_filters(
545
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
-            add_query_arg($query_args, site_url()),
547
-            $message
548
-        );
549
-    }
550
-
551
-
552
-
553
-
554
-
555
-
556
-    /**
557
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
-     * @param EE_Message $message
559
-     * @return string
560
-     */
561
-    public static function generate_error_display_trigger(EE_Message $message)
562
-    {
563
-        return apply_filters(
564
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
-            add_query_arg(
566
-                array(
567
-                    'ee' => 'msg_browser_error_trigger',
568
-                    'token' => $message->MSG_token()
569
-                ),
570
-                site_url()
571
-            ),
572
-            $message
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
579
-     *
580
-     * @param string          $sending_messenger      The sending messenger slug.
581
-     * @param string          $generating_messenger   The generating messenger slug.
582
-     * @param string          $context                The context for the template.
583
-     * @param string          $message_type           The message type slug
584
-     * @param EE_Registration $registration
585
-     * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
-     * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
-     *                                                trigger.
588
-     * @return string          The generated url.
589
-     * @throws EE_Error
590
-     */
591
-    public static function generate_url_trigger(
592
-        $sending_messenger,
593
-        $generating_messenger,
594
-        $context,
595
-        $message_type,
596
-        EE_Registration $registration,
597
-        $message_template_group,
598
-        $data_id = 0
599
-    ) {
600
-        $query_args = array(
601
-            'ee' => 'msg_url_trigger',
602
-            'snd_msgr' => $sending_messenger,
603
-            'gen_msgr' => $generating_messenger,
604
-            'message_type' => $message_type,
605
-            'context' => $context,
606
-            'token' => $registration->reg_url_link(),
607
-            'GRP_ID' => $message_template_group,
608
-            'id' => $data_id
609
-            );
610
-        $url = add_query_arg($query_args, get_home_url());
611
-
612
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
-        return apply_filters(
614
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
615
-            $url,
616
-            $sending_messenger,
617
-            $generating_messenger,
618
-            $context,
619
-            $message_type,
620
-            $registration,
621
-            $message_template_group,
622
-            $data_id
623
-        );
624
-    }
625
-
626
-
627
-
628
-
629
-    /**
630
-     * Return the specific css for the action icon given.
631
-     *
632
-     * @param string $type  What action to return.
633
-     * @return string[]
634
-     * @since 4.9.0
635
-     */
636
-    public static function get_message_action_icon($type)
637
-    {
638
-        $action_icons = self::get_message_action_icons();
639
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
-    }
641
-
642
-
643
-    /**
644
-     * This is used for retrieving the css classes used for the icons representing message actions.
645
-     *
646
-     * @since 4.9.0
647
-     *
648
-     * @return array
649
-     */
650
-    public static function get_message_action_icons()
651
-    {
652
-        return apply_filters(
653
-            'FHEE__EEH_MSG_Template__message_action_icons',
654
-            array(
655
-                'view' => array(
656
-                    'label' => esc_html__('View Message', 'event_espresso'),
657
-                    'css_class' => 'dashicons dashicons-visibility',
658
-                ),
659
-                'error' => array(
660
-                    'label' => esc_html__('View Error Message', 'event_espresso'),
661
-                    'css_class' => 'dashicons dashicons-info',
662
-                ),
663
-                'see_notifications_for' => array(
664
-                    'label' => esc_html__('View Related Messages', 'event_espresso'),
665
-                    'css_class' => 'dashicons dashicons-megaphone',
666
-                ),
667
-                'generate_now' => array(
668
-                    'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
-                    'css_class' => 'dashicons dashicons-admin-tools',
670
-                ),
671
-                'send_now' => array(
672
-                    'label' => esc_html__('Send Immediately', 'event_espresso'),
673
-                    'css_class' => 'dashicons dashicons-controls-forward',
674
-                ),
675
-                'queue_for_resending' => array(
676
-                    'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
-                    'css_class' => 'dashicons dashicons-controls-repeat',
678
-                ),
679
-                'view_transaction' => array(
680
-                    'label' => esc_html__('View related Transaction', 'event_espresso'),
681
-                    'css_class' => 'dashicons dashicons-cart',
682
-                )
683
-            )
684
-        );
685
-    }
686
-
687
-
688
-    /**
689
-     * This returns the url for a given action related to EE_Message.
690
-     *
691
-     * @param string     $type         What type of action to return the url for.
692
-     * @param EE_Message $message      Required for generating the correct url for some types.
693
-     * @param array      $query_params Any additional query params to be included with the generated url.
694
-     *
695
-     * @return string
696
-     * @throws EE_Error
697
-     * @throws ReflectionException
698
-     * @since 4.9.0
699
-     *
700
-     */
701
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
-    {
703
-        $action_urls = self::get_message_action_urls($message, $query_params);
704
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
-    }
706
-
707
-
708
-    /**
709
-     * This returns all the current urls for EE_Message actions.
710
-     *
711
-     * @since 4.9.0
712
-     *
713
-     * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
-     * @param array      $query_params Any additional query_params to be included with the generated url.
715
-     *
716
-     * @return array
717
-     * @throws EE_Error
718
-     * @throws ReflectionException
719
-     */
720
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
-    {
722
-        EE_Registry::instance()->load_helper('URL');
723
-        // if $message is not an instance of EE_Message then let's just do a dummy.
724
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
725
-        $action_urls =  apply_filters(
726
-            'FHEE__EEH_MSG_Template__get_message_action_url',
727
-            array(
728
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
-                    array_merge(
732
-                        array(
733
-                            'page' => 'espresso_messages',
734
-                            'action' => 'default',
735
-                            'filterby' => 1,
736
-                        ),
737
-                        $query_params
738
-                    ),
739
-                    admin_url('admin.php')
740
-                ),
741
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
742
-                    array(
743
-                        'page' => 'espresso_messages',
744
-                        'action' => 'generate_now',
745
-                        'MSG_ID' => $message->ID()
746
-                    ),
747
-                    admin_url('admin.php')
748
-                ),
749
-                'send_now' => EEH_URL::add_query_args_and_nonce(
750
-                    array(
751
-                        'page' => 'espresso_messages',
752
-                        'action' => 'send_now',
753
-                        'MSG_ID' => $message->ID()
754
-                    ),
755
-                    admin_url('admin.php')
756
-                ),
757
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
-                    array(
759
-                        'page' => 'espresso_messages',
760
-                        'action' => 'queue_for_resending',
761
-                        'MSG_ID' => $message->ID()
762
-                    ),
763
-                    admin_url('admin.php')
764
-                ),
765
-            )
766
-        );
767
-        if (
768
-            $message->TXN_ID() > 0
769
-            && EE_Registry::instance()->CAP->current_user_can(
770
-                'ee_read_transaction',
771
-                'espresso_transactions_default',
772
-                $message->TXN_ID()
773
-            )
774
-        ) {
775
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
-                array(
777
-                    'page' => 'espresso_transactions',
778
-                    'action' => 'view_transaction',
779
-                    'TXN_ID' => $message->TXN_ID()
780
-                ),
781
-                admin_url('admin.php')
782
-            );
783
-        } else {
784
-            $action_urls['view_transaction'] = '';
785
-        }
786
-        return $action_urls;
787
-    }
788
-
789
-
790
-    /**
791
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
-     *
793
-     * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
-     *                                      empty string is returned)
795
-     * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
-     * @param array           $query_params Any extra query params to include in the generated link.
797
-     *
798
-     * @return string
799
-     * @throws EE_Error
800
-     * @throws ReflectionException
801
-     * @since 4.9.0
802
-     *
803
-     */
804
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
-    {
806
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
-        $label = $icon_css['label'] ?? null;
809
-        $label = $label ? 'aria-label="' . $label . '"' : '';
810
-        $class = $label ? ' ee-aria-tooltip' : '';
811
-
812
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
-            return '';
814
-        }
815
-
816
-        $icon_css_class = $icon_css['css_class'] . apply_filters(
817
-            'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
818
-            ' js-ee-message-action-link ee-message-action-link-' . $type,
819
-            $type,
820
-            $message,
821
-            $query_params
822
-        );
823
-
824
-        return '
16
+	/**
17
+	 * Holds a collection of EE_Message_Template_Pack objects.
18
+	 * @type EE_Messages_Template_Pack_Collection
19
+	 */
20
+	protected static $_template_pack_collection;
21
+
22
+
23
+	/**
24
+	 * @throws EE_Error
25
+	 */
26
+	private static function _set_autoloader()
27
+	{
28
+		EED_Messages::set_autoloaders();
29
+	}
30
+
31
+
32
+	/**
33
+	 * generate_new_templates
34
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
35
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
36
+	 * for the event.
37
+	 *
38
+	 * @access protected
39
+	 * @param string $messenger     the messenger we are generating templates for
40
+	 * @param array  $message_types array of message types that the templates are generated for.
41
+	 * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
42
+	 *                              to use as the base for the new generated template.
43
+	 * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
44
+	 *                              for event specific template generation.
45
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
46
+	 *                for templates that are generated.  If this is an empty array then it means no templates were
47
+	 *                generated which usually means there was an error.  Anything in the array with an empty value for
48
+	 *                `MTP_context` means that it was not a new generated template but just reactivated (which only
49
+	 *                happens for global templates that already exist in the database.
50
+	 * @throws EE_Error
51
+	 * @throws ReflectionException
52
+	 */
53
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
54
+	{
55
+		// make sure message_type is an array.
56
+		$message_types = (array) $message_types;
57
+		$templates = array();
58
+
59
+		if (empty($messenger)) {
60
+			throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
61
+		}
62
+
63
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
64
+		if (empty($message_types)) {
65
+			throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
66
+		}
67
+
68
+		EEH_MSG_Template::_set_autoloader();
69
+		foreach ($message_types as $message_type) {
70
+			// if this is global template generation.
71
+			if ($global) {
72
+				// let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
+				if (empty($GRP_ID)) {
74
+					$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
+						array(
76
+							array(
77
+								'MTP_messenger'    => $messenger,
78
+								'MTP_message_type' => $message_type,
79
+								'MTP_is_global'    => true,
80
+							),
81
+						)
82
+					);
83
+					$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
+				}
85
+				// First let's determine if we already HAVE global templates for this messenger and message_type combination.
86
+				//  If we do then NO generation!!
87
+				if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
88
+					$templates[] = array(
89
+						'GRP_ID' => $GRP_ID,
90
+						'MTP_context' => '',
91
+					);
92
+					// we already have generated templates for this so let's go to the next message type.
93
+					continue;
94
+				}
95
+			}
96
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
+
98
+			if (! $new_message_template_group) {
99
+				continue;
100
+			}
101
+			$templates[] = $new_message_template_group;
102
+		}
103
+
104
+		return $templates;
105
+	}
106
+
107
+
108
+	/**
109
+	 * The purpose of this method is to determine if there are already generated templates in the database for the
110
+	 * given variables.
111
+	 *
112
+	 * @param string $messenger    messenger
113
+	 * @param string $message_type message type
114
+	 * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
+	 *                             template check)
116
+	 * @return bool                true = generated, false = hasn't been generated.
117
+	 * @throws EE_Error
118
+	 */
119
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
+	{
121
+		EEH_MSG_Template::_set_autoloader();
122
+		// what method we use depends on whether we have an GRP_ID or not
123
+		$count = empty($GRP_ID)
124
+			? EEM_Message_Template::instance()->count(
125
+				array(
126
+					array(
127
+						'Message_Template_Group.MTP_messenger'    => $messenger,
128
+						'Message_Template_Group.MTP_message_type' => $message_type,
129
+						'Message_Template_Group.MTP_is_global'    => true
130
+					)
131
+				)
132
+			)
133
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
+
135
+		return $count > 0;
136
+	}
137
+
138
+
139
+	/**
140
+	 * Updates all message templates matching the incoming messengers and message types to active status.
141
+	 *
142
+	 * @static
143
+	 * @param array $messenger_names    Messenger slug
144
+	 * @param array $message_type_names Message type slug
145
+	 * @return  int                         count of updated records.
146
+	 * @throws EE_Error
147
+	 */
148
+	public static function update_to_active($messenger_names, $message_type_names)
149
+	{
150
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
+		return EEM_Message_Template_Group::instance()->update(
153
+			array( 'MTP_is_active' => 1 ),
154
+			array(
155
+				array(
156
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
157
+					'MTP_message_type'  => array( 'IN', $message_type_names )
158
+				)
159
+			)
160
+		);
161
+	}
162
+
163
+
164
+	/**
165
+	 * Updates all message template groups matching the incoming arguments to inactive status.
166
+	 *
167
+	 * @static
168
+	 * @param array $messenger_names    The messenger slugs.
169
+	 *                                  If empty then all templates matching the message types are marked inactive.
170
+	 *                                  Otherwise only templates matching the messengers and message types.
171
+	 * @param array $message_type_names The message type slugs.
172
+	 *                                  If empty then all templates matching the messengers are marked inactive.
173
+	 *                                  Otherwise only templates matching the messengers and message types.
174
+	 *
175
+	 * @return int  count of updated records.
176
+	 * @throws EE_Error
177
+	 */
178
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
+	{
180
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
+			$messenger_names,
182
+			$message_type_names
183
+		);
184
+	}
185
+
186
+
187
+	/**
188
+	 * The purpose of this function is to return all installed message objects
189
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
190
+	 *
191
+	 * @param string $type
192
+	 * @return array array consisting of installed messenger objects and installed message type objects.
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 * @deprecated 4.9.0
196
+	 * @static
197
+	 */
198
+	public static function get_installed_message_objects($type = 'all')
199
+	{
200
+		self::_set_autoloader();
201
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
+		return array(
203
+			'messenger' => $message_resource_manager->installed_messengers(),
204
+			'message_type' => $message_resource_manager->installed_message_types()
205
+		);
206
+	}
207
+
208
+
209
+	/**
210
+	 * This will return an array of shortcodes => labels from the
211
+	 * messenger and message_type objects associated with this
212
+	 * template.
213
+	 *
214
+	 * @param string $message_type
215
+	 * @param string $messenger
216
+	 * @param array  $fields                        What fields we're returning valid shortcodes for.
217
+	 *                                              If empty then we assume all fields are to be returned. Optional.
218
+	 * @param string $context                       What context we're going to return shortcodes for. Optional.
219
+	 * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
+	 *                                              but instead an array of the unique shortcodes for all the given (
221
+	 *                                              or all) fields. Optional.
222
+	 * @return array                                an array of shortcodes in the format
223
+	 *                                              array( '[shortcode] => 'label')
224
+	 *                                              OR
225
+	 *                                              FALSE if no shortcodes found.
226
+	 * @throws ReflectionException
227
+	 * @throws EE_Error*@since 4.3.0
228
+	 *
229
+	 */
230
+	public static function get_shortcodes(
231
+		$message_type,
232
+		$messenger,
233
+		$fields = array(),
234
+		$context = 'admin',
235
+		$merged = false
236
+	) {
237
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
240
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
+		// convert slug to object
242
+		$messenger = $message_resource_manager->get_messenger($messenger);
243
+
244
+		// if messenger isn't a EE_messenger resource then bail.
245
+		if (! $messenger instanceof EE_messenger) {
246
+			return array();
247
+		}
248
+
249
+		// validate class for getting our list of shortcodes
250
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
+		if (! class_exists($classname)) {
252
+			$msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
+			$msg[] = sprintf(
254
+				esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
+				$classname
256
+			);
257
+			throw new EE_Error(implode('||', $msg));
258
+		}
259
+
260
+		/** @type EE_Messages_Validator $_VLD */
261
+		$_VLD = new $classname(array(), $context);
262
+		$valid_shortcodes = $_VLD->get_validators();
263
+
264
+		// let's make sure we're only getting the shortcode part of the validators
265
+		$shortcodes = array();
266
+		foreach ($valid_shortcodes as $field => $validators) {
267
+			$shortcodes[ $field ] = $validators['shortcodes'];
268
+		}
269
+		$valid_shortcodes = $shortcodes;
270
+
271
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
+		if (! empty($fields)) {
273
+			$specified_shortcodes = array();
274
+			foreach ($fields as $field) {
275
+				if (isset($valid_shortcodes[ $field ])) {
276
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
+				}
278
+			}
279
+			$valid_shortcodes = $specified_shortcodes;
280
+		}
281
+
282
+		// if not merged then let's replace the fields with the localized fields
283
+		if (! $merged) {
284
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
+			$field_settings = $messenger->get_template_fields();
286
+			$localized = array();
287
+			foreach ($valid_shortcodes as $field => $shortcodes) {
288
+				// get localized field label
289
+				if (isset($field_settings[ $field ])) {
290
+					// possible that this is used as a main field.
291
+					if (empty($field_settings[ $field ])) {
292
+						if (isset($field_settings['extra'][ $field ])) {
293
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
294
+						} else {
295
+							$_field = $field;
296
+						}
297
+					} else {
298
+						$_field = $field_settings[ $field ]['label'];
299
+					}
300
+				} elseif (isset($field_settings['extra'])) {
301
+					// loop through extra "main fields" and see if any of their children have our field
302
+					foreach ($field_settings['extra'] as $fields) {
303
+						if (isset($fields[ $field ])) {
304
+							$_field = $fields[ $field ]['label'];
305
+						} else {
306
+							$_field = $field;
307
+						}
308
+					}
309
+				} else {
310
+					$_field = $field;
311
+				}
312
+				if (isset($_field)) {
313
+					$localized[ (string) $_field ] = $shortcodes;
314
+				}
315
+			}
316
+			$valid_shortcodes = $localized;
317
+		}
318
+
319
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
+		if ($merged) {
321
+			$merged_codes = array();
322
+			foreach ($valid_shortcodes as $shortcode) {
323
+				foreach ($shortcode as $code => $label) {
324
+					if (isset($merged_codes[ $code ])) {
325
+						continue;
326
+					} else {
327
+						$merged_codes[ $code ] = $label;
328
+					}
329
+				}
330
+			}
331
+			$valid_shortcodes = $merged_codes;
332
+		}
333
+
334
+		return $valid_shortcodes;
335
+	}
336
+
337
+
338
+	/**
339
+	 * Get Messenger object.
340
+	 *
341
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
+	 * @return EE_messenger
343
+	 * @throws ReflectionException
344
+	 * @throws EE_Error*@since 4.3.0
345
+	 * @deprecated 4.9.0
346
+	 */
347
+	public static function messenger_obj($messenger)
348
+	{
349
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
+		return $Message_Resource_Manager->get_messenger($messenger);
352
+	}
353
+
354
+
355
+	/**
356
+	 * get Message type object
357
+	 *
358
+	 * @param string $message_type the slug for the message type object to retrieve
359
+	 * @return EE_message_type
360
+	 * @throws ReflectionException
361
+	 * @throws EE_Error*@since 4.3.0
362
+	 * @deprecated 4.9.0
363
+	 */
364
+	public static function message_type_obj($message_type)
365
+	{
366
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
+		return $Message_Resource_Manager->get_message_type($message_type);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
374
+	 *
375
+	 * @since    4.3.0
376
+	 * @param string $message_type message type to check for.
377
+	 * @return boolean
378
+	 * @throws EE_Error
379
+	 * @throws ReflectionException
380
+	 */
381
+	public static function is_mt_active($message_type)
382
+	{
383
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
+		return in_array($message_type, $active_mts);
387
+	}
388
+
389
+
390
+	/**
391
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
392
+	 *
393
+	 * @since    4.3.0
394
+	 *
395
+	 * @param string $messenger slug for messenger to check.
396
+	 * @return boolean
397
+	 * @throws EE_Error
398
+	 * @throws ReflectionException
399
+	 */
400
+	public static function is_messenger_active($messenger)
401
+	{
402
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
+		return $active_messenger instanceof EE_messenger;
406
+	}
407
+
408
+
409
+	/**
410
+	 * Used to return active messengers array stored in the wp options table.
411
+	 * If no value is present in the option then an empty array is returned.
412
+	 *
413
+	 * @deprecated 4.9
414
+	 * @since      4.3.1
415
+	 *
416
+	 * @return array
417
+	 * @throws EE_Error
418
+	 * @throws ReflectionException
419
+	 */
420
+	public static function get_active_messengers_in_db()
421
+	{
422
+		EE_Error::doing_it_wrong(
423
+			__METHOD__,
424
+			esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
+			'4.9.0'
426
+		);
427
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
+		return $Message_Resource_Manager->get_active_messengers_option();
430
+	}
431
+
432
+
433
+	/**
434
+	 * Used to update the active messengers array stored in the wp options table.
435
+	 *
436
+	 * @since      4.3.1
437
+	 * @deprecated 4.9.0
438
+	 *
439
+	 * @param array $data_to_save Incoming data to save.
440
+	 *
441
+	 * @return bool FALSE if not updated, TRUE if updated.
442
+	 * @throws EE_Error
443
+	 * @throws ReflectionException
444
+	 */
445
+	public static function update_active_messengers_in_db($data_to_save)
446
+	{
447
+		EE_Error::doing_it_wrong(
448
+			__METHOD__,
449
+			esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
+			'4.9.0'
451
+		);
452
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
+	}
456
+
457
+
458
+	/**
459
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
+	 * appropriate url trigger
461
+	 *
462
+	 * @param EE_message_type $message_type
463
+	 * @param EE_Message $message
464
+	 * @param EE_Registration | null $registration  The registration object must be included if this
465
+	 *                                              is going to be a registration trigger url.
466
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
467
+	 *
468
+	 * @return string
469
+	 * @throws EE_Error
470
+	 */
471
+	public static function get_url_trigger(
472
+		EE_message_type $message_type,
473
+		EE_Message $message,
474
+		$registration = null,
475
+		$sending_messenger = ''
476
+	) {
477
+		// first determine if the url can be to the EE_Message object.
478
+		if (! $message_type->always_generate()) {
479
+			return EEH_MSG_Template::generate_browser_trigger($message);
480
+		}
481
+
482
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
483
+		if (! $registration instanceof EE_Registration) {
484
+			throw new EE_Error(
485
+				esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
+			);
487
+		}
488
+
489
+		// validate given context
490
+		$contexts = $message_type->get_contexts();
491
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
+			throw new EE_Error(
493
+				sprintf(
494
+					esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
+					$message->context(),
496
+					get_class($message_type)
497
+				)
498
+			);
499
+		}
500
+
501
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
+		if (! empty($sending_messenger)) {
503
+			$with_messengers = $message_type->with_messengers();
504
+			if (
505
+				! isset($with_messengers[ $message->messenger() ])
506
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
+			) {
508
+				throw new EE_Error(
509
+					sprintf(
510
+						esc_html__(
511
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
+							'event_espresso'
513
+						),
514
+						$sending_messenger,
515
+						get_class($message_type)
516
+					)
517
+				);
518
+			}
519
+		} else {
520
+			$sending_messenger = $message->messenger();
521
+		}
522
+		return EEH_MSG_Template::generate_url_trigger(
523
+			$sending_messenger,
524
+			$message->messenger(),
525
+			$message->context(),
526
+			$message->message_type(),
527
+			$registration,
528
+			$message->GRP_ID()
529
+		);
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
535
+	 * @param EE_Message $message
536
+	 * @return string.
537
+	 */
538
+	public static function generate_browser_trigger(EE_Message $message)
539
+	{
540
+		$query_args = array(
541
+			'ee' => 'msg_browser_trigger',
542
+			'token' => $message->MSG_token()
543
+		);
544
+		return apply_filters(
545
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
+			add_query_arg($query_args, site_url()),
547
+			$message
548
+		);
549
+	}
550
+
551
+
552
+
553
+
554
+
555
+
556
+	/**
557
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
+	 * @param EE_Message $message
559
+	 * @return string
560
+	 */
561
+	public static function generate_error_display_trigger(EE_Message $message)
562
+	{
563
+		return apply_filters(
564
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
+			add_query_arg(
566
+				array(
567
+					'ee' => 'msg_browser_error_trigger',
568
+					'token' => $message->MSG_token()
569
+				),
570
+				site_url()
571
+			),
572
+			$message
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
579
+	 *
580
+	 * @param string          $sending_messenger      The sending messenger slug.
581
+	 * @param string          $generating_messenger   The generating messenger slug.
582
+	 * @param string          $context                The context for the template.
583
+	 * @param string          $message_type           The message type slug
584
+	 * @param EE_Registration $registration
585
+	 * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
+	 * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
+	 *                                                trigger.
588
+	 * @return string          The generated url.
589
+	 * @throws EE_Error
590
+	 */
591
+	public static function generate_url_trigger(
592
+		$sending_messenger,
593
+		$generating_messenger,
594
+		$context,
595
+		$message_type,
596
+		EE_Registration $registration,
597
+		$message_template_group,
598
+		$data_id = 0
599
+	) {
600
+		$query_args = array(
601
+			'ee' => 'msg_url_trigger',
602
+			'snd_msgr' => $sending_messenger,
603
+			'gen_msgr' => $generating_messenger,
604
+			'message_type' => $message_type,
605
+			'context' => $context,
606
+			'token' => $registration->reg_url_link(),
607
+			'GRP_ID' => $message_template_group,
608
+			'id' => $data_id
609
+			);
610
+		$url = add_query_arg($query_args, get_home_url());
611
+
612
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
+		return apply_filters(
614
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
615
+			$url,
616
+			$sending_messenger,
617
+			$generating_messenger,
618
+			$context,
619
+			$message_type,
620
+			$registration,
621
+			$message_template_group,
622
+			$data_id
623
+		);
624
+	}
625
+
626
+
627
+
628
+
629
+	/**
630
+	 * Return the specific css for the action icon given.
631
+	 *
632
+	 * @param string $type  What action to return.
633
+	 * @return string[]
634
+	 * @since 4.9.0
635
+	 */
636
+	public static function get_message_action_icon($type)
637
+	{
638
+		$action_icons = self::get_message_action_icons();
639
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
+	}
641
+
642
+
643
+	/**
644
+	 * This is used for retrieving the css classes used for the icons representing message actions.
645
+	 *
646
+	 * @since 4.9.0
647
+	 *
648
+	 * @return array
649
+	 */
650
+	public static function get_message_action_icons()
651
+	{
652
+		return apply_filters(
653
+			'FHEE__EEH_MSG_Template__message_action_icons',
654
+			array(
655
+				'view' => array(
656
+					'label' => esc_html__('View Message', 'event_espresso'),
657
+					'css_class' => 'dashicons dashicons-visibility',
658
+				),
659
+				'error' => array(
660
+					'label' => esc_html__('View Error Message', 'event_espresso'),
661
+					'css_class' => 'dashicons dashicons-info',
662
+				),
663
+				'see_notifications_for' => array(
664
+					'label' => esc_html__('View Related Messages', 'event_espresso'),
665
+					'css_class' => 'dashicons dashicons-megaphone',
666
+				),
667
+				'generate_now' => array(
668
+					'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
+					'css_class' => 'dashicons dashicons-admin-tools',
670
+				),
671
+				'send_now' => array(
672
+					'label' => esc_html__('Send Immediately', 'event_espresso'),
673
+					'css_class' => 'dashicons dashicons-controls-forward',
674
+				),
675
+				'queue_for_resending' => array(
676
+					'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
+					'css_class' => 'dashicons dashicons-controls-repeat',
678
+				),
679
+				'view_transaction' => array(
680
+					'label' => esc_html__('View related Transaction', 'event_espresso'),
681
+					'css_class' => 'dashicons dashicons-cart',
682
+				)
683
+			)
684
+		);
685
+	}
686
+
687
+
688
+	/**
689
+	 * This returns the url for a given action related to EE_Message.
690
+	 *
691
+	 * @param string     $type         What type of action to return the url for.
692
+	 * @param EE_Message $message      Required for generating the correct url for some types.
693
+	 * @param array      $query_params Any additional query params to be included with the generated url.
694
+	 *
695
+	 * @return string
696
+	 * @throws EE_Error
697
+	 * @throws ReflectionException
698
+	 * @since 4.9.0
699
+	 *
700
+	 */
701
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
+	{
703
+		$action_urls = self::get_message_action_urls($message, $query_params);
704
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
+	}
706
+
707
+
708
+	/**
709
+	 * This returns all the current urls for EE_Message actions.
710
+	 *
711
+	 * @since 4.9.0
712
+	 *
713
+	 * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
+	 * @param array      $query_params Any additional query_params to be included with the generated url.
715
+	 *
716
+	 * @return array
717
+	 * @throws EE_Error
718
+	 * @throws ReflectionException
719
+	 */
720
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
+	{
722
+		EE_Registry::instance()->load_helper('URL');
723
+		// if $message is not an instance of EE_Message then let's just do a dummy.
724
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
725
+		$action_urls =  apply_filters(
726
+			'FHEE__EEH_MSG_Template__get_message_action_url',
727
+			array(
728
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
+					array_merge(
732
+						array(
733
+							'page' => 'espresso_messages',
734
+							'action' => 'default',
735
+							'filterby' => 1,
736
+						),
737
+						$query_params
738
+					),
739
+					admin_url('admin.php')
740
+				),
741
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
742
+					array(
743
+						'page' => 'espresso_messages',
744
+						'action' => 'generate_now',
745
+						'MSG_ID' => $message->ID()
746
+					),
747
+					admin_url('admin.php')
748
+				),
749
+				'send_now' => EEH_URL::add_query_args_and_nonce(
750
+					array(
751
+						'page' => 'espresso_messages',
752
+						'action' => 'send_now',
753
+						'MSG_ID' => $message->ID()
754
+					),
755
+					admin_url('admin.php')
756
+				),
757
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
+					array(
759
+						'page' => 'espresso_messages',
760
+						'action' => 'queue_for_resending',
761
+						'MSG_ID' => $message->ID()
762
+					),
763
+					admin_url('admin.php')
764
+				),
765
+			)
766
+		);
767
+		if (
768
+			$message->TXN_ID() > 0
769
+			&& EE_Registry::instance()->CAP->current_user_can(
770
+				'ee_read_transaction',
771
+				'espresso_transactions_default',
772
+				$message->TXN_ID()
773
+			)
774
+		) {
775
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
+				array(
777
+					'page' => 'espresso_transactions',
778
+					'action' => 'view_transaction',
779
+					'TXN_ID' => $message->TXN_ID()
780
+				),
781
+				admin_url('admin.php')
782
+			);
783
+		} else {
784
+			$action_urls['view_transaction'] = '';
785
+		}
786
+		return $action_urls;
787
+	}
788
+
789
+
790
+	/**
791
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
+	 *
793
+	 * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
+	 *                                      empty string is returned)
795
+	 * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
+	 * @param array           $query_params Any extra query params to include in the generated link.
797
+	 *
798
+	 * @return string
799
+	 * @throws EE_Error
800
+	 * @throws ReflectionException
801
+	 * @since 4.9.0
802
+	 *
803
+	 */
804
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
+	{
806
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
+		$label = $icon_css['label'] ?? null;
809
+		$label = $label ? 'aria-label="' . $label . '"' : '';
810
+		$class = $label ? ' ee-aria-tooltip' : '';
811
+
812
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
+			return '';
814
+		}
815
+
816
+		$icon_css_class = $icon_css['css_class'] . apply_filters(
817
+			'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
818
+			' js-ee-message-action-link ee-message-action-link-' . $type,
819
+			$type,
820
+			$message,
821
+			$query_params
822
+		);
823
+
824
+		return '
825 825
             <a href="' . $url . '" ' . $label . ' class="button button--icon-only' . $class . '">
826 826
                 <span class="' .  esc_attr($icon_css_class) . '"></span>
827 827
             </a>';
828
-    }
829
-
830
-
831
-
832
-
833
-
834
-    /**
835
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
836
-     *
837
-     * @since 4.9.0
838
-     * @return array
839
-     */
840
-    public static function reg_status_to_message_type_array()
841
-    {
842
-        return (array) apply_filters(
843
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
844
-            array(
845
-                EEM_Registration::status_id_approved => 'registration',
846
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
847
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
848
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
849
-                EEM_Registration::status_id_declined => 'declined_registration'
850
-            )
851
-        );
852
-    }
853
-
854
-
855
-
856
-
857
-    /**
858
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
859
-     * match, then returns an empty string.
860
-     *
861
-     * @since 4.9.0
862
-     * @param $reg_status
863
-     * @return string
864
-     */
865
-    public static function convert_reg_status_to_message_type($reg_status)
866
-    {
867
-        $reg_status_array = self::reg_status_to_message_type_array();
868
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
869
-    }
870
-
871
-
872
-    /**
873
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
874
-     *
875
-     * @since 4.9.0
876
-     * @return array
877
-     */
878
-    public static function payment_status_to_message_type_array()
879
-    {
880
-        return (array) apply_filters(
881
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
882
-            array(
883
-                EEM_Payment::status_id_approved => 'payment',
884
-                EEM_Payment::status_id_pending => 'payment_pending',
885
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
886
-                EEM_Payment::status_id_declined => 'payment_declined',
887
-                EEM_Payment::status_id_failed => 'payment_failed'
888
-            )
889
-        );
890
-    }
891
-
892
-
893
-
894
-
895
-    /**
896
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
897
-     * an empty string is returned
898
-     *
899
-     * @since 4.9.0
900
-     * @param $payment_status
901
-     * @return string
902
-     */
903
-    public static function convert_payment_status_to_message_type($payment_status)
904
-    {
905
-        $payment_status_array = self::payment_status_to_message_type_array();
906
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
907
-    }
908
-
909
-
910
-    /**
911
-     * This is used to retrieve the template pack for the given name.
912
-     *
913
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
914
-     *
915
-     * @return EE_Messages_Template_Pack
916
-     */
917
-    public static function get_template_pack($template_pack_name)
918
-    {
919
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
920
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
921
-        }
922
-
923
-        // first see if in collection already
924
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
925
-
926
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
927
-            return $template_pack;
928
-        }
929
-
930
-        // nope...let's get it.
931
-        // not set yet so let's attempt to get it.
932
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
933
-            ' ',
934
-            '_',
935
-            ucwords(
936
-                str_replace('_', ' ', $template_pack_name)
937
-            )
938
-        );
939
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
940
-            return self::get_template_pack('default');
941
-        } else {
942
-            $template_pack = new $pack_class_name();
943
-            self::$_template_pack_collection->add($template_pack);
944
-            return $template_pack;
945
-        }
946
-    }
947
-
948
-
949
-
950
-
951
-    /**
952
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
953
-     * in it.
954
-     *
955
-     * @since 4.9.0
956
-     *
957
-     * @return EE_Messages_Template_Pack_Collection
958
-     */
959
-    public static function get_template_pack_collection()
960
-    {
961
-        $new_collection = false;
962
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
963
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
964
-            $new_collection = true;
965
-        }
966
-
967
-        // glob the defaults directory for messages
968
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
969
-        foreach ($templates as $template_path) {
970
-            // grab folder name
971
-            $template = basename($template_path);
972
-
973
-            if (! $new_collection) {
974
-                // already have it?
975
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
976
-                    continue;
977
-                }
978
-            }
979
-
980
-            // setup classname.
981
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
982
-                ' ',
983
-                '_',
984
-                ucwords(
985
-                    str_replace(
986
-                        '_',
987
-                        ' ',
988
-                        $template
989
-                    )
990
-                )
991
-            );
992
-            if (! class_exists($template_pack_class_name)) {
993
-                continue;
994
-            }
995
-            self::$_template_pack_collection->add(new $template_pack_class_name());
996
-        }
997
-
998
-        /**
999
-         * Filter for plugins to add in any additional template packs
1000
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1001
-         */
1002
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1003
-        foreach ((array) $additional_template_packs as $template_pack) {
1004
-            if (
1005
-                self::$_template_pack_collection->get_by_name(
1006
-                    $template_pack->dbref
1007
-                ) instanceof EE_Messages_Template_Pack
1008
-            ) {
1009
-                continue;
1010
-            }
1011
-            self::$_template_pack_collection->add($template_pack);
1012
-        }
1013
-        return self::$_template_pack_collection;
1014
-    }
1015
-
1016
-
1017
-    /**
1018
-     * This is a wrapper for the protected _create_new_templates function
1019
-     *
1020
-     * @param string $messenger_name
1021
-     * @param string $message_type_name message type that the templates are being created for
1022
-     * @param int    $GRP_ID
1023
-     * @param bool   $global
1024
-     * @return array
1025
-     * @throws EE_Error
1026
-     * @throws ReflectionException
1027
-     */
1028
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1029
-    {
1030
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1031
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1032
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1033
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1034
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1035
-            return array();
1036
-        }
1037
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1038
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * @param EE_messenger     $messenger
1044
-     * @param EE_message_type  $message_type
1045
-     * @param                  $GRP_ID
1046
-     * @param                  $global
1047
-     * @return array|mixed
1048
-     * @throws EE_Error
1049
-     * @throws ReflectionException
1050
-     */
1051
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1052
-    {
1053
-        // if we're creating a custom template then we don't need to use the defaults class
1054
-        if (! $global) {
1055
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1056
-        }
1057
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1058
-        $Message_Template_Defaults = EE_Registry::factory(
1059
-            'EE_Messages_Template_Defaults',
1060
-            array( $messenger, $message_type, $GRP_ID )
1061
-        );
1062
-        // generate templates
1063
-        $success = $Message_Template_Defaults->create_new_templates();
1064
-
1065
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1066
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1067
-        // attempts.
1068
-        if (! $success) {
1069
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1070
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1071
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1072
-        }
1073
-
1074
-        /**
1075
-         * $success is in an array in the following format
1076
-         * array(
1077
-         *    'GRP_ID' => $new_grp_id,
1078
-         *    'MTP_context' => $first_context_in_new_templates,
1079
-         * )
1080
-         */
1081
-        return $success;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * This creates a custom template using the incoming GRP_ID
1087
-     *
1088
-     * @param EE_messenger    $messenger
1089
-     * @param EE_message_type $message_type
1090
-     * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1091
-     * @return  array $success              This will be an array in the format:
1092
-     *                                          array(
1093
-     *                                          'GRP_ID' => $new_grp_id,
1094
-     *                                          'MTP_context' => $first_context_in_created_template
1095
-     *                                          )
1096
-     * @throws EE_Error
1097
-     * @throws ReflectionException
1098
-     * @access private
1099
-     */
1100
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1101
-    {
1102
-        // defaults
1103
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1104
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1105
-        $Message_Template_Group = empty($GRP_ID)
1106
-            ? EEM_Message_Template_Group::instance()->get_one(
1107
-                array(
1108
-                    array(
1109
-                        'MTP_messenger'    => $messenger->name,
1110
-                        'MTP_message_type' => $message_type->name,
1111
-                        'MTP_is_global'    => true
1112
-                    )
1113
-                )
1114
-            )
1115
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1116
-        // if we don't have a mtg at this point then we need to bail.
1117
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1118
-            EE_Error::add_error(
1119
-                sprintf(
1120
-                    esc_html__(
1121
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1122
-                        'event_espresso'
1123
-                    ),
1124
-                    $GRP_ID
1125
-                ),
1126
-                __FILE__,
1127
-                __FUNCTION__,
1128
-                __LINE__
1129
-            );
1130
-            return $success;
1131
-        }
1132
-        // let's get all the related message_template objects for this group.
1133
-        $message_templates = $Message_Template_Group->message_templates();
1134
-        // now we have what we need to setup the new template
1135
-        $new_mtg = clone $Message_Template_Group;
1136
-        $new_mtg->set('GRP_ID', 0);
1137
-        $new_mtg->set('MTP_is_global', false);
1138
-
1139
-        /** @var RequestInterface $request */
1140
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1141
-        $template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1142
-            ? $request->getRequestParam('templateName')
1143
-            : sprintf(
1144
-                esc_html__('Custom %1$s', 'event_espresso'),
1145
-                ucwords($message_type->label['singular']) ?? esc_html__('Template', 'event_espresso')
1146
-            );
1147
-        $template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1148
-            ? $request->getRequestParam('templateDescription')
1149
-            : sprintf(
1150
-                esc_html__(
1151
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1152
-                    'event_espresso'
1153
-                ),
1154
-                $new_mtg->messenger_obj()->label['singular'],
1155
-                $new_mtg->message_type_obj()->label['singular']
1156
-            );
1157
-        $new_mtg->set('MTP_name', $template_name);
1158
-        $new_mtg->set('MTP_description', $template_description);
1159
-        // remove ALL relations on this template group so they don't get saved!
1160
-        $new_mtg->_remove_relations('Message_Template');
1161
-        $new_mtg->save();
1162
-        $success['GRP_ID'] = $new_mtg->ID();
1163
-        $success['template_name'] = $template_name;
1164
-        // add new message templates and add relation to.
1165
-        foreach ($message_templates as $message_template) {
1166
-            if (! $message_template instanceof EE_Message_Template) {
1167
-                continue;
1168
-            }
1169
-            $new_message_template = clone $message_template;
1170
-            $new_message_template->set('MTP_ID', 0);
1171
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1172
-            $new_message_template->save();
1173
-            if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1174
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1175
-            }
1176
-        }
1177
-        return $success;
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * message_type_has_active_templates_for_messenger
1183
-     *
1184
-     * @param EE_messenger    $messenger
1185
-     * @param EE_message_type $message_type
1186
-     * @param bool            $global
1187
-     * @return bool
1188
-     * @throws EE_Error
1189
-     */
1190
-    public static function message_type_has_active_templates_for_messenger(
1191
-        EE_messenger $messenger,
1192
-        EE_message_type $message_type,
1193
-        $global = false
1194
-    ) {
1195
-        // is given message_type valid for given messenger (if this is not a global save)
1196
-        if ($global) {
1197
-            return true;
1198
-        }
1199
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1200
-            array(
1201
-                array(
1202
-                    'MTP_is_active'    => true,
1203
-                    'MTP_messenger'    => $messenger->name,
1204
-                    'MTP_message_type' => $message_type->name
1205
-                )
1206
-            )
1207
-        );
1208
-        if ($active_templates > 0) {
1209
-            return true;
1210
-        }
1211
-        EE_Error::add_error(
1212
-            sprintf(
1213
-                esc_html__(
1214
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1215
-                    'event_espresso'
1216
-                ),
1217
-                $message_type->name,
1218
-                $messenger->name
1219
-            ),
1220
-            __FILE__,
1221
-            __FUNCTION__,
1222
-            __LINE__
1223
-        );
1224
-        return false;
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * get_fields
1230
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1231
-     *
1232
-     * @param string $messenger_name    name of EE_messenger
1233
-     * @param string $message_type_name name of EE_message_type
1234
-     * @return array
1235
-     * @throws EE_Error
1236
-     * @throws ReflectionException
1237
-     */
1238
-    public static function get_fields($messenger_name, $message_type_name)
1239
-    {
1240
-        $template_fields = array();
1241
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1242
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1243
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1244
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1245
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1246
-            return array();
1247
-        }
1248
-
1249
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1250
-
1251
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1252
-        foreach ($message_type->get_contexts() as $context => $details) {
1253
-            foreach ($messenger->get_template_fields() as $field => $value) {
1254
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1255
-                    continue;
1256
-                }
1257
-                $template_fields[ $context ][ $field ] = $value;
1258
-            }
1259
-        }
1260
-        if (empty($template_fields)) {
1261
-            EE_Error::add_error(
1262
-                esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1263
-                __FILE__,
1264
-                __FUNCTION__,
1265
-                __LINE__
1266
-            );
1267
-            return array();
1268
-        }
1269
-        return $template_fields;
1270
-    }
828
+	}
829
+
830
+
831
+
832
+
833
+
834
+	/**
835
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
836
+	 *
837
+	 * @since 4.9.0
838
+	 * @return array
839
+	 */
840
+	public static function reg_status_to_message_type_array()
841
+	{
842
+		return (array) apply_filters(
843
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
844
+			array(
845
+				EEM_Registration::status_id_approved => 'registration',
846
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
847
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
848
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
849
+				EEM_Registration::status_id_declined => 'declined_registration'
850
+			)
851
+		);
852
+	}
853
+
854
+
855
+
856
+
857
+	/**
858
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
859
+	 * match, then returns an empty string.
860
+	 *
861
+	 * @since 4.9.0
862
+	 * @param $reg_status
863
+	 * @return string
864
+	 */
865
+	public static function convert_reg_status_to_message_type($reg_status)
866
+	{
867
+		$reg_status_array = self::reg_status_to_message_type_array();
868
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
869
+	}
870
+
871
+
872
+	/**
873
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
874
+	 *
875
+	 * @since 4.9.0
876
+	 * @return array
877
+	 */
878
+	public static function payment_status_to_message_type_array()
879
+	{
880
+		return (array) apply_filters(
881
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
882
+			array(
883
+				EEM_Payment::status_id_approved => 'payment',
884
+				EEM_Payment::status_id_pending => 'payment_pending',
885
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
886
+				EEM_Payment::status_id_declined => 'payment_declined',
887
+				EEM_Payment::status_id_failed => 'payment_failed'
888
+			)
889
+		);
890
+	}
891
+
892
+
893
+
894
+
895
+	/**
896
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
897
+	 * an empty string is returned
898
+	 *
899
+	 * @since 4.9.0
900
+	 * @param $payment_status
901
+	 * @return string
902
+	 */
903
+	public static function convert_payment_status_to_message_type($payment_status)
904
+	{
905
+		$payment_status_array = self::payment_status_to_message_type_array();
906
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
907
+	}
908
+
909
+
910
+	/**
911
+	 * This is used to retrieve the template pack for the given name.
912
+	 *
913
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
914
+	 *
915
+	 * @return EE_Messages_Template_Pack
916
+	 */
917
+	public static function get_template_pack($template_pack_name)
918
+	{
919
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
920
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
921
+		}
922
+
923
+		// first see if in collection already
924
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
925
+
926
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
927
+			return $template_pack;
928
+		}
929
+
930
+		// nope...let's get it.
931
+		// not set yet so let's attempt to get it.
932
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
933
+			' ',
934
+			'_',
935
+			ucwords(
936
+				str_replace('_', ' ', $template_pack_name)
937
+			)
938
+		);
939
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
940
+			return self::get_template_pack('default');
941
+		} else {
942
+			$template_pack = new $pack_class_name();
943
+			self::$_template_pack_collection->add($template_pack);
944
+			return $template_pack;
945
+		}
946
+	}
947
+
948
+
949
+
950
+
951
+	/**
952
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
953
+	 * in it.
954
+	 *
955
+	 * @since 4.9.0
956
+	 *
957
+	 * @return EE_Messages_Template_Pack_Collection
958
+	 */
959
+	public static function get_template_pack_collection()
960
+	{
961
+		$new_collection = false;
962
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
963
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
964
+			$new_collection = true;
965
+		}
966
+
967
+		// glob the defaults directory for messages
968
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
969
+		foreach ($templates as $template_path) {
970
+			// grab folder name
971
+			$template = basename($template_path);
972
+
973
+			if (! $new_collection) {
974
+				// already have it?
975
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
976
+					continue;
977
+				}
978
+			}
979
+
980
+			// setup classname.
981
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
982
+				' ',
983
+				'_',
984
+				ucwords(
985
+					str_replace(
986
+						'_',
987
+						' ',
988
+						$template
989
+					)
990
+				)
991
+			);
992
+			if (! class_exists($template_pack_class_name)) {
993
+				continue;
994
+			}
995
+			self::$_template_pack_collection->add(new $template_pack_class_name());
996
+		}
997
+
998
+		/**
999
+		 * Filter for plugins to add in any additional template packs
1000
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1001
+		 */
1002
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1003
+		foreach ((array) $additional_template_packs as $template_pack) {
1004
+			if (
1005
+				self::$_template_pack_collection->get_by_name(
1006
+					$template_pack->dbref
1007
+				) instanceof EE_Messages_Template_Pack
1008
+			) {
1009
+				continue;
1010
+			}
1011
+			self::$_template_pack_collection->add($template_pack);
1012
+		}
1013
+		return self::$_template_pack_collection;
1014
+	}
1015
+
1016
+
1017
+	/**
1018
+	 * This is a wrapper for the protected _create_new_templates function
1019
+	 *
1020
+	 * @param string $messenger_name
1021
+	 * @param string $message_type_name message type that the templates are being created for
1022
+	 * @param int    $GRP_ID
1023
+	 * @param bool   $global
1024
+	 * @return array
1025
+	 * @throws EE_Error
1026
+	 * @throws ReflectionException
1027
+	 */
1028
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1029
+	{
1030
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1031
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1032
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1033
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1034
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1035
+			return array();
1036
+		}
1037
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1038
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * @param EE_messenger     $messenger
1044
+	 * @param EE_message_type  $message_type
1045
+	 * @param                  $GRP_ID
1046
+	 * @param                  $global
1047
+	 * @return array|mixed
1048
+	 * @throws EE_Error
1049
+	 * @throws ReflectionException
1050
+	 */
1051
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1052
+	{
1053
+		// if we're creating a custom template then we don't need to use the defaults class
1054
+		if (! $global) {
1055
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1056
+		}
1057
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1058
+		$Message_Template_Defaults = EE_Registry::factory(
1059
+			'EE_Messages_Template_Defaults',
1060
+			array( $messenger, $message_type, $GRP_ID )
1061
+		);
1062
+		// generate templates
1063
+		$success = $Message_Template_Defaults->create_new_templates();
1064
+
1065
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1066
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1067
+		// attempts.
1068
+		if (! $success) {
1069
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1070
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1071
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1072
+		}
1073
+
1074
+		/**
1075
+		 * $success is in an array in the following format
1076
+		 * array(
1077
+		 *    'GRP_ID' => $new_grp_id,
1078
+		 *    'MTP_context' => $first_context_in_new_templates,
1079
+		 * )
1080
+		 */
1081
+		return $success;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * This creates a custom template using the incoming GRP_ID
1087
+	 *
1088
+	 * @param EE_messenger    $messenger
1089
+	 * @param EE_message_type $message_type
1090
+	 * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1091
+	 * @return  array $success              This will be an array in the format:
1092
+	 *                                          array(
1093
+	 *                                          'GRP_ID' => $new_grp_id,
1094
+	 *                                          'MTP_context' => $first_context_in_created_template
1095
+	 *                                          )
1096
+	 * @throws EE_Error
1097
+	 * @throws ReflectionException
1098
+	 * @access private
1099
+	 */
1100
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1101
+	{
1102
+		// defaults
1103
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1104
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1105
+		$Message_Template_Group = empty($GRP_ID)
1106
+			? EEM_Message_Template_Group::instance()->get_one(
1107
+				array(
1108
+					array(
1109
+						'MTP_messenger'    => $messenger->name,
1110
+						'MTP_message_type' => $message_type->name,
1111
+						'MTP_is_global'    => true
1112
+					)
1113
+				)
1114
+			)
1115
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1116
+		// if we don't have a mtg at this point then we need to bail.
1117
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1118
+			EE_Error::add_error(
1119
+				sprintf(
1120
+					esc_html__(
1121
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1122
+						'event_espresso'
1123
+					),
1124
+					$GRP_ID
1125
+				),
1126
+				__FILE__,
1127
+				__FUNCTION__,
1128
+				__LINE__
1129
+			);
1130
+			return $success;
1131
+		}
1132
+		// let's get all the related message_template objects for this group.
1133
+		$message_templates = $Message_Template_Group->message_templates();
1134
+		// now we have what we need to setup the new template
1135
+		$new_mtg = clone $Message_Template_Group;
1136
+		$new_mtg->set('GRP_ID', 0);
1137
+		$new_mtg->set('MTP_is_global', false);
1138
+
1139
+		/** @var RequestInterface $request */
1140
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1141
+		$template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1142
+			? $request->getRequestParam('templateName')
1143
+			: sprintf(
1144
+				esc_html__('Custom %1$s', 'event_espresso'),
1145
+				ucwords($message_type->label['singular']) ?? esc_html__('Template', 'event_espresso')
1146
+			);
1147
+		$template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1148
+			? $request->getRequestParam('templateDescription')
1149
+			: sprintf(
1150
+				esc_html__(
1151
+					'This is a custom template that was created for the %s messenger and %s message type.',
1152
+					'event_espresso'
1153
+				),
1154
+				$new_mtg->messenger_obj()->label['singular'],
1155
+				$new_mtg->message_type_obj()->label['singular']
1156
+			);
1157
+		$new_mtg->set('MTP_name', $template_name);
1158
+		$new_mtg->set('MTP_description', $template_description);
1159
+		// remove ALL relations on this template group so they don't get saved!
1160
+		$new_mtg->_remove_relations('Message_Template');
1161
+		$new_mtg->save();
1162
+		$success['GRP_ID'] = $new_mtg->ID();
1163
+		$success['template_name'] = $template_name;
1164
+		// add new message templates and add relation to.
1165
+		foreach ($message_templates as $message_template) {
1166
+			if (! $message_template instanceof EE_Message_Template) {
1167
+				continue;
1168
+			}
1169
+			$new_message_template = clone $message_template;
1170
+			$new_message_template->set('MTP_ID', 0);
1171
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1172
+			$new_message_template->save();
1173
+			if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1174
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1175
+			}
1176
+		}
1177
+		return $success;
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * message_type_has_active_templates_for_messenger
1183
+	 *
1184
+	 * @param EE_messenger    $messenger
1185
+	 * @param EE_message_type $message_type
1186
+	 * @param bool            $global
1187
+	 * @return bool
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	public static function message_type_has_active_templates_for_messenger(
1191
+		EE_messenger $messenger,
1192
+		EE_message_type $message_type,
1193
+		$global = false
1194
+	) {
1195
+		// is given message_type valid for given messenger (if this is not a global save)
1196
+		if ($global) {
1197
+			return true;
1198
+		}
1199
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1200
+			array(
1201
+				array(
1202
+					'MTP_is_active'    => true,
1203
+					'MTP_messenger'    => $messenger->name,
1204
+					'MTP_message_type' => $message_type->name
1205
+				)
1206
+			)
1207
+		);
1208
+		if ($active_templates > 0) {
1209
+			return true;
1210
+		}
1211
+		EE_Error::add_error(
1212
+			sprintf(
1213
+				esc_html__(
1214
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1215
+					'event_espresso'
1216
+				),
1217
+				$message_type->name,
1218
+				$messenger->name
1219
+			),
1220
+			__FILE__,
1221
+			__FUNCTION__,
1222
+			__LINE__
1223
+		);
1224
+		return false;
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * get_fields
1230
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1231
+	 *
1232
+	 * @param string $messenger_name    name of EE_messenger
1233
+	 * @param string $message_type_name name of EE_message_type
1234
+	 * @return array
1235
+	 * @throws EE_Error
1236
+	 * @throws ReflectionException
1237
+	 */
1238
+	public static function get_fields($messenger_name, $message_type_name)
1239
+	{
1240
+		$template_fields = array();
1241
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1242
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1243
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1244
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1245
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1246
+			return array();
1247
+		}
1248
+
1249
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1250
+
1251
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1252
+		foreach ($message_type->get_contexts() as $context => $details) {
1253
+			foreach ($messenger->get_template_fields() as $field => $value) {
1254
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1255
+					continue;
1256
+				}
1257
+				$template_fields[ $context ][ $field ] = $value;
1258
+			}
1259
+		}
1260
+		if (empty($template_fields)) {
1261
+			EE_Error::add_error(
1262
+				esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1263
+				__FILE__,
1264
+				__FUNCTION__,
1265
+				__LINE__
1266
+			);
1267
+			return array();
1268
+		}
1269
+		return $template_fields;
1270
+	}
1271 1271
 }
Please login to merge, or discard this patch.