Completed
Branch BUG-10878-event-spaces-remaini... (fc4422)
by
unknown
34:51 queued 23:23
created
core/libraries/form_sections/inputs/EE_Float_Input.input.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -11,33 +11,33 @@
 block discarded – undo
11 11
 class EE_Float_Input extends EE_Form_Input_Base
12 12
 {
13 13
 
14
-    /**
15
-     * @param array $input_settings
16
-     * @throws InvalidArgumentException
17
-     */
18
-    public function __construct($input_settings = array())
19
-    {
20
-        $this->_set_display_strategy(
21
-            new EE_Number_Input_Display_Strategy(
22
-                isset($input_settings['min_value'])
23
-                    ? $input_settings['min_value']
24
-                    : null,
25
-                isset($input_settings['max_value'])
26
-                    ? $input_settings['max_value']
27
-                    : null,
28
-                isset($input_settings['step_value'])
29
-                    ? $input_settings['step_value']
30
-                    : null
31
-            )
32
-        );
33
-        $this->_set_normalization_strategy(new EE_Float_Normalization());
34
-        $this->_add_validation_strategy(
35
-            new EE_Float_Validation_Strategy(
36
-                isset($input_settings['validation_error_message'])
37
-                    ? $input_settings['validation_error_message']
38
-                    : null
39
-            )
40
-        );
41
-        parent::__construct($input_settings);
42
-    }
14
+	/**
15
+	 * @param array $input_settings
16
+	 * @throws InvalidArgumentException
17
+	 */
18
+	public function __construct($input_settings = array())
19
+	{
20
+		$this->_set_display_strategy(
21
+			new EE_Number_Input_Display_Strategy(
22
+				isset($input_settings['min_value'])
23
+					? $input_settings['min_value']
24
+					: null,
25
+				isset($input_settings['max_value'])
26
+					? $input_settings['max_value']
27
+					: null,
28
+				isset($input_settings['step_value'])
29
+					? $input_settings['step_value']
30
+					: null
31
+			)
32
+		);
33
+		$this->_set_normalization_strategy(new EE_Float_Normalization());
34
+		$this->_add_validation_strategy(
35
+			new EE_Float_Validation_Strategy(
36
+				isset($input_settings['validation_error_message'])
37
+					? $input_settings['validation_error_message']
38
+					: null
39
+			)
40
+		);
41
+		parent::__construct($input_settings);
42
+	}
43 43
 }
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_Page.core.php 1 patch
Indentation   +2689 added lines, -2689 removed lines patch added patch discarded remove patch
@@ -15,2696 +15,2696 @@
 block discarded – undo
15 15
 class Events_Admin_Page extends EE_Admin_Page_CPT
16 16
 {
17 17
 
18
-    /**
19
-     * This will hold the event object for event_details screen.
20
-     *
21
-     * @access protected
22
-     * @var EE_Event $_event
23
-     */
24
-    protected $_event;
25
-
26
-
27
-    /**
28
-     * This will hold the category object for category_details screen.
29
-     *
30
-     * @var stdClass $_category
31
-     */
32
-    protected $_category;
33
-
34
-
35
-    /**
36
-     * This will hold the event model instance
37
-     *
38
-     * @var EEM_Event $_event_model
39
-     */
40
-    protected $_event_model;
41
-
42
-
43
-
44
-    /**
45
-     * @var EE_Event
46
-     */
47
-    protected $_cpt_model_obj = false;
48
-
49
-
50
-    /**
51
-     * Initialize page props for this admin page group.
52
-     */
53
-    protected function _init_page_props()
54
-    {
55
-        $this->page_slug = EVENTS_PG_SLUG;
56
-        $this->page_label = EVENTS_LABEL;
57
-        $this->_admin_base_url = EVENTS_ADMIN_URL;
58
-        $this->_admin_base_path = EVENTS_ADMIN;
59
-        $this->_cpt_model_names = array(
60
-            'create_new' => 'EEM_Event',
61
-            'edit'       => 'EEM_Event',
62
-        );
63
-        $this->_cpt_edit_routes = array(
64
-            'espresso_events' => 'edit',
65
-        );
66
-        add_action(
67
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
68
-            array($this, 'verify_event_edit'), 10, 2
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     * Sets the ajax hooks used for this admin page group.
75
-     */
76
-    protected function _ajax_hooks()
77
-    {
78
-        add_action('wp_ajax_ee_save_timezone_setting', array($this, 'save_timezonestring_setting'));
79
-    }
80
-
81
-
82
-    /**
83
-     * Sets the page properties for this admin page group.
84
-     */
85
-    protected function _define_page_props()
86
-    {
87
-        $this->_admin_page_title = EVENTS_LABEL;
88
-        $this->_labels = array(
89
-            'buttons'      => array(
90
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
91
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
92
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
93
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
94
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
95
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
96
-            ),
97
-            'editor_title' => array(
98
-                'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
99
-            ),
100
-            'publishbox'   => array(
101
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
102
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
103
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
104
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
105
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
106
-            ),
107
-        );
108
-    }
109
-
110
-
111
-    /**
112
-     * Sets the page routes property for this admin page group.
113
-     */
114
-    protected function _set_page_routes()
115
-    {
116
-        //load formatter helper
117
-        //load field generator helper
118
-        //is there a evt_id in the request?
119
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
120
-            ? $this->_req_data['EVT_ID']
121
-            : 0;
122
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
123
-        $this->_page_routes = array(
124
-            'default'                       => array(
125
-                'func'       => '_events_overview_list_table',
126
-                'capability' => 'ee_read_events',
127
-            ),
128
-            'create_new'                    => array(
129
-                'func'       => '_create_new_cpt_item',
130
-                'capability' => 'ee_edit_events',
131
-            ),
132
-            'edit'                          => array(
133
-                'func'       => '_edit_cpt_item',
134
-                'capability' => 'ee_edit_event',
135
-                'obj_id'     => $evt_id,
136
-            ),
137
-            'copy_event'                    => array(
138
-                'func'       => '_copy_events',
139
-                'capability' => 'ee_edit_event',
140
-                'obj_id'     => $evt_id,
141
-                'noheader'   => true,
142
-            ),
143
-            'trash_event'                   => array(
144
-                'func'       => '_trash_or_restore_event',
145
-                'args'       => array('event_status' => 'trash'),
146
-                'capability' => 'ee_delete_event',
147
-                'obj_id'     => $evt_id,
148
-                'noheader'   => true,
149
-            ),
150
-            'trash_events'                  => array(
151
-                'func'       => '_trash_or_restore_events',
152
-                'args'       => array('event_status' => 'trash'),
153
-                'capability' => 'ee_delete_events',
154
-                'noheader'   => true,
155
-            ),
156
-            'restore_event'                 => array(
157
-                'func'       => '_trash_or_restore_event',
158
-                'args'       => array('event_status' => 'draft'),
159
-                'capability' => 'ee_delete_event',
160
-                'obj_id'     => $evt_id,
161
-                'noheader'   => true,
162
-            ),
163
-            'restore_events'                => array(
164
-                'func'       => '_trash_or_restore_events',
165
-                'args'       => array('event_status' => 'draft'),
166
-                'capability' => 'ee_delete_events',
167
-                'noheader'   => true,
168
-            ),
169
-            'delete_event'                  => array(
170
-                'func'       => '_delete_event',
171
-                'capability' => 'ee_delete_event',
172
-                'obj_id'     => $evt_id,
173
-                'noheader'   => true,
174
-            ),
175
-            'delete_events'                 => array(
176
-                'func'       => '_delete_events',
177
-                'capability' => 'ee_delete_events',
178
-                'noheader'   => true,
179
-            ),
180
-            'view_report'                   => array(
181
-                'func'      => '_view_report',
182
-                'capablity' => 'ee_edit_events',
183
-            ),
184
-            'default_event_settings'        => array(
185
-                'func'       => '_default_event_settings',
186
-                'capability' => 'manage_options',
187
-            ),
188
-            'update_default_event_settings' => array(
189
-                'func'       => '_update_default_event_settings',
190
-                'capability' => 'manage_options',
191
-                'noheader'   => true,
192
-            ),
193
-            'template_settings'             => array(
194
-                'func'       => '_template_settings',
195
-                'capability' => 'manage_options',
196
-            ),
197
-            //event category tab related
198
-            'add_category'                  => array(
199
-                'func'       => '_category_details',
200
-                'capability' => 'ee_edit_event_category',
201
-                'args'       => array('add'),
202
-            ),
203
-            'edit_category'                 => array(
204
-                'func'       => '_category_details',
205
-                'capability' => 'ee_edit_event_category',
206
-                'args'       => array('edit'),
207
-            ),
208
-            'delete_categories'             => array(
209
-                'func'       => '_delete_categories',
210
-                'capability' => 'ee_delete_event_category',
211
-                'noheader'   => true,
212
-            ),
213
-            'delete_category'               => array(
214
-                'func'       => '_delete_categories',
215
-                'capability' => 'ee_delete_event_category',
216
-                'noheader'   => true,
217
-            ),
218
-            'insert_category'               => array(
219
-                'func'       => '_insert_or_update_category',
220
-                'args'       => array('new_category' => true),
221
-                'capability' => 'ee_edit_event_category',
222
-                'noheader'   => true,
223
-            ),
224
-            'update_category'               => array(
225
-                'func'       => '_insert_or_update_category',
226
-                'args'       => array('new_category' => false),
227
-                'capability' => 'ee_edit_event_category',
228
-                'noheader'   => true,
229
-            ),
230
-            'category_list'                 => array(
231
-                'func'       => '_category_list_table',
232
-                'capability' => 'ee_manage_event_categories',
233
-            ),
234
-        );
235
-    }
236
-
237
-
238
-    /**
239
-     * Set the _page_config property for this admin page group.
240
-     */
241
-    protected function _set_page_config()
242
-    {
243
-        $this->_page_config = array(
244
-            'default'                => array(
245
-                'nav'           => array(
246
-                    'label' => esc_html__('Overview', 'event_espresso'),
247
-                    'order' => 10,
248
-                ),
249
-                'list_table'    => 'Events_Admin_List_Table',
250
-                'help_tabs'     => array(
251
-                    'events_overview_help_tab'                       => array(
252
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
253
-                        'filename' => 'events_overview',
254
-                    ),
255
-                    'events_overview_table_column_headings_help_tab' => array(
256
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
257
-                        'filename' => 'events_overview_table_column_headings',
258
-                    ),
259
-                    'events_overview_filters_help_tab'               => array(
260
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
261
-                        'filename' => 'events_overview_filters',
262
-                    ),
263
-                    'events_overview_view_help_tab'                  => array(
264
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
265
-                        'filename' => 'events_overview_views',
266
-                    ),
267
-                    'events_overview_other_help_tab'                 => array(
268
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
269
-                        'filename' => 'events_overview_other',
270
-                    ),
271
-                ),
272
-                'help_tour'     => array(
273
-                    'Event_Overview_Help_Tour',
274
-                    //'New_Features_Test_Help_Tour' for testing multiple help tour
275
-                ),
276
-                'qtips'         => array(
277
-                    'EE_Event_List_Table_Tips',
278
-                ),
279
-                'require_nonce' => false,
280
-            ),
281
-            'create_new'             => array(
282
-                'nav'           => array(
283
-                    'label'      => esc_html__('Add Event', 'event_espresso'),
284
-                    'order'      => 5,
285
-                    'persistent' => false,
286
-                ),
287
-                'metaboxes'     => array('_register_event_editor_meta_boxes'),
288
-                'help_tabs'     => array(
289
-                    'event_editor_help_tab'                            => array(
290
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
291
-                        'filename' => 'event_editor',
292
-                    ),
293
-                    'event_editor_title_richtexteditor_help_tab'       => array(
294
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
295
-                        'filename' => 'event_editor_title_richtexteditor',
296
-                    ),
297
-                    'event_editor_venue_details_help_tab'              => array(
298
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
299
-                        'filename' => 'event_editor_venue_details',
300
-                    ),
301
-                    'event_editor_event_datetimes_help_tab'            => array(
302
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
303
-                        'filename' => 'event_editor_event_datetimes',
304
-                    ),
305
-                    'event_editor_event_tickets_help_tab'              => array(
306
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
307
-                        'filename' => 'event_editor_event_tickets',
308
-                    ),
309
-                    'event_editor_event_registration_options_help_tab' => array(
310
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
311
-                        'filename' => 'event_editor_event_registration_options',
312
-                    ),
313
-                    'event_editor_tags_categories_help_tab'            => array(
314
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
315
-                        'filename' => 'event_editor_tags_categories',
316
-                    ),
317
-                    'event_editor_questions_registrants_help_tab'      => array(
318
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
319
-                        'filename' => 'event_editor_questions_registrants',
320
-                    ),
321
-                    'event_editor_save_new_event_help_tab'             => array(
322
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
323
-                        'filename' => 'event_editor_save_new_event',
324
-                    ),
325
-                    'event_editor_other_help_tab'                      => array(
326
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
327
-                        'filename' => 'event_editor_other',
328
-                    ),
329
-                ),
330
-                'help_tour'     => array(
331
-                    'Event_Editor_Help_Tour',
332
-                ),
333
-                'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
334
-                'require_nonce' => false,
335
-            ),
336
-            'edit'                   => array(
337
-                'nav'           => array(
338
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
339
-                    'order'      => 5,
340
-                    'persistent' => false,
341
-                    'url'        => isset($this->_req_data['post'])
342
-                        ? EE_Admin_Page::add_query_args_and_nonce(
343
-                            array('post' => $this->_req_data['post'], 'action' => 'edit'),
344
-                            $this->_current_page_view_url
345
-                        )
346
-                        : $this->_admin_base_url,
347
-                ),
348
-                'metaboxes'     => array('_register_event_editor_meta_boxes'),
349
-                'help_tabs'     => array(
350
-                    'event_editor_help_tab'                            => array(
351
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
352
-                        'filename' => 'event_editor',
353
-                    ),
354
-                    'event_editor_title_richtexteditor_help_tab'       => array(
355
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
356
-                        'filename' => 'event_editor_title_richtexteditor',
357
-                    ),
358
-                    'event_editor_venue_details_help_tab'              => array(
359
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
360
-                        'filename' => 'event_editor_venue_details',
361
-                    ),
362
-                    'event_editor_event_datetimes_help_tab'            => array(
363
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
364
-                        'filename' => 'event_editor_event_datetimes',
365
-                    ),
366
-                    'event_editor_event_tickets_help_tab'              => array(
367
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
368
-                        'filename' => 'event_editor_event_tickets',
369
-                    ),
370
-                    'event_editor_event_registration_options_help_tab' => array(
371
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
372
-                        'filename' => 'event_editor_event_registration_options',
373
-                    ),
374
-                    'event_editor_tags_categories_help_tab'            => array(
375
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
376
-                        'filename' => 'event_editor_tags_categories',
377
-                    ),
378
-                    'event_editor_questions_registrants_help_tab'      => array(
379
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
380
-                        'filename' => 'event_editor_questions_registrants',
381
-                    ),
382
-                    'event_editor_save_new_event_help_tab'             => array(
383
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
384
-                        'filename' => 'event_editor_save_new_event',
385
-                    ),
386
-                    'event_editor_other_help_tab'                      => array(
387
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
388
-                        'filename' => 'event_editor_other',
389
-                    ),
390
-                ),
391
-                /*'help_tour' => array(
18
+	/**
19
+	 * This will hold the event object for event_details screen.
20
+	 *
21
+	 * @access protected
22
+	 * @var EE_Event $_event
23
+	 */
24
+	protected $_event;
25
+
26
+
27
+	/**
28
+	 * This will hold the category object for category_details screen.
29
+	 *
30
+	 * @var stdClass $_category
31
+	 */
32
+	protected $_category;
33
+
34
+
35
+	/**
36
+	 * This will hold the event model instance
37
+	 *
38
+	 * @var EEM_Event $_event_model
39
+	 */
40
+	protected $_event_model;
41
+
42
+
43
+
44
+	/**
45
+	 * @var EE_Event
46
+	 */
47
+	protected $_cpt_model_obj = false;
48
+
49
+
50
+	/**
51
+	 * Initialize page props for this admin page group.
52
+	 */
53
+	protected function _init_page_props()
54
+	{
55
+		$this->page_slug = EVENTS_PG_SLUG;
56
+		$this->page_label = EVENTS_LABEL;
57
+		$this->_admin_base_url = EVENTS_ADMIN_URL;
58
+		$this->_admin_base_path = EVENTS_ADMIN;
59
+		$this->_cpt_model_names = array(
60
+			'create_new' => 'EEM_Event',
61
+			'edit'       => 'EEM_Event',
62
+		);
63
+		$this->_cpt_edit_routes = array(
64
+			'espresso_events' => 'edit',
65
+		);
66
+		add_action(
67
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
68
+			array($this, 'verify_event_edit'), 10, 2
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 * Sets the ajax hooks used for this admin page group.
75
+	 */
76
+	protected function _ajax_hooks()
77
+	{
78
+		add_action('wp_ajax_ee_save_timezone_setting', array($this, 'save_timezonestring_setting'));
79
+	}
80
+
81
+
82
+	/**
83
+	 * Sets the page properties for this admin page group.
84
+	 */
85
+	protected function _define_page_props()
86
+	{
87
+		$this->_admin_page_title = EVENTS_LABEL;
88
+		$this->_labels = array(
89
+			'buttons'      => array(
90
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
91
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
92
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
93
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
94
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
95
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
96
+			),
97
+			'editor_title' => array(
98
+				'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
99
+			),
100
+			'publishbox'   => array(
101
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
102
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
103
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
104
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
105
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
106
+			),
107
+		);
108
+	}
109
+
110
+
111
+	/**
112
+	 * Sets the page routes property for this admin page group.
113
+	 */
114
+	protected function _set_page_routes()
115
+	{
116
+		//load formatter helper
117
+		//load field generator helper
118
+		//is there a evt_id in the request?
119
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
120
+			? $this->_req_data['EVT_ID']
121
+			: 0;
122
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
123
+		$this->_page_routes = array(
124
+			'default'                       => array(
125
+				'func'       => '_events_overview_list_table',
126
+				'capability' => 'ee_read_events',
127
+			),
128
+			'create_new'                    => array(
129
+				'func'       => '_create_new_cpt_item',
130
+				'capability' => 'ee_edit_events',
131
+			),
132
+			'edit'                          => array(
133
+				'func'       => '_edit_cpt_item',
134
+				'capability' => 'ee_edit_event',
135
+				'obj_id'     => $evt_id,
136
+			),
137
+			'copy_event'                    => array(
138
+				'func'       => '_copy_events',
139
+				'capability' => 'ee_edit_event',
140
+				'obj_id'     => $evt_id,
141
+				'noheader'   => true,
142
+			),
143
+			'trash_event'                   => array(
144
+				'func'       => '_trash_or_restore_event',
145
+				'args'       => array('event_status' => 'trash'),
146
+				'capability' => 'ee_delete_event',
147
+				'obj_id'     => $evt_id,
148
+				'noheader'   => true,
149
+			),
150
+			'trash_events'                  => array(
151
+				'func'       => '_trash_or_restore_events',
152
+				'args'       => array('event_status' => 'trash'),
153
+				'capability' => 'ee_delete_events',
154
+				'noheader'   => true,
155
+			),
156
+			'restore_event'                 => array(
157
+				'func'       => '_trash_or_restore_event',
158
+				'args'       => array('event_status' => 'draft'),
159
+				'capability' => 'ee_delete_event',
160
+				'obj_id'     => $evt_id,
161
+				'noheader'   => true,
162
+			),
163
+			'restore_events'                => array(
164
+				'func'       => '_trash_or_restore_events',
165
+				'args'       => array('event_status' => 'draft'),
166
+				'capability' => 'ee_delete_events',
167
+				'noheader'   => true,
168
+			),
169
+			'delete_event'                  => array(
170
+				'func'       => '_delete_event',
171
+				'capability' => 'ee_delete_event',
172
+				'obj_id'     => $evt_id,
173
+				'noheader'   => true,
174
+			),
175
+			'delete_events'                 => array(
176
+				'func'       => '_delete_events',
177
+				'capability' => 'ee_delete_events',
178
+				'noheader'   => true,
179
+			),
180
+			'view_report'                   => array(
181
+				'func'      => '_view_report',
182
+				'capablity' => 'ee_edit_events',
183
+			),
184
+			'default_event_settings'        => array(
185
+				'func'       => '_default_event_settings',
186
+				'capability' => 'manage_options',
187
+			),
188
+			'update_default_event_settings' => array(
189
+				'func'       => '_update_default_event_settings',
190
+				'capability' => 'manage_options',
191
+				'noheader'   => true,
192
+			),
193
+			'template_settings'             => array(
194
+				'func'       => '_template_settings',
195
+				'capability' => 'manage_options',
196
+			),
197
+			//event category tab related
198
+			'add_category'                  => array(
199
+				'func'       => '_category_details',
200
+				'capability' => 'ee_edit_event_category',
201
+				'args'       => array('add'),
202
+			),
203
+			'edit_category'                 => array(
204
+				'func'       => '_category_details',
205
+				'capability' => 'ee_edit_event_category',
206
+				'args'       => array('edit'),
207
+			),
208
+			'delete_categories'             => array(
209
+				'func'       => '_delete_categories',
210
+				'capability' => 'ee_delete_event_category',
211
+				'noheader'   => true,
212
+			),
213
+			'delete_category'               => array(
214
+				'func'       => '_delete_categories',
215
+				'capability' => 'ee_delete_event_category',
216
+				'noheader'   => true,
217
+			),
218
+			'insert_category'               => array(
219
+				'func'       => '_insert_or_update_category',
220
+				'args'       => array('new_category' => true),
221
+				'capability' => 'ee_edit_event_category',
222
+				'noheader'   => true,
223
+			),
224
+			'update_category'               => array(
225
+				'func'       => '_insert_or_update_category',
226
+				'args'       => array('new_category' => false),
227
+				'capability' => 'ee_edit_event_category',
228
+				'noheader'   => true,
229
+			),
230
+			'category_list'                 => array(
231
+				'func'       => '_category_list_table',
232
+				'capability' => 'ee_manage_event_categories',
233
+			),
234
+		);
235
+	}
236
+
237
+
238
+	/**
239
+	 * Set the _page_config property for this admin page group.
240
+	 */
241
+	protected function _set_page_config()
242
+	{
243
+		$this->_page_config = array(
244
+			'default'                => array(
245
+				'nav'           => array(
246
+					'label' => esc_html__('Overview', 'event_espresso'),
247
+					'order' => 10,
248
+				),
249
+				'list_table'    => 'Events_Admin_List_Table',
250
+				'help_tabs'     => array(
251
+					'events_overview_help_tab'                       => array(
252
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
253
+						'filename' => 'events_overview',
254
+					),
255
+					'events_overview_table_column_headings_help_tab' => array(
256
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
257
+						'filename' => 'events_overview_table_column_headings',
258
+					),
259
+					'events_overview_filters_help_tab'               => array(
260
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
261
+						'filename' => 'events_overview_filters',
262
+					),
263
+					'events_overview_view_help_tab'                  => array(
264
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
265
+						'filename' => 'events_overview_views',
266
+					),
267
+					'events_overview_other_help_tab'                 => array(
268
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
269
+						'filename' => 'events_overview_other',
270
+					),
271
+				),
272
+				'help_tour'     => array(
273
+					'Event_Overview_Help_Tour',
274
+					//'New_Features_Test_Help_Tour' for testing multiple help tour
275
+				),
276
+				'qtips'         => array(
277
+					'EE_Event_List_Table_Tips',
278
+				),
279
+				'require_nonce' => false,
280
+			),
281
+			'create_new'             => array(
282
+				'nav'           => array(
283
+					'label'      => esc_html__('Add Event', 'event_espresso'),
284
+					'order'      => 5,
285
+					'persistent' => false,
286
+				),
287
+				'metaboxes'     => array('_register_event_editor_meta_boxes'),
288
+				'help_tabs'     => array(
289
+					'event_editor_help_tab'                            => array(
290
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
291
+						'filename' => 'event_editor',
292
+					),
293
+					'event_editor_title_richtexteditor_help_tab'       => array(
294
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
295
+						'filename' => 'event_editor_title_richtexteditor',
296
+					),
297
+					'event_editor_venue_details_help_tab'              => array(
298
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
299
+						'filename' => 'event_editor_venue_details',
300
+					),
301
+					'event_editor_event_datetimes_help_tab'            => array(
302
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
303
+						'filename' => 'event_editor_event_datetimes',
304
+					),
305
+					'event_editor_event_tickets_help_tab'              => array(
306
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
307
+						'filename' => 'event_editor_event_tickets',
308
+					),
309
+					'event_editor_event_registration_options_help_tab' => array(
310
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
311
+						'filename' => 'event_editor_event_registration_options',
312
+					),
313
+					'event_editor_tags_categories_help_tab'            => array(
314
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
315
+						'filename' => 'event_editor_tags_categories',
316
+					),
317
+					'event_editor_questions_registrants_help_tab'      => array(
318
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
319
+						'filename' => 'event_editor_questions_registrants',
320
+					),
321
+					'event_editor_save_new_event_help_tab'             => array(
322
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
323
+						'filename' => 'event_editor_save_new_event',
324
+					),
325
+					'event_editor_other_help_tab'                      => array(
326
+						'title'    => esc_html__('Event Other', 'event_espresso'),
327
+						'filename' => 'event_editor_other',
328
+					),
329
+				),
330
+				'help_tour'     => array(
331
+					'Event_Editor_Help_Tour',
332
+				),
333
+				'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
334
+				'require_nonce' => false,
335
+			),
336
+			'edit'                   => array(
337
+				'nav'           => array(
338
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
339
+					'order'      => 5,
340
+					'persistent' => false,
341
+					'url'        => isset($this->_req_data['post'])
342
+						? EE_Admin_Page::add_query_args_and_nonce(
343
+							array('post' => $this->_req_data['post'], 'action' => 'edit'),
344
+							$this->_current_page_view_url
345
+						)
346
+						: $this->_admin_base_url,
347
+				),
348
+				'metaboxes'     => array('_register_event_editor_meta_boxes'),
349
+				'help_tabs'     => array(
350
+					'event_editor_help_tab'                            => array(
351
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
352
+						'filename' => 'event_editor',
353
+					),
354
+					'event_editor_title_richtexteditor_help_tab'       => array(
355
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
356
+						'filename' => 'event_editor_title_richtexteditor',
357
+					),
358
+					'event_editor_venue_details_help_tab'              => array(
359
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
360
+						'filename' => 'event_editor_venue_details',
361
+					),
362
+					'event_editor_event_datetimes_help_tab'            => array(
363
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
364
+						'filename' => 'event_editor_event_datetimes',
365
+					),
366
+					'event_editor_event_tickets_help_tab'              => array(
367
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
368
+						'filename' => 'event_editor_event_tickets',
369
+					),
370
+					'event_editor_event_registration_options_help_tab' => array(
371
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
372
+						'filename' => 'event_editor_event_registration_options',
373
+					),
374
+					'event_editor_tags_categories_help_tab'            => array(
375
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
376
+						'filename' => 'event_editor_tags_categories',
377
+					),
378
+					'event_editor_questions_registrants_help_tab'      => array(
379
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
380
+						'filename' => 'event_editor_questions_registrants',
381
+					),
382
+					'event_editor_save_new_event_help_tab'             => array(
383
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
384
+						'filename' => 'event_editor_save_new_event',
385
+					),
386
+					'event_editor_other_help_tab'                      => array(
387
+						'title'    => esc_html__('Event Other', 'event_espresso'),
388
+						'filename' => 'event_editor_other',
389
+					),
390
+				),
391
+				/*'help_tour' => array(
392 392
 					'Event_Edit_Help_Tour'
393 393
 				),*/
394
-                'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
395
-                'require_nonce' => false,
396
-            ),
397
-            'default_event_settings' => array(
398
-                'nav'           => array(
399
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
400
-                    'order' => 40,
401
-                ),
402
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
403
-                'labels'        => array(
404
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
405
-                ),
406
-                'help_tabs'     => array(
407
-                    'default_settings_help_tab'        => array(
408
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
409
-                        'filename' => 'events_default_settings',
410
-                    ),
411
-                    'default_settings_status_help_tab' => array(
412
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
413
-                        'filename' => 'events_default_settings_status',
414
-                    ),
415
-                    'default_maximum_tickets_help_tab' => array(
416
-                        'title' => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
417
-                        'filename' => 'events_default_settings_max_tickets',
418
-                    )
419
-                ),
420
-                'help_tour'     => array('Event_Default_Settings_Help_Tour'),
421
-                'require_nonce' => false,
422
-            ),
423
-            //template settings
424
-            'template_settings'      => array(
425
-                'nav'           => array(
426
-                    'label' => esc_html__('Templates', 'event_espresso'),
427
-                    'order' => 30,
428
-                ),
429
-                'metaboxes'     => $this->_default_espresso_metaboxes,
430
-                'help_tabs'     => array(
431
-                    'general_settings_templates_help_tab' => array(
432
-                        'title'    => esc_html__('Templates', 'event_espresso'),
433
-                        'filename' => 'general_settings_templates',
434
-                    ),
435
-                ),
436
-                'help_tour'     => array('Templates_Help_Tour'),
437
-                'require_nonce' => false,
438
-            ),
439
-            //event category stuff
440
-            'add_category'           => array(
441
-                'nav'           => array(
442
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
443
-                    'order'      => 15,
444
-                    'persistent' => false,
445
-                ),
446
-                'help_tabs'     => array(
447
-                    'add_category_help_tab' => array(
448
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
449
-                        'filename' => 'events_add_category',
450
-                    ),
451
-                ),
452
-                'help_tour'     => array('Event_Add_Category_Help_Tour'),
453
-                'metaboxes'     => array('_publish_post_box'),
454
-                'require_nonce' => false,
455
-            ),
456
-            'edit_category'          => array(
457
-                'nav'           => array(
458
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
459
-                    'order'      => 15,
460
-                    'persistent' => false,
461
-                    'url'        => isset($this->_req_data['EVT_CAT_ID'])
462
-                        ? add_query_arg(
463
-                            array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID']),
464
-                            $this->_current_page_view_url
465
-                        )
466
-                        : $this->_admin_base_url,
467
-                ),
468
-                'help_tabs'     => array(
469
-                    'edit_category_help_tab' => array(
470
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
471
-                        'filename' => 'events_edit_category',
472
-                    ),
473
-                ),
474
-                /*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
475
-                'metaboxes'     => array('_publish_post_box'),
476
-                'require_nonce' => false,
477
-            ),
478
-            'category_list'          => array(
479
-                'nav'           => array(
480
-                    'label' => esc_html__('Categories', 'event_espresso'),
481
-                    'order' => 20,
482
-                ),
483
-                'list_table'    => 'Event_Categories_Admin_List_Table',
484
-                'help_tabs'     => array(
485
-                    'events_categories_help_tab'                       => array(
486
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
487
-                        'filename' => 'events_categories',
488
-                    ),
489
-                    'events_categories_table_column_headings_help_tab' => array(
490
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
491
-                        'filename' => 'events_categories_table_column_headings',
492
-                    ),
493
-                    'events_categories_view_help_tab'                  => array(
494
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
495
-                        'filename' => 'events_categories_views',
496
-                    ),
497
-                    'events_categories_other_help_tab'                 => array(
498
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
499
-                        'filename' => 'events_categories_other',
500
-                    ),
501
-                ),
502
-                'help_tour'     => array(
503
-                    'Event_Categories_Help_Tour',
504
-                ),
505
-                'metaboxes'     => $this->_default_espresso_metaboxes,
506
-                'require_nonce' => false,
507
-            ),
508
-        );
509
-    }
510
-
511
-
512
-    /**
513
-     * Used to register any global screen options if necessary for every route in this admin page group.
514
-     */
515
-    protected function _add_screen_options()
516
-    {
517
-    }
518
-
519
-
520
-    /**
521
-     * Implementing the screen options for the 'default' route.
522
-     */
523
-    protected function _add_screen_options_default()
524
-    {
525
-        $this->_per_page_screen_option();
526
-    }
527
-
528
-
529
-    /**
530
-     * Implementing screen options for the category list route.
531
-     */
532
-    protected function _add_screen_options_category_list()
533
-    {
534
-        $page_title = $this->_admin_page_title;
535
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
536
-        $this->_per_page_screen_option();
537
-        $this->_admin_page_title = $page_title;
538
-    }
539
-
540
-
541
-    /**
542
-     * Used to register any global feature pointers for the admin page group.
543
-     */
544
-    protected function _add_feature_pointers()
545
-    {
546
-    }
547
-
548
-
549
-    /**
550
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
551
-     */
552
-    public function load_scripts_styles()
553
-    {
554
-        wp_register_style(
555
-            'events-admin-css',
556
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
557
-            array(),
558
-            EVENT_ESPRESSO_VERSION
559
-        );
560
-        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION);
561
-        wp_enqueue_style('events-admin-css');
562
-        wp_enqueue_style('ee-cat-admin');
563
-        //todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
564
-        //registers for all views
565
-        //scripts
566
-        wp_register_script(
567
-            'event_editor_js',
568
-            EVENTS_ASSETS_URL . 'event_editor.js',
569
-            array('ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'),
570
-            EVENT_ESPRESSO_VERSION,
571
-            true
572
-        );
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * Enqueuing scripts and styles specific to this view
579
-     */
580
-    public function load_scripts_styles_create_new()
581
-    {
582
-        $this->load_scripts_styles_edit();
583
-    }
584
-
585
-
586
-
587
-    /**
588
-     * Enqueuing scripts and styles specific to this view
589
-     */
590
-    public function load_scripts_styles_edit()
591
-    {
592
-        //styles
593
-        wp_enqueue_style('espresso-ui-theme');
594
-        wp_register_style(
595
-            'event-editor-css',
596
-            EVENTS_ASSETS_URL . 'event-editor.css',
597
-            array('ee-admin-css'),
598
-            EVENT_ESPRESSO_VERSION
599
-        );
600
-        wp_enqueue_style('event-editor-css');
601
-        //scripts
602
-        wp_register_script(
603
-            'event-datetime-metabox',
604
-            EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
605
-            array('event_editor_js', 'ee-datepicker'),
606
-            EVENT_ESPRESSO_VERSION
607
-        );
608
-        wp_enqueue_script('event-datetime-metabox');
609
-    }
610
-
611
-
612
-    /**
613
-     * Populating the _views property for the category list table view.
614
-     */
615
-    protected function _set_list_table_views_category_list()
616
-    {
617
-        $this->_views = array(
618
-            'all' => array(
619
-                'slug'        => 'all',
620
-                'label'       => esc_html__('All', 'event_espresso'),
621
-                'count'       => 0,
622
-                'bulk_action' => array(
623
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
624
-                ),
625
-            ),
626
-        );
627
-    }
628
-
629
-
630
-    /**
631
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
632
-     */
633
-    public function admin_init()
634
-    {
635
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
636
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
637
-            'event_espresso'
638
-        );
639
-    }
640
-
641
-
642
-    /**
643
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page group.
644
-     */
645
-    public function admin_notices()
646
-    {
647
-    }
648
-
649
-
650
-    /**
651
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
652
-     * this admin page group.
653
-     */
654
-    public function admin_footer_scripts()
655
-    {
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
662
-     * warning (via EE_Error::add_error());
663
-     *
664
-     * @param  EE_Event $event Event object
665
-     * @param string    $req_type
666
-     * @return void
667
-     * @throws EE_Error
668
-     * @access public
669
-     */
670
-    public function verify_event_edit($event = null, $req_type = '')
671
-    {
672
-        // don't need to do this when processing
673
-        if(!empty($req_type)) {
674
-            return;
675
-        }
676
-        // no event?
677
-        if (empty($event)) {
678
-            // set event
679
-            $event = $this->_cpt_model_obj;
680
-        }
681
-        // STILL no event?
682
-        if (! $event instanceof EE_Event) {
683
-            return;
684
-        }
685
-        $orig_status = $event->status();
686
-        // first check if event is active.
687
-        if (
688
-            $orig_status === EEM_Event::cancelled
689
-            || $orig_status === EEM_Event::postponed
690
-            || $event->is_expired()
691
-            || $event->is_inactive()
692
-        ) {
693
-            return;
694
-        }
695
-        //made it here so it IS active... next check that any of the tickets are sold.
696
-        if ($event->is_sold_out(true)) {
697
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
698
-                EE_Error::add_attention(
699
-                    sprintf(
700
-                        esc_html__(
701
-                            '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.',
702
-                            'event_espresso'
703
-                        ),
704
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
705
-                    )
706
-                );
707
-            }
708
-            return;
709
-        } else if ($orig_status === EEM_Event::sold_out) {
710
-            EE_Error::add_attention(
711
-                sprintf(
712
-                    esc_html__(
713
-                        '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.',
714
-                        'event_espresso'
715
-                    ),
716
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
717
-                )
718
-            );
719
-        }
720
-        //now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
721
-        if ( ! $event->tickets_on_sale()) {
722
-            return;
723
-        }
724
-        //made it here so show warning
725
-        $this->_edit_event_warning();
726
-    }
727
-
728
-
729
-
730
-    /**
731
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
732
-     * When needed, hook this into a EE_Error::add_error() notice.
733
-     *
734
-     * @access protected
735
-     * @return void
736
-     */
737
-    protected function _edit_event_warning()
738
-    {
739
-        // we don't want to add warnings during these requests
740
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'editpost') {
741
-            return;
742
-        }
743
-        EE_Error::add_attention(
744
-            esc_html__(
745
-                'Please be advised that this event has been published and is open for registrations on your website. If you update any registration-related details (i.e. custom questions, messages, tickets, datetimes, etc.) while a registration is in process, the registration process could be interrupted and result in errors for the person registering and potentially incorrect registration or transaction data inside Event Espresso. We recommend editing events during a period of slow traffic, or even temporarily changing the status of an event to "Draft" until your edits are complete.',
746
-                'event_espresso'
747
-            )
748
-        );
749
-    }
750
-
751
-
752
-
753
-    /**
754
-     * When a user is creating a new event, notify them if they haven't set their timezone.
755
-     * Otherwise, do the normal logic
756
-     *
757
-     * @return string
758
-     * @throws \EE_Error
759
-     */
760
-    protected function _create_new_cpt_item()
761
-    {
762
-        $has_timezone_string = get_option('timezone_string');
763
-        //only nag them about setting their timezone if it's their first event, and they haven't already done it
764
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists(array())) {
765
-            EE_Error::add_attention(
766
-                sprintf(
767
-                    __(
768
-                        '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',
769
-                        'event_espresso'
770
-                    ),
771
-                    '<br>',
772
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
773
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
774
-                    . '</select>',
775
-                    '<button class="button button-secondary timezone-submit">',
776
-                    '</button><span class="spinner"></span>'
777
-                ),
778
-                __FILE__,
779
-                __FUNCTION__,
780
-                __LINE__
781
-            );
782
-        }
783
-        return parent::_create_new_cpt_item();
784
-    }
785
-
786
-
787
-    /**
788
-     * Sets the _views property for the default route in this admin page group.
789
-     */
790
-    protected function _set_list_table_views_default()
791
-    {
792
-        $this->_views = array(
793
-            'all'   => array(
794
-                'slug'        => 'all',
795
-                'label'       => esc_html__('View All Events', 'event_espresso'),
796
-                'count'       => 0,
797
-                'bulk_action' => array(
798
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
799
-                ),
800
-            ),
801
-            'draft' => array(
802
-                'slug'        => 'draft',
803
-                'label'       => esc_html__('Draft', 'event_espresso'),
804
-                'count'       => 0,
805
-                'bulk_action' => array(
806
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
807
-                ),
808
-            ),
809
-        );
810
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
811
-            $this->_views['trash'] = array(
812
-                'slug'        => 'trash',
813
-                'label'       => esc_html__('Trash', 'event_espresso'),
814
-                'count'       => 0,
815
-                'bulk_action' => array(
816
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
817
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
818
-                ),
819
-            );
820
-        }
821
-    }
822
-
823
-
824
-
825
-    /**
826
-     * Provides the legend item array for the default list table view.
827
-     * @return array
828
-     */
829
-    protected function _event_legend_items()
830
-    {
831
-        $items = array(
832
-            'view_details'   => array(
833
-                'class' => 'dashicons dashicons-search',
834
-                'desc'  => esc_html__('View Event', 'event_espresso'),
835
-            ),
836
-            'edit_event'     => array(
837
-                'class' => 'ee-icon ee-icon-calendar-edit',
838
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
839
-            ),
840
-            'view_attendees' => array(
841
-                'class' => 'dashicons dashicons-groups',
842
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
843
-            ),
844
-        );
845
-        $items = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
846
-        $statuses = array(
847
-            'sold_out_status'  => array(
848
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
849
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
850
-            ),
851
-            'active_status'    => array(
852
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
853
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
854
-            ),
855
-            'upcoming_status'  => array(
856
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
857
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
858
-            ),
859
-            'postponed_status' => array(
860
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
861
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
862
-            ),
863
-            'cancelled_status' => array(
864
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
865
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
866
-            ),
867
-            'expired_status'   => array(
868
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
869
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
870
-            ),
871
-            'inactive_status'  => array(
872
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
873
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
874
-            ),
875
-        );
876
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
877
-        return array_merge($items, $statuses);
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     * @return EEM_Event
884
-     */
885
-    private function _event_model()
886
-    {
887
-        if ( ! $this->_event_model instanceof EEM_Event) {
888
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
889
-        }
890
-        return $this->_event_model;
891
-    }
892
-
893
-
894
-
895
-    /**
896
-     * Adds extra buttons to the WP CPT permalink field row.
897
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
898
-     *
899
-     * @param  string $return    the current html
900
-     * @param  int    $id        the post id for the page
901
-     * @param  string $new_title What the title is
902
-     * @param  string $new_slug  what the slug is
903
-     * @return string            The new html string for the permalink area
904
-     */
905
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
906
-    {
907
-        //make sure this is only when editing
908
-        if ( ! empty($id)) {
909
-            $post = get_post($id);
910
-            $return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
911
-                       . esc_html__('Shortcode', 'event_espresso')
912
-                       . '</a> ';
913
-            $return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
914
-                       . $post->ID
915
-                       . ']">';
916
-        }
917
-        return $return;
918
-    }
919
-
920
-
921
-
922
-    /**
923
-     * _events_overview_list_table
924
-     * This contains the logic for showing the events_overview list
925
-     *
926
-     * @access protected
927
-     * @return void
928
-     * @throws \EE_Error
929
-     */
930
-    protected function _events_overview_list_table()
931
-    {
932
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
933
-        $this->_template_args['after_list_table'] = ! empty($this->_template_args['after_list_table'])
934
-            ? (array)$this->_template_args['after_list_table']
935
-            : array();
936
-        $this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
937
-                                                                              . EEH_Template::get_button_or_link(
938
-                get_post_type_archive_link('espresso_events'),
939
-                esc_html__("View Event Archive Page", "event_espresso"),
940
-                'button'
941
-            );
942
-        $this->_template_args['after_list_table']['legend'] = $this->_display_legend($this->_event_legend_items());
943
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
944
-                'create_new',
945
-                'add',
946
-                array(),
947
-                'add-new-h2'
948
-            );
949
-        $this->display_admin_list_table_page_with_no_sidebar();
950
-    }
951
-
952
-
953
-
954
-    /**
955
-     * this allows for extra misc actions in the default WP publish box
956
-     *
957
-     * @return void
958
-     */
959
-    public function extra_misc_actions_publish_box()
960
-    {
961
-        $this->_generate_publish_box_extra_content();
962
-    }
963
-
964
-
965
-
966
-    /**
967
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been saved.
968
-     * Typically you would use this to save any additional data.
969
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
970
-     * ALSO very important.  When a post transitions from scheduled to published,
971
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from other meta saves.
972
-     * So MAKE sure that you handle this accordingly.
973
-     *
974
-     * @access protected
975
-     * @abstract
976
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
977
-     * @param  object $post    The post object of the cpt that was saved.
978
-     * @return void
979
-     * @throws \EE_Error
980
-     */
981
-    protected function _insert_update_cpt_item($post_id, $post)
982
-    {
983
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
984
-            //get out we're not processing an event save.
985
-            return;
986
-        }
987
-        $event_values = array(
988
-            'EVT_display_desc'                => ! empty($this->_req_data['display_desc']) ? 1 : 0,
989
-            'EVT_display_ticket_selector'     => ! empty($this->_req_data['display_ticket_selector']) ? 1 : 0,
990
-            'EVT_additional_limit'            => min(
991
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
992
-                ! empty($this->_req_data['additional_limit']) ? $this->_req_data['additional_limit'] : null
993
-            ),
994
-            'EVT_default_registration_status' => ! empty($this->_req_data['EVT_default_registration_status'])
995
-                ? $this->_req_data['EVT_default_registration_status']
996
-                : EE_Registry::instance()->CFG->registration->default_STS_ID,
997
-            'EVT_member_only'                 => ! empty($this->_req_data['member_only']) ? 1 : 0,
998
-            'EVT_allow_overflow'              => ! empty($this->_req_data['EVT_allow_overflow']) ? 1 : 0,
999
-            'EVT_timezone_string'             => ! empty($this->_req_data['timezone_string'])
1000
-                ? $this->_req_data['timezone_string'] : null,
1001
-            'EVT_external_URL'                => ! empty($this->_req_data['externalURL'])
1002
-                ? $this->_req_data['externalURL'] : null,
1003
-            'EVT_phone'                       => ! empty($this->_req_data['event_phone'])
1004
-                ? $this->_req_data['event_phone'] : null,
1005
-        );
1006
-        //update event
1007
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1008
-        //get event_object for other metaboxes... though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id ).. i have to setup where conditions to override the filters in the model that filter out autodraft and inherit statuses so we GET the inherit id!
1009
-        $get_one_where = array(
1010
-            $this->_event_model()->primary_key_name() => $post_id,
1011
-            'OR' => array(
1012
-                'status' => $post->post_status,
1013
-                // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1014
-                // but the returned object here has a status of "publish", so use the original post status as well
1015
-                'status*1' => $this->_req_data['original_post_status'],
1016
-            )
1017
-        );
1018
-        $event = $this->_event_model()->get_one(array($get_one_where));
1019
-        //the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1020
-        $event_update_callbacks = apply_filters(
1021
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1022
-            array(
1023
-                array($this, '_default_venue_update'),
1024
-                array($this, '_default_tickets_update')
1025
-            )
1026
-        );
1027
-        $att_success = true;
1028
-        foreach ($event_update_callbacks as $e_callback) {
1029
-            $_success = is_callable($e_callback)
1030
-                ? call_user_func($e_callback, $event, $this->_req_data)
1031
-                : false;
1032
-            //if ANY of these updates fail then we want the appropriate global error message
1033
-            $att_success = ! $att_success ? $att_success : $_success;
1034
-        }
1035
-        //any errors?
1036
-        if ($success && false === $att_success) {
1037
-            EE_Error::add_error(
1038
-                esc_html__(
1039
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1040
-                    'event_espresso'
1041
-                ),
1042
-                __FILE__,
1043
-                __FUNCTION__,
1044
-                __LINE__
1045
-            );
1046
-        } else if ($success === false) {
1047
-            EE_Error::add_error(
1048
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1049
-                __FILE__,
1050
-                __FUNCTION__,
1051
-                __LINE__
1052
-            );
1053
-        }
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * @see parent::restore_item()
1060
-     * @param int $post_id
1061
-     * @param int $revision_id
1062
-     */
1063
-    protected function _restore_cpt_item($post_id, $revision_id)
1064
-    {
1065
-        //copy existing event meta to new post
1066
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1067
-        if ($post_evt instanceof EE_Event) {
1068
-            //meta revision restore
1069
-            $post_evt->restore_revision($revision_id);
1070
-            //related objs restore
1071
-            $post_evt->restore_revision($revision_id, array('Venue', 'Datetime', 'Price'));
1072
-        }
1073
-    }
1074
-
1075
-
1076
-
1077
-    /**
1078
-     * Attach the venue to the Event
1079
-     *
1080
-     * @param  \EE_Event $evtobj Event Object to add the venue to
1081
-     * @param  array     $data   The request data from the form
1082
-     * @return bool           Success or fail.
1083
-     */
1084
-    protected function _default_venue_update(\EE_Event $evtobj, $data)
1085
-    {
1086
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1087
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1088
-        $rows_affected = null;
1089
-        $venue_id = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1090
-        // very important.  If we don't have a venue name...
1091
-        // then we'll get out because not necessary to create empty venue
1092
-        if (empty($data['venue_title'])) {
1093
-            return false;
1094
-        }
1095
-        $venue_array = array(
1096
-            'VNU_wp_user'         => $evtobj->get('EVT_wp_user'),
1097
-            'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1098
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1099
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1100
-            'VNU_short_desc'      => ! empty($data['venue_short_description']) ? $data['venue_short_description']
1101
-                : null,
1102
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1103
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1104
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1105
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1106
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1107
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1108
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1109
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1110
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1111
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1112
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1113
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1114
-            'status'              => 'publish',
1115
-        );
1116
-        //if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1117
-        if ( ! empty($venue_id)) {
1118
-            $update_where = array($venue_model->primary_key_name() => $venue_id);
1119
-            $rows_affected = $venue_model->update($venue_array, array($update_where));
1120
-            //we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1121
-            $evtobj->_add_relation_to($venue_id, 'Venue');
1122
-            return $rows_affected > 0 ? true : false;
1123
-        } else {
1124
-            //we insert the venue
1125
-            $venue_id = $venue_model->insert($venue_array);
1126
-            $evtobj->_add_relation_to($venue_id, 'Venue');
1127
-            return ! empty($venue_id) ? true : false;
1128
-        }
1129
-        //when we have the ancestor come in it's already been handled by the revision save.
1130
-    }
1131
-
1132
-
1133
-
1134
-    /**
1135
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1136
-     *
1137
-     * @param  EE_Event $evtobj The Event object we're attaching data to
1138
-     * @param  array    $data   The request data from the form
1139
-     * @return array
1140
-     */
1141
-    protected function _default_tickets_update(EE_Event $evtobj, $data)
1142
-    {
1143
-        $success = true;
1144
-        $saved_dtt = null;
1145
-        $saved_tickets = array();
1146
-        $incoming_date_formats = array('Y-m-d', 'h:i a');
1147
-        foreach ($data['edit_event_datetimes'] as $row => $dtt) {
1148
-            //trim all values to ensure any excess whitespace is removed.
1149
-            $dtt = array_map('trim', $dtt);
1150
-            $dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end']
1151
-                : $dtt['DTT_EVT_start'];
1152
-            $datetime_values = array(
1153
-                'DTT_ID'        => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
1154
-                'DTT_EVT_start' => $dtt['DTT_EVT_start'],
1155
-                'DTT_EVT_end'   => $dtt['DTT_EVT_end'],
1156
-                'DTT_reg_limit' => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
1157
-                'DTT_order'     => $row,
1158
-            );
1159
-            //if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
1160
-            if ( ! empty($dtt['DTT_ID'])) {
1161
-                $DTM = EE_Registry::instance()
1162
-                                  ->load_model('Datetime', array($evtobj->get_timezone()))
1163
-                                  ->get_one_by_ID($dtt['DTT_ID']);
1164
-                $DTM->set_date_format($incoming_date_formats[0]);
1165
-                $DTM->set_time_format($incoming_date_formats[1]);
1166
-                foreach ($datetime_values as $field => $value) {
1167
-                    $DTM->set($field, $value);
1168
-                }
1169
-                //make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.  We need to do this so we dont' TRASH the parent DTT.
1170
-                $saved_dtts[$DTM->ID()] = $DTM;
1171
-            } else {
1172
-                $DTM = EE_Registry::instance()->load_class(
1173
-                    'Datetime',
1174
-                    array($datetime_values, $evtobj->get_timezone(), $incoming_date_formats),
1175
-                    false,
1176
-                    false
1177
-                );
1178
-                foreach ($datetime_values as $field => $value) {
1179
-                    $DTM->set($field, $value);
1180
-                }
1181
-            }
1182
-            $DTM->save();
1183
-            $DTT = $evtobj->_add_relation_to($DTM, 'Datetime');
1184
-            //load DTT helper
1185
-            //before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1186
-            if ($DTT->get_raw('DTT_EVT_start') > $DTT->get_raw('DTT_EVT_end')) {
1187
-                $DTT->set('DTT_EVT_end', $DTT->get('DTT_EVT_start'));
1188
-                $DTT = EEH_DTT_Helper::date_time_add($DTT, 'DTT_EVT_end', 'days');
1189
-                $DTT->save();
1190
-            }
1191
-            //now we got to make sure we add the new DTT_ID to the $saved_dtts array  because it is possible there was a new one created for the autosave.
1192
-            $saved_dtt = $DTT;
1193
-            $success = ! $success ? $success : $DTT;
1194
-            //if ANY of these updates fail then we want the appropriate global error message.
1195
-            // //todo this is actually sucky we need a better error message but this is what it is for now.
1196
-        }
1197
-        //no dtts get deleted so we don't do any of that logic here.
1198
-        //update tickets next
1199
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
1200
-        foreach ($data['edit_tickets'] as $row => $tkt) {
1201
-            $incoming_date_formats = array('Y-m-d', 'h:i a');
1202
-            $update_prices = false;
1203
-            $ticket_price = isset($data['edit_prices'][$row][1]['PRC_amount'])
1204
-                ? $data['edit_prices'][$row][1]['PRC_amount'] : 0;
1205
-            // trim inputs to ensure any excess whitespace is removed.
1206
-            $tkt = array_map('trim', $tkt);
1207
-            if (empty($tkt['TKT_start_date'])) {
1208
-                //let's use now in the set timezone.
1209
-                $now = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
1210
-                $tkt['TKT_start_date'] = $now->format($incoming_date_formats[0] . ' ' . $incoming_date_formats[1]);
1211
-            }
1212
-            if (empty($tkt['TKT_end_date'])) {
1213
-                //use the start date of the first datetime
1214
-                $dtt = $evtobj->first_datetime();
1215
-                $tkt['TKT_end_date'] = $dtt->start_date_and_time(
1216
-                    $incoming_date_formats[0],
1217
-                    $incoming_date_formats[1]
1218
-                );
1219
-            }
1220
-            $TKT_values = array(
1221
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
1222
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
1223
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
1224
-                'TKT_description' => ! empty($tkt['TKT_description']) ? $tkt['TKT_description'] : '',
1225
-                'TKT_start_date'  => $tkt['TKT_start_date'],
1226
-                'TKT_end_date'    => $tkt['TKT_end_date'],
1227
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
1228
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
1229
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
1230
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
1231
-                'TKT_row'         => $row,
1232
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : $row,
1233
-                'TKT_price'       => $ticket_price,
1234
-            );
1235
-            //if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
1236
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
1237
-                $TKT_values['TKT_ID'] = 0;
1238
-                $TKT_values['TKT_is_default'] = 0;
1239
-                $TKT_values['TKT_price'] = $ticket_price;
1240
-                $update_prices = true;
1241
-            }
1242
-            //if we have a TKT_ID then we need to get that existing TKT_obj and update it
1243
-            //we actually do our saves a head of doing any add_relations to because its entirely possible that this ticket didn't removed or added to any datetime in the session but DID have it's items modified.
1244
-            //keep in mind that if the TKT has been sold (and we have changed pricing information), then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1245
-            if ( ! empty($tkt['TKT_ID'])) {
1246
-                $TKT = EE_Registry::instance()
1247
-                                  ->load_model('Ticket', array($evtobj->get_timezone()))
1248
-                                  ->get_one_by_ID($tkt['TKT_ID']);
1249
-                if ($TKT instanceof EE_Ticket) {
1250
-                    $ticket_sold = $TKT->count_related(
1251
-                        'Registration',
1252
-                        array(
1253
-                            array(
1254
-                                'STS_ID' => array(
1255
-                                    'NOT IN',
1256
-                                    array(EEM_Registration::status_id_incomplete),
1257
-                                ),
1258
-                            ),
1259
-                        )
1260
-                    ) > 0 ? true : false;
1261
-                    //let's just check the total price for the existing ticket and determine if it matches the new total price.  if they are different then we create a new ticket (if tkts sold) if they aren't different then we go ahead and modify existing ticket.
1262
-                    $create_new_TKT = $ticket_sold && $ticket_price != $TKT->get('TKT_price')
1263
-                                      && ! $TKT->get(
1264
-                        'TKT_deleted'
1265
-                    ) ? true : false;
1266
-                    $TKT->set_date_format($incoming_date_formats[0]);
1267
-                    $TKT->set_time_format($incoming_date_formats[1]);
1268
-                    //set new values
1269
-                    foreach ($TKT_values as $field => $value) {
1270
-                        if ($field == 'TKT_qty') {
1271
-                            $TKT->set_qty($value);
1272
-                        } else {
1273
-                            $TKT->set($field, $value);
1274
-                        }
1275
-                    }
1276
-                    //if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
1277
-                    if ($create_new_TKT) {
1278
-                        //archive the old ticket first
1279
-                        $TKT->set('TKT_deleted', 1);
1280
-                        $TKT->save();
1281
-                        //make sure this ticket is still recorded in our saved_tkts so we don't run it through the regular trash routine.
1282
-                        $saved_tickets[$TKT->ID()] = $TKT;
1283
-                        //create new ticket that's a copy of the existing except a new id of course (and not archived) AND has the new TKT_price associated with it.
1284
-                        $TKT = clone $TKT;
1285
-                        $TKT->set('TKT_ID', 0);
1286
-                        $TKT->set('TKT_deleted', 0);
1287
-                        $TKT->set('TKT_price', $ticket_price);
1288
-                        $TKT->set('TKT_sold', 0);
1289
-                        //now we need to make sure that $new prices are created as well and attached to new ticket.
1290
-                        $update_prices = true;
1291
-                    }
1292
-                    //make sure price is set if it hasn't been already
1293
-                    $TKT->set('TKT_price', $ticket_price);
1294
-                }
1295
-            } else {
1296
-                //no TKT_id so a new TKT
1297
-                $TKT_values['TKT_price'] = $ticket_price;
1298
-                $TKT = EE_Registry::instance()->load_class('Ticket', array($TKT_values), false, false);
1299
-                if ($TKT instanceof EE_Ticket) {
1300
-                    //need to reset values to properly account for the date formats
1301
-                    $TKT->set_date_format($incoming_date_formats[0]);
1302
-                    $TKT->set_time_format($incoming_date_formats[1]);
1303
-                    $TKT->set_timezone($evtobj->get_timezone());
1304
-                    //set new values
1305
-                    foreach ($TKT_values as $field => $value) {
1306
-                        if ($field == 'TKT_qty') {
1307
-                            $TKT->set_qty($value);
1308
-                        } else {
1309
-                            $TKT->set($field, $value);
1310
-                        }
1311
-                    }
1312
-                    $update_prices = true;
1313
-                }
1314
-            }
1315
-            // cap ticket qty by datetime reg limits
1316
-            $TKT->set_qty(min($TKT->qty(), $TKT->qty('reg_limit')));
1317
-            //update ticket.
1318
-            $TKT->save();
1319
-            //before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1320
-            if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
1321
-                $TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
1322
-                $TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
1323
-                $TKT->save();
1324
-            }
1325
-            //initially let's add the ticket to the dtt
1326
-            $saved_dtt->_add_relation_to($TKT, 'Ticket');
1327
-            $saved_tickets[$TKT->ID()] = $TKT;
1328
-            //add prices to ticket
1329
-            $this->_add_prices_to_ticket($data['edit_prices'][$row], $TKT, $update_prices);
1330
-        }
1331
-        //however now we need to handle permanently deleting tickets via the ui.  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.  However, it does allow for deleting tickets that have no tickets sold, in which case we want to get rid of permanently because there is no need to save in db.
1332
-        $old_tickets = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
1333
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1334
-        foreach ($tickets_removed as $id) {
1335
-            $id = absint($id);
1336
-            //get the ticket for this id
1337
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
1338
-            //need to get all the related datetimes on this ticket and remove from every single one of them (remember this process can ONLY kick off if there are NO tkts_sold)
1339
-            $dtts = $tkt_to_remove->get_many_related('Datetime');
1340
-            foreach ($dtts as $dtt) {
1341
-                $tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
1342
-            }
1343
-            //need to do the same for prices (except these prices can also be deleted because again, tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1344
-            $tkt_to_remove->delete_related_permanently('Price');
1345
-            //finally let's delete this ticket (which should not be blocked at this point b/c we've removed all our relationships)
1346
-            $tkt_to_remove->delete_permanently();
1347
-        }
1348
-        return array($saved_dtt, $saved_tickets);
1349
-    }
1350
-
1351
-
1352
-
1353
-    /**
1354
-     * This attaches a list of given prices to a ticket.
1355
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1356
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1357
-     * price info and prices are automatically "archived" via the ticket.
1358
-     *
1359
-     * @access  private
1360
-     * @param array     $prices     Array of prices from the form.
1361
-     * @param EE_Ticket $ticket     EE_Ticket object that prices are being attached to.
1362
-     * @param bool      $new_prices Whether attach existing incoming prices or create new ones.
1363
-     * @return  void
1364
-     */
1365
-    private function _add_prices_to_ticket($prices, EE_Ticket $ticket, $new_prices = false)
1366
-    {
1367
-        foreach ($prices as $row => $prc) {
1368
-            $PRC_values = array(
1369
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
1370
-                'PRT_ID'         => ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null,
1371
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
1372
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
1373
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
1374
-                'PRC_is_default' => 0, //make sure prices are NOT set as default from this context
1375
-                'PRC_order'      => $row,
1376
-            );
1377
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
1378
-                $PRC_values['PRC_ID'] = 0;
1379
-                $PRC = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
1380
-            } else {
1381
-                $PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
1382
-                //update this price with new values
1383
-                foreach ($PRC_values as $field => $newprc) {
1384
-                    $PRC->set($field, $newprc);
1385
-                }
1386
-                $PRC->save();
1387
-            }
1388
-            $ticket->_add_relation_to($PRC, 'Price');
1389
-        }
1390
-    }
1391
-
1392
-
1393
-
1394
-    /**
1395
-     * Add in our autosave ajax handlers
1396
-     *
1397
-     */
1398
-    protected function _ee_autosave_create_new()
1399
-    {
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * More autosave handlers.
1405
-     */
1406
-    protected function _ee_autosave_edit()
1407
-    {
1408
-        return; //TEMPORARILY EXITING CAUSE THIS IS A TODO
1409
-    }
1410
-
1411
-
1412
-
1413
-    /**
1414
-     *    _generate_publish_box_extra_content
1415
-     */
1416
-    private function _generate_publish_box_extra_content()
1417
-    {
1418
-        //load formatter helper
1419
-        //args for getting related registrations
1420
-        $approved_query_args = array(
1421
-            array(
1422
-                'REG_deleted' => 0,
1423
-                'STS_ID'      => EEM_Registration::status_id_approved,
1424
-            ),
1425
-        );
1426
-        $not_approved_query_args = array(
1427
-            array(
1428
-                'REG_deleted' => 0,
1429
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1430
-            ),
1431
-        );
1432
-        $pending_payment_query_args = array(
1433
-            array(
1434
-                'REG_deleted' => 0,
1435
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1436
-            ),
1437
-        );
1438
-        // publish box
1439
-        $publish_box_extra_args = array(
1440
-            'view_approved_reg_url'        => add_query_arg(
1441
-                array(
1442
-                    'action'      => 'default',
1443
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1444
-                    '_reg_status' => EEM_Registration::status_id_approved,
1445
-                ),
1446
-                REG_ADMIN_URL
1447
-            ),
1448
-            'view_not_approved_reg_url'    => add_query_arg(
1449
-                array(
1450
-                    'action'      => 'default',
1451
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1452
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1453
-                ),
1454
-                REG_ADMIN_URL
1455
-            ),
1456
-            'view_pending_payment_reg_url' => add_query_arg(
1457
-                array(
1458
-                    'action'      => 'default',
1459
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1460
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1461
-                ),
1462
-                REG_ADMIN_URL
1463
-            ),
1464
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1465
-                'Registration',
1466
-                $approved_query_args
1467
-            ),
1468
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1469
-                'Registration',
1470
-                $not_approved_query_args
1471
-            ),
1472
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1473
-                'Registration',
1474
-                $pending_payment_query_args
1475
-            ),
1476
-            'misc_pub_section_class'       => apply_filters(
1477
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1478
-                'misc-pub-section'
1479
-            ),
1480
-        );
1481
-        ob_start();
1482
-        do_action(
1483
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1484
-            $this->_cpt_model_obj
1485
-        );
1486
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1487
-        // load template
1488
-        EEH_Template::display_template(
1489
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1490
-            $publish_box_extra_args
1491
-        );
1492
-    }
1493
-
1494
-
1495
-
1496
-    /**
1497
-     * @return EE_Event
1498
-     */
1499
-    public function get_event_object()
1500
-    {
1501
-        return $this->_cpt_model_obj;
1502
-    }
1503
-
1504
-
1505
-
1506
-
1507
-    /** METABOXES * */
1508
-    /**
1509
-     * _register_event_editor_meta_boxes
1510
-     * add all metaboxes related to the event_editor
1511
-     *
1512
-     * @return void
1513
-     */
1514
-    protected function _register_event_editor_meta_boxes()
1515
-    {
1516
-        $this->verify_cpt_object();
1517
-        add_meta_box(
1518
-            'espresso_event_editor_tickets',
1519
-            esc_html__('Event Datetime & Ticket', 'event_espresso'),
1520
-            array($this, 'ticket_metabox'),
1521
-            $this->page_slug,
1522
-            'normal',
1523
-            'high'
1524
-        );
1525
-        add_meta_box(
1526
-            'espresso_event_editor_event_options',
1527
-            esc_html__('Event Registration Options', 'event_espresso'),
1528
-            array($this, 'registration_options_meta_box'),
1529
-            $this->page_slug,
1530
-            'side',
1531
-            'default'
1532
-        );
1533
-        // NOTE: if you're looking for other metaboxes in here,
1534
-        // where a metabox has a related management page in the admin
1535
-        // you will find it setup in the related management page's "_Hooks" file.
1536
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1537
-    }
1538
-
1539
-
1540
-    /**
1541
-     * @throws DomainException
1542
-     * @throws EE_Error
1543
-     */
1544
-    public function ticket_metabox()
1545
-    {
1546
-        $existing_datetime_ids = $existing_ticket_ids = array();
1547
-        //defaults for template args
1548
-        $template_args = array(
1549
-            'existing_datetime_ids'    => '',
1550
-            'event_datetime_help_link' => '',
1551
-            'ticket_options_help_link' => '',
1552
-            'time'                     => null,
1553
-            'ticket_rows'              => '',
1554
-            'existing_ticket_ids'      => '',
1555
-            'total_ticket_rows'        => 1,
1556
-            'ticket_js_structure'      => '',
1557
-            'trash_icon'               => 'ee-lock-icon',
1558
-            'disabled'                 => '',
1559
-        );
1560
-        $event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1561
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1562
-        /**
1563
-         * 1. Start with retrieving Datetimes
1564
-         * 2. Fore each datetime get related tickets
1565
-         * 3. For each ticket get related prices
1566
-         */
1567
-        $times = EE_Registry::instance()->load_model('Datetime')->get_all_event_dates($event_id);
1568
-        /** @type EE_Datetime $first_datetime */
1569
-        $first_datetime = reset($times);
1570
-        //do we get related tickets?
1571
-        if ($first_datetime instanceof EE_Datetime
1572
-            && $first_datetime->ID() !== 0
1573
-        ) {
1574
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1575
-            $template_args['time'] = $first_datetime;
1576
-            $related_tickets = $first_datetime->tickets(
1577
-                array(
1578
-                    array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
1579
-                    'default_where_conditions' => 'none',
1580
-                )
1581
-            );
1582
-            if ( ! empty($related_tickets)) {
1583
-                $template_args['total_ticket_rows'] = count($related_tickets);
1584
-                $row = 0;
1585
-                foreach ($related_tickets as $ticket) {
1586
-                    $existing_ticket_ids[] = $ticket->get('TKT_ID');
1587
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1588
-                    $row++;
1589
-                }
1590
-            } else {
1591
-                $template_args['total_ticket_rows'] = 1;
1592
-                /** @type EE_Ticket $ticket */
1593
-                $ticket = EE_Registry::instance()->load_model('Ticket')->create_default_object();
1594
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1595
-            }
1596
-        } else {
1597
-            $template_args['time'] = $times[0];
1598
-            /** @type EE_Ticket $ticket */
1599
-            $ticket = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
1600
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket[1]);
1601
-            // NOTE: we're just sending the first default row
1602
-            // (decaf can't manage default tickets so this should be sufficient);
1603
-        }
1604
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1605
-            'event_editor_event_datetimes_help_tab'
1606
-        );
1607
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1608
-        $template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1609
-        $template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1610
-        $template_args['ticket_js_structure'] = $this->_get_ticket_row(
1611
-            EE_Registry::instance()->load_model('Ticket')->create_default_object(),
1612
-            true
1613
-        );
1614
-        $template = apply_filters(
1615
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1616
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1617
-        );
1618
-        EEH_Template::display_template($template, $template_args);
1619
-    }
1620
-
1621
-
1622
-
1623
-    /**
1624
-     * Setup an individual ticket form for the decaf event editor page
1625
-     *
1626
-     * @access private
1627
-     * @param  EE_Ticket $ticket   the ticket object
1628
-     * @param  boolean   $skeleton whether we're generating a skeleton for js manipulation
1629
-     * @param int        $row
1630
-     * @return string generated html for the ticket row.
1631
-     */
1632
-    private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1633
-    {
1634
-        $template_args = array(
1635
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1636
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1637
-                : '',
1638
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1639
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1640
-            'TKT_name'            => $ticket->get('TKT_name'),
1641
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1642
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1643
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1644
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1645
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1646
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1647
-            'trash_icon'          => ($skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')))
1648
-                                     && ( ! empty($ticket) && $ticket->get('TKT_sold') === 0)
1649
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1650
-            'disabled'            => $skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1651
-                : ' disabled=disabled',
1652
-        );
1653
-        $price = $ticket->ID() !== 0
1654
-            ? $ticket->get_first_related('Price', array('default_where_conditions' => 'none'))
1655
-            : EE_Registry::instance()->load_model('Price')->create_default_object();
1656
-        $price_args = array(
1657
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1658
-            'PRC_amount'            => $price->get('PRC_amount'),
1659
-            'PRT_ID'                => $price->get('PRT_ID'),
1660
-            'PRC_ID'                => $price->get('PRC_ID'),
1661
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1662
-        );
1663
-        //make sure we have default start and end dates if skeleton
1664
-        //handle rows that should NOT be empty
1665
-        if (empty($template_args['TKT_start_date'])) {
1666
-            //if empty then the start date will be now.
1667
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1668
-        }
1669
-        if (empty($template_args['TKT_end_date'])) {
1670
-            //get the earliest datetime (if present);
1671
-            $earliest_dtt = $this->_cpt_model_obj->ID() > 0
1672
-                ? $this->_cpt_model_obj->get_first_related(
1673
-                    'Datetime',
1674
-                    array('order_by' => array('DTT_EVT_start' => 'ASC'))
1675
-                )
1676
-                : null;
1677
-            if ( ! empty($earliest_dtt)) {
1678
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a');
1679
-            } else {
1680
-                $template_args['TKT_end_date'] = date(
1681
-                    'Y-m-d h:i a',
1682
-                    mktime(0, 0, 0, date("m"), date("d") + 7, date("Y"))
1683
-                );
1684
-            }
1685
-        }
1686
-        $template_args = array_merge($template_args, $price_args);
1687
-        $template = apply_filters(
1688
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1689
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1690
-            $ticket
1691
-        );
1692
-        return EEH_Template::display_template($template, $template_args, true);
1693
-    }
1694
-
1695
-
1696
-    /**
1697
-     * @throws DomainException
1698
-     */
1699
-    public function registration_options_meta_box()
1700
-    {
1701
-        $yes_no_values = array(
1702
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
1703
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
1704
-        );
1705
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1706
-            array(
1707
-                EEM_Registration::status_id_cancelled,
1708
-                EEM_Registration::status_id_declined,
1709
-                EEM_Registration::status_id_incomplete,
1710
-            ),
1711
-            true
1712
-        );
1713
-        //$template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1714
-        $template_args['_event'] = $this->_cpt_model_obj;
1715
-        $template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1716
-        $template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1717
-        $template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1718
-            'default_reg_status',
1719
-            $default_reg_status_values,
1720
-            $this->_cpt_model_obj->default_registration_status()
1721
-        );
1722
-        $template_args['display_description'] = EEH_Form_Fields::select_input(
1723
-            'display_desc',
1724
-            $yes_no_values,
1725
-            $this->_cpt_model_obj->display_description()
1726
-        );
1727
-        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1728
-            'display_ticket_selector',
1729
-            $yes_no_values,
1730
-            $this->_cpt_model_obj->display_ticket_selector(),
1731
-            '',
1732
-            '',
1733
-            false
1734
-        );
1735
-        $template_args['additional_registration_options'] = apply_filters(
1736
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1737
-            '',
1738
-            $template_args,
1739
-            $yes_no_values,
1740
-            $default_reg_status_values
1741
-        );
1742
-        EEH_Template::display_template(
1743
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1744
-            $template_args
1745
-        );
1746
-    }
1747
-
1748
-
1749
-
1750
-    /**
1751
-     * _get_events()
1752
-     * This method simply returns all the events (for the given _view and paging)
1753
-     *
1754
-     * @access public
1755
-     * @param int  $per_page     count of items per page (20 default);
1756
-     * @param int  $current_page what is the current page being viewed.
1757
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1758
-     *                           If FALSE then we return an array of event objects
1759
-     *                           that match the given _view and paging parameters.
1760
-     * @return array an array of event objects.
1761
-     */
1762
-    public function get_events($per_page = 10, $current_page = 1, $count = false)
1763
-    {
1764
-        $EEME = $this->_event_model();
1765
-        $offset = ($current_page - 1) * $per_page;
1766
-        $limit = $count ? null : $offset . ',' . $per_page;
1767
-        $orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'EVT_ID';
1768
-        $order = isset($this->_req_data['order']) ? $this->_req_data['order'] : "DESC";
1769
-        if (isset($this->_req_data['month_range'])) {
1770
-            $pieces = explode(' ', $this->_req_data['month_range'], 3);
1771
-            //simulate the FIRST day of the month, that fixes issues for months like February
1772
-            //where PHP doesn't know what to assume for date.
1773
-            //@see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1774
-            $month_r = ! empty($pieces[0]) ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1775
-            $year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1776
-        }
1777
-        $where = array();
1778
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1779
-        //determine what post_status our condition will have for the query.
1780
-        switch ($status) {
1781
-            case 'month' :
1782
-            case 'today' :
1783
-            case null :
1784
-            case 'all' :
1785
-                break;
1786
-            case 'draft' :
1787
-                $where['status'] = array('IN', array('draft', 'auto-draft'));
1788
-                break;
1789
-            default :
1790
-                $where['status'] = $status;
1791
-        }
1792
-        //categories?
1793
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1794
-            ? $this->_req_data['EVT_CAT'] : null;
1795
-        if ( ! empty ($category)) {
1796
-            $where['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1797
-            $where['Term_Taxonomy.term_id'] = $category;
1798
-        }
1799
-        //date where conditions
1800
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1801
-        if (isset($this->_req_data['month_range']) && $this->_req_data['month_range'] != '') {
1802
-            $DateTime = new DateTime(
1803
-                $year_r . '-' . $month_r . '-01 00:00:00',
1804
-                new DateTimeZone(EEM_Datetime::instance()->get_timezone())
1805
-            );
1806
-            $start = $DateTime->format(implode(' ', $start_formats));
1807
-            $end = $DateTime->setDate($year_r, $month_r, $DateTime
1808
-                ->format('t'))->setTime(23, 59, 59)
1809
-                            ->format(implode(' ', $start_formats));
1810
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1811
-        } else if (isset($this->_req_data['status']) && $this->_req_data['status'] == 'today') {
1812
-            $DateTime = new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1813
-            $start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1814
-            $end = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1815
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1816
-        } else if (isset($this->_req_data['status']) && $this->_req_data['status'] == 'month') {
1817
-            $now = date('Y-m-01');
1818
-            $DateTime = new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1819
-            $start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1820
-            $end = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1821
-                            ->setTime(23, 59, 59)
1822
-                            ->format(implode(' ', $start_formats));
1823
-            $where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1824
-        }
1825
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1826
-            $where['EVT_wp_user'] = get_current_user_id();
1827
-        } else {
1828
-            if ( ! isset($where['status'])) {
1829
-                if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1830
-                    $where['OR'] = array(
1831
-                        'status*restrict_private' => array('!=', 'private'),
1832
-                        'AND'                     => array(
1833
-                            'status*inclusive' => array('=', 'private'),
1834
-                            'EVT_wp_user'      => get_current_user_id(),
1835
-                        ),
1836
-                    );
1837
-                }
1838
-            }
1839
-        }
1840
-        if (isset($this->_req_data['EVT_wp_user'])) {
1841
-            if ($this->_req_data['EVT_wp_user'] != get_current_user_id()
1842
-                && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1843
-            ) {
1844
-                $where['EVT_wp_user'] = $this->_req_data['EVT_wp_user'];
1845
-            }
1846
-        }
1847
-        //search query handling
1848
-        if (isset($this->_req_data['s'])) {
1849
-            $search_string = '%' . $this->_req_data['s'] . '%';
1850
-            $where['OR'] = array(
1851
-                'EVT_name'       => array('LIKE', $search_string),
1852
-                'EVT_desc'       => array('LIKE', $search_string),
1853
-                'EVT_short_desc' => array('LIKE', $search_string),
1854
-            );
1855
-        }
1856
-        $where = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $this->_req_data);
1857
-        $query_params = apply_filters(
1858
-            'FHEE__Events_Admin_Page__get_events__query_params',
1859
-            array(
1860
-                $where,
1861
-                'limit'    => $limit,
1862
-                'order_by' => $orderby,
1863
-                'order'    => $order,
1864
-                'group_by' => 'EVT_ID',
1865
-            ),
1866
-            $this->_req_data
1867
-        );
1868
-        //let's first check if we have special requests coming in.
1869
-        if (isset($this->_req_data['active_status'])) {
1870
-            switch ($this->_req_data['active_status']) {
1871
-                case 'upcoming' :
1872
-                    return $EEME->get_upcoming_events($query_params, $count);
1873
-                    break;
1874
-                case 'expired' :
1875
-                    return $EEME->get_expired_events($query_params, $count);
1876
-                    break;
1877
-                case 'active' :
1878
-                    return $EEME->get_active_events($query_params, $count);
1879
-                    break;
1880
-                case 'inactive' :
1881
-                    return $EEME->get_inactive_events($query_params, $count);
1882
-                    break;
1883
-            }
1884
-        }
1885
-        $events = $count ? $EEME->count(array($where), 'EVT_ID', true) : $EEME->get_all($query_params);
1886
-        return $events;
1887
-    }
1888
-
1889
-
1890
-
1891
-    /**
1892
-     * handling for WordPress CPT actions (trash, restore, delete)
1893
-     *
1894
-     * @param string $post_id
1895
-     */
1896
-    public function trash_cpt_item($post_id)
1897
-    {
1898
-        $this->_req_data['EVT_ID'] = $post_id;
1899
-        $this->_trash_or_restore_event('trash', false);
1900
-    }
1901
-
1902
-
1903
-
1904
-    /**
1905
-     * @param string $post_id
1906
-     */
1907
-    public function restore_cpt_item($post_id)
1908
-    {
1909
-        $this->_req_data['EVT_ID'] = $post_id;
1910
-        $this->_trash_or_restore_event('draft', false);
1911
-    }
1912
-
1913
-
1914
-
1915
-    /**
1916
-     * @param string $post_id
1917
-     */
1918
-    public function delete_cpt_item($post_id)
1919
-    {
1920
-        $this->_req_data['EVT_ID'] = $post_id;
1921
-        $this->_delete_event(false);
1922
-    }
1923
-
1924
-
1925
-
1926
-    /**
1927
-     * _trash_or_restore_event
1928
-     *
1929
-     * @access protected
1930
-     * @param  string $event_status
1931
-     * @param bool    $redirect_after
1932
-     */
1933
-    protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
1934
-    {
1935
-        //determine the event id and set to array.
1936
-        $EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : false;
1937
-        // loop thru events
1938
-        if ($EVT_ID) {
1939
-            // clean status
1940
-            $event_status = sanitize_key($event_status);
1941
-            // grab status
1942
-            if ( ! empty($event_status)) {
1943
-                $success = $this->_change_event_status($EVT_ID, $event_status);
1944
-            } else {
1945
-                $success = false;
1946
-                $msg = esc_html__(
1947
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
1948
-                    'event_espresso'
1949
-                );
1950
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1951
-            }
1952
-        } else {
1953
-            $success = false;
1954
-            $msg = esc_html__(
1955
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
1956
-                'event_espresso'
1957
-            );
1958
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1959
-        }
1960
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
1961
-        if ($redirect_after) {
1962
-            $this->_redirect_after_action($success, 'Event', $action, array('action' => 'default'));
1963
-        }
1964
-    }
1965
-
1966
-
1967
-
1968
-    /**
1969
-     * _trash_or_restore_events
1970
-     *
1971
-     * @access protected
1972
-     * @param  string $event_status
1973
-     * @return void
1974
-     */
1975
-    protected function _trash_or_restore_events($event_status = 'trash')
1976
-    {
1977
-        // clean status
1978
-        $event_status = sanitize_key($event_status);
1979
-        // grab status
1980
-        if ( ! empty($event_status)) {
1981
-            $success = true;
1982
-            //determine the event id and set to array.
1983
-            $EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array)$this->_req_data['EVT_IDs'] : array();
1984
-            // loop thru events
1985
-            foreach ($EVT_IDs as $EVT_ID) {
1986
-                if ($EVT_ID = absint($EVT_ID)) {
1987
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
1988
-                    $success = $results !== false ? $success : false;
1989
-                } else {
1990
-                    $msg = sprintf(
1991
-                        esc_html__(
1992
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
1993
-                            'event_espresso'
1994
-                        ),
1995
-                        $EVT_ID
1996
-                    );
1997
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1998
-                    $success = false;
1999
-                }
2000
-            }
2001
-        } else {
2002
-            $success = false;
2003
-            $msg = esc_html__(
2004
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2005
-                'event_espresso'
2006
-            );
2007
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2008
-        }
2009
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2010
-        $success = $success ? 2 : false;
2011
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2012
-        $this->_redirect_after_action($success, 'Events', $action, array('action' => 'default'));
2013
-    }
2014
-
2015
-
2016
-
2017
-    /**
2018
-     * _trash_or_restore_events
2019
-     *
2020
-     * @access  private
2021
-     * @param  int    $EVT_ID
2022
-     * @param  string $event_status
2023
-     * @return bool
2024
-     */
2025
-    private function _change_event_status($EVT_ID = 0, $event_status = '')
2026
-    {
2027
-        // grab event id
2028
-        if ( ! $EVT_ID) {
2029
-            $msg = esc_html__(
2030
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2031
-                'event_espresso'
2032
-            );
2033
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2034
-            return false;
2035
-        }
2036
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2037
-        // clean status
2038
-        $event_status = sanitize_key($event_status);
2039
-        // grab status
2040
-        if (empty($event_status)) {
2041
-            $msg = esc_html__(
2042
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2043
-                'event_espresso'
2044
-            );
2045
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2046
-            return false;
2047
-        }
2048
-        // was event trashed or restored ?
2049
-        switch ($event_status) {
2050
-            case 'draft' :
2051
-                $action = 'restored from the trash';
2052
-                $hook = 'AHEE_event_restored_from_trash';
2053
-                break;
2054
-            case 'trash' :
2055
-                $action = 'moved to the trash';
2056
-                $hook = 'AHEE_event_moved_to_trash';
2057
-                break;
2058
-            default :
2059
-                $action = 'updated';
2060
-                $hook = false;
2061
-        }
2062
-        //use class to change status
2063
-        $this->_cpt_model_obj->set_status($event_status);
2064
-        $success = $this->_cpt_model_obj->save();
2065
-        if ($success === false) {
2066
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2067
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2068
-            return false;
2069
-        }
2070
-        if ($hook) {
2071
-            do_action($hook);
2072
-        }
2073
-        return true;
2074
-    }
2075
-
2076
-
2077
-
2078
-    /**
2079
-     * _delete_event
2080
-     *
2081
-     * @access protected
2082
-     * @param bool $redirect_after
2083
-     */
2084
-    protected function _delete_event($redirect_after = true)
2085
-    {
2086
-        //determine the event id and set to array.
2087
-        $EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : null;
2088
-        $EVT_ID = isset($this->_req_data['post']) ? absint($this->_req_data['post']) : $EVT_ID;
2089
-        // loop thru events
2090
-        if ($EVT_ID) {
2091
-            $success = $this->_permanently_delete_event($EVT_ID);
2092
-            // get list of events with no prices
2093
-            $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', array());
2094
-            // remove this event from the list of events with no prices
2095
-            if (isset($espresso_no_ticket_prices[$EVT_ID])) {
2096
-                unset($espresso_no_ticket_prices[$EVT_ID]);
2097
-            }
2098
-            update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
2099
-        } else {
2100
-            $success = false;
2101
-            $msg = esc_html__(
2102
-                'An error occurred. An event could not be deleted because a valid event ID was not not supplied.',
2103
-                'event_espresso'
2104
-            );
2105
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2106
-        }
2107
-        if ($redirect_after) {
2108
-            $this->_redirect_after_action(
2109
-                $success,
2110
-                'Event',
2111
-                'deleted',
2112
-                array('action' => 'default', 'status' => 'trash')
2113
-            );
2114
-        }
2115
-    }
2116
-
2117
-
2118
-
2119
-    /**
2120
-     * _delete_events
2121
-     *
2122
-     * @access protected
2123
-     * @return void
2124
-     */
2125
-    protected function _delete_events()
2126
-    {
2127
-        $success = true;
2128
-        // get list of events with no prices
2129
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', array());
2130
-        //determine the event id and set to array.
2131
-        $EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array)$this->_req_data['EVT_IDs'] : array();
2132
-        // loop thru events
2133
-        foreach ($EVT_IDs as $EVT_ID) {
2134
-            $EVT_ID = absint($EVT_ID);
2135
-            if ($EVT_ID) {
2136
-                $results = $this->_permanently_delete_event($EVT_ID);
2137
-                $success = $results !== false ? $success : false;
2138
-                // remove this event from the list of events with no prices
2139
-                unset($espresso_no_ticket_prices[$EVT_ID]);
2140
-            } else {
2141
-                $success = false;
2142
-                $msg = esc_html__(
2143
-                    'An error occurred. An event could not be deleted because a valid event ID was not not supplied.',
2144
-                    'event_espresso'
2145
-                );
2146
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2147
-            }
2148
-        }
2149
-        update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
2150
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2151
-        $success = $success ? 2 : false;
2152
-        $this->_redirect_after_action($success, 'Events', 'deleted', array('action' => 'default'));
2153
-    }
2154
-
2155
-
2156
-
2157
-    /**
2158
-     * _permanently_delete_event
2159
-     *
2160
-     * @access  private
2161
-     * @param  int $EVT_ID
2162
-     * @return bool
2163
-     */
2164
-    private function _permanently_delete_event($EVT_ID = 0)
2165
-    {
2166
-        // grab event id
2167
-        if ( ! $EVT_ID) {
2168
-            $msg = esc_html__(
2169
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2170
-                'event_espresso'
2171
-            );
2172
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2173
-            return false;
2174
-        }
2175
-        if (
2176
-            ! $this->_cpt_model_obj instanceof EE_Event
2177
-            || $this->_cpt_model_obj->ID() !== $EVT_ID
2178
-        ) {
2179
-            $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2180
-        }
2181
-        if ( ! $this->_cpt_model_obj instanceof EE_Event) {
2182
-            return false;
2183
-        }
2184
-        //need to delete related tickets and prices first.
2185
-        $datetimes = $this->_cpt_model_obj->get_many_related('Datetime');
2186
-        foreach ($datetimes as $datetime) {
2187
-            $this->_cpt_model_obj->_remove_relation_to($datetime, 'Datetime');
2188
-            $tickets = $datetime->get_many_related('Ticket');
2189
-            foreach ($tickets as $ticket) {
2190
-                $ticket->_remove_relation_to($datetime, 'Datetime');
2191
-                $ticket->delete_related_permanently('Price');
2192
-                $ticket->delete_permanently();
2193
-            }
2194
-            $datetime->delete();
2195
-        }
2196
-        //what about related venues or terms?
2197
-        $venues = $this->_cpt_model_obj->get_many_related('Venue');
2198
-        foreach ($venues as $venue) {
2199
-            $this->_cpt_model_obj->_remove_relation_to($venue, 'Venue');
2200
-        }
2201
-        //any attached question groups?
2202
-        $question_groups = $this->_cpt_model_obj->get_many_related('Question_Group');
2203
-        if ( ! empty($question_groups)) {
2204
-            foreach ($question_groups as $question_group) {
2205
-                $this->_cpt_model_obj->_remove_relation_to($question_group, 'Question_Group');
2206
-            }
2207
-        }
2208
-        //Message Template Groups
2209
-        $this->_cpt_model_obj->_remove_relations('Message_Template_Group');
2210
-        /** @type EE_Term_Taxonomy[] $term_taxonomies */
2211
-        $term_taxonomies = $this->_cpt_model_obj->term_taxonomies();
2212
-        foreach ($term_taxonomies as $term_taxonomy) {
2213
-            $this->_cpt_model_obj->remove_relation_to_term_taxonomy($term_taxonomy);
2214
-        }
2215
-        $success = $this->_cpt_model_obj->delete_permanently();
2216
-        // did it all go as planned ?
2217
-        if ($success) {
2218
-            $msg = sprintf(esc_html__('Event ID # %d has been deleted.', 'event_espresso'), $EVT_ID);
2219
-            EE_Error::add_success($msg);
2220
-        } else {
2221
-            $msg = sprintf(
2222
-                esc_html__('An error occurred. Event ID # %d could not be deleted.', 'event_espresso'),
2223
-                $EVT_ID
2224
-            );
2225
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2226
-            return false;
2227
-        }
2228
-        do_action('AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted', $EVT_ID);
2229
-        return true;
2230
-    }
2231
-
2232
-
2233
-
2234
-    /**
2235
-     * get total number of events
2236
-     *
2237
-     * @access public
2238
-     * @return int
2239
-     */
2240
-    public function total_events()
2241
-    {
2242
-        $count = EEM_Event::instance()->count(array('caps' => 'read_admin'), 'EVT_ID', true);
2243
-        return $count;
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * get total number of draft events
2250
-     *
2251
-     * @access public
2252
-     * @return int
2253
-     */
2254
-    public function total_events_draft()
2255
-    {
2256
-        $where = array(
2257
-            'status' => array('IN', array('draft', 'auto-draft')),
2258
-        );
2259
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2260
-        return $count;
2261
-    }
2262
-
2263
-
2264
-
2265
-    /**
2266
-     * get total number of trashed events
2267
-     *
2268
-     * @access public
2269
-     * @return int
2270
-     */
2271
-    public function total_trashed_events()
2272
-    {
2273
-        $where = array(
2274
-            'status' => 'trash',
2275
-        );
2276
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2277
-        return $count;
2278
-    }
2279
-
2280
-
2281
-    /**
2282
-     *    _default_event_settings
2283
-     *    This generates the Default Settings Tab
2284
-     *
2285
-     * @return void
2286
-     * @throws EE_Error
2287
-     */
2288
-    protected function _default_event_settings()
2289
-    {
2290
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2291
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
2292
-        $this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2293
-        $this->display_admin_page_with_sidebar();
2294
-    }
2295
-
2296
-
2297
-    /**
2298
-     * Return the form for event settings.
2299
-     * @return EE_Form_Section_Proper
2300
-     */
2301
-    protected function _default_event_settings_form()
2302
-    {
2303
-        $registration_config = EE_Registry::instance()->CFG->registration;
2304
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2305
-        //exclude
2306
-            array(
2307
-                EEM_Registration::status_id_cancelled,
2308
-                EEM_Registration::status_id_declined,
2309
-                EEM_Registration::status_id_incomplete,
2310
-                EEM_Registration::status_id_wait_list,
2311
-            ),
2312
-            true
2313
-        );
2314
-        return new EE_Form_Section_Proper(
2315
-            array(
2316
-                'name' => 'update_default_event_settings',
2317
-                'html_id' => 'update_default_event_settings',
2318
-                'html_class' => 'form-table',
2319
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2320
-                'subsections' => apply_filters(
2321
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2322
-                    array(
2323
-                        'default_reg_status' => new EE_Select_Input(
2324
-                            $registration_stati_for_selection,
2325
-                            array(
2326
-                                'default' => isset($registration_config->default_STS_ID)
2327
-                                             && array_key_exists(
2328
-                                                $registration_config->default_STS_ID,
2329
-                                                $registration_stati_for_selection
2330
-                                             )
2331
-                                            ? sanitize_text_field($registration_config->default_STS_ID)
2332
-                                            : EEM_Registration::status_id_pending_payment,
2333
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2334
-                                                    . EEH_Template::get_help_tab_link(
2335
-                                                        'default_settings_status_help_tab'
2336
-                                                    ),
2337
-                                'html_help_text' => esc_html__(
2338
-                                    '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.',
2339
-                                    'event_espresso'
2340
-                                )
2341
-                            )
2342
-                        ),
2343
-                        'default_max_tickets' => new EE_Integer_Input(
2344
-                            array(
2345
-                                'default' => isset($registration_config->default_maximum_number_of_tickets)
2346
-                                    ? $registration_config->default_maximum_number_of_tickets
2347
-                                    : EEM_Event::get_default_additional_limit(),
2348
-                                'html_label_text' => esc_html__(
2349
-                                    'Default Maximum Tickets Allowed Per Order:',
2350
-                                    'event_espresso'
2351
-                                ) . EEH_Template::get_help_tab_link(
2352
-                                    'default_maximum_tickets_help_tab"'
2353
-                                    ),
2354
-                                'html_help_text' => esc_html__(
2355
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2356
-                                    'event_espresso'
2357
-                                )
2358
-                            )
2359
-                        )
2360
-                    )
2361
-                )
2362
-            )
2363
-        );
2364
-    }
2365
-
2366
-
2367
-    /**
2368
-     * _update_default_event_settings
2369
-     *
2370
-     * @access protected
2371
-     * @return void
2372
-     * @throws EE_Error
2373
-     */
2374
-    protected function _update_default_event_settings()
2375
-    {
2376
-        $registration_config = EE_Registry::instance()->CFG->registration;
2377
-        $form = $this->_default_event_settings_form();
2378
-        if ($form->was_submitted()) {
2379
-            $form->receive_form_submission();
2380
-            if ($form->is_valid()) {
2381
-                $valid_data = $form->valid_data();
2382
-                if (isset($valid_data['default_reg_status'])) {
2383
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2384
-                }
2385
-                if (isset($valid_data['default_max_tickets'])) {
2386
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2387
-                }
2388
-                //update because data was valid!
2389
-                EE_Registry::instance()->CFG->update_espresso_config();
2390
-                EE_Error::overwrite_success();
2391
-                EE_Error::add_success(
2392
-                    __('Default Event Settings were updated', 'event_espresso')
2393
-                );
2394
-            }
2395
-        }
2396
-        $this->_redirect_after_action(0, '', '', array('action' => 'default_event_settings'), true);
2397
-    }
2398
-
2399
-
2400
-
2401
-    /*************        Templates        *************/
2402
-    protected function _template_settings()
2403
-    {
2404
-        $this->_admin_page_title = esc_html__('Template Settings (Preview)', 'event_espresso');
2405
-        $this->_template_args['preview_img'] = '<img src="'
2406
-                                               . EVENTS_ASSETS_URL
2407
-                                               . DS
2408
-                                               . 'images'
2409
-                                               . DS
2410
-                                               . 'caffeinated_template_features.jpg" alt="'
2411
-                                               . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2412
-                                               . '" />';
2413
-        $this->_template_args['preview_text'] = '<strong>' . esc_html__(
2414
-                '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.',
2415
-                'event_espresso'
2416
-            ) . '</strong>';
2417
-        $this->display_admin_caf_preview_page('template_settings_tab');
2418
-    }
2419
-
2420
-
2421
-    /** Event Category Stuff **/
2422
-    /**
2423
-     * set the _category property with the category object for the loaded page.
2424
-     *
2425
-     * @access private
2426
-     * @return void
2427
-     */
2428
-    private function _set_category_object()
2429
-    {
2430
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2431
-            return;
2432
-        } //already have the category object so get out.
2433
-        //set default category object
2434
-        $this->_set_empty_category_object();
2435
-        //only set if we've got an id
2436
-        if ( ! isset($this->_req_data['EVT_CAT_ID'])) {
2437
-            return;
2438
-        }
2439
-        $category_id = absint($this->_req_data['EVT_CAT_ID']);
2440
-        $term = get_term($category_id, 'espresso_event_categories');
2441
-        if ( ! empty($term)) {
2442
-            $this->_category->category_name = $term->name;
2443
-            $this->_category->category_identifier = $term->slug;
2444
-            $this->_category->category_desc = $term->description;
2445
-            $this->_category->id = $term->term_id;
2446
-            $this->_category->parent = $term->parent;
2447
-        }
2448
-    }
2449
-
2450
-
2451
-    /**
2452
-     * Clears out category properties.
2453
-     */
2454
-    private function _set_empty_category_object()
2455
-    {
2456
-        $this->_category = new stdClass();
2457
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2458
-        $this->_category->id = $this->_category->parent = 0;
2459
-    }
2460
-
2461
-
2462
-    /**
2463
-     * @throws EE_Error
2464
-     */
2465
-    protected function _category_list_table()
2466
-    {
2467
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2468
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2469
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2470
-                'add_category',
2471
-                'add_category',
2472
-                array(),
2473
-                'add-new-h2'
2474
-            );
2475
-        $this->display_admin_list_table_page_with_sidebar();
2476
-    }
2477
-
2478
-
2479
-
2480
-    /**
2481
-     * Output category details view.
2482
-     */
2483
-    protected function _category_details($view)
2484
-    {
2485
-        //load formatter helper
2486
-        //load field generator helper
2487
-        $route = $view == 'edit' ? 'update_category' : 'insert_category';
2488
-        $this->_set_add_edit_form_tags($route);
2489
-        $this->_set_category_object();
2490
-        $id = ! empty($this->_category->id) ? $this->_category->id : '';
2491
-        $delete_action = 'delete_category';
2492
-        //custom redirect
2493
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2494
-            array('action' => 'category_list'),
2495
-            $this->_admin_base_url
2496
-        );
2497
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2498
-        //take care of contents
2499
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2500
-        $this->display_admin_page_with_sidebar();
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Output category details content.
2507
-     */
2508
-    protected function _category_details_content()
2509
-    {
2510
-        $editor_args['category_desc'] = array(
2511
-            'type'          => 'wp_editor',
2512
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2513
-            'class'         => 'my_editor_custom',
2514
-            'wpeditor_args' => array('media_buttons' => false),
2515
-        );
2516
-        $_wp_editor = $this->_generate_admin_form_fields($editor_args, 'array');
2517
-        $all_terms = get_terms(
2518
-            array('espresso_event_categories'),
2519
-            array('hide_empty' => 0, 'exclude' => array($this->_category->id))
2520
-        );
2521
-        //setup category select for term parents.
2522
-        $category_select_values[] = array(
2523
-            'text' => esc_html__('No Parent', 'event_espresso'),
2524
-            'id'   => 0,
2525
-        );
2526
-        foreach ($all_terms as $term) {
2527
-            $category_select_values[] = array(
2528
-                'text' => $term->name,
2529
-                'id'   => $term->term_id,
2530
-            );
2531
-        }
2532
-        $category_select = EEH_Form_Fields::select_input(
2533
-            'category_parent',
2534
-            $category_select_values,
2535
-            $this->_category->parent
2536
-        );
2537
-        $template_args = array(
2538
-            'category'                 => $this->_category,
2539
-            'category_select'          => $category_select,
2540
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2541
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2542
-            'disable'                  => '',
2543
-            'disabled_message'         => false,
2544
-        );
2545
-        $template = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2546
-        return EEH_Template::display_template($template, $template_args, true);
2547
-    }
2548
-
2549
-
2550
-    /**
2551
-     * Handles deleting categories.
2552
-     */
2553
-    protected function _delete_categories()
2554
-    {
2555
-        $cat_ids = isset($this->_req_data['EVT_CAT_ID']) ? (array)$this->_req_data['EVT_CAT_ID']
2556
-            : (array)$this->_req_data['category_id'];
2557
-        foreach ($cat_ids as $cat_id) {
2558
-            $this->_delete_category($cat_id);
2559
-        }
2560
-        //doesn't matter what page we're coming from... we're going to the same place after delete.
2561
-        $query_args = array(
2562
-            'action' => 'category_list',
2563
-        );
2564
-        $this->_redirect_after_action(0, '', '', $query_args);
2565
-    }
2566
-
2567
-
2568
-
2569
-    /**
2570
-     * Handles deleting specific category.
2571
-     * @param int $cat_id
2572
-     */
2573
-    protected function _delete_category($cat_id)
2574
-    {
2575
-        $cat_id = absint($cat_id);
2576
-        wp_delete_term($cat_id, 'espresso_event_categories');
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Handles triggering the update or insertion of a new category.
2583
-     * @param bool $new_category  true means we're triggering the insert of a new category.
2584
-     */
2585
-    protected function _insert_or_update_category($new_category)
2586
-    {
2587
-        $cat_id = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2588
-        $success = 0; //we already have a success message so lets not send another.
2589
-        if ($cat_id) {
2590
-            $query_args = array(
2591
-                'action'     => 'edit_category',
2592
-                'EVT_CAT_ID' => $cat_id,
2593
-            );
2594
-        } else {
2595
-            $query_args = array('action' => 'add_category');
2596
-        }
2597
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2598
-    }
2599
-
2600
-
2601
-
2602
-    /**
2603
-     * Inserts or updates category
2604
-     * @param bool $update (true indicates we're updating a category).
2605
-     * @return bool|mixed|string
2606
-     */
2607
-    private function _insert_category($update = false)
2608
-    {
2609
-        $cat_id = $update ? $this->_req_data['EVT_CAT_ID'] : '';
2610
-        $category_name = isset($this->_req_data['category_name']) ? $this->_req_data['category_name'] : '';
2611
-        $category_desc = isset($this->_req_data['category_desc']) ? $this->_req_data['category_desc'] : '';
2612
-        $category_parent = isset($this->_req_data['category_parent']) ? $this->_req_data['category_parent'] : 0;
2613
-        if (empty($category_name)) {
2614
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2615
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2616
-            return false;
2617
-        }
2618
-        $term_args = array(
2619
-            'name'        => $category_name,
2620
-            'description' => $category_desc,
2621
-            'parent'      => $category_parent,
2622
-        );
2623
-        //was the category_identifier input disabled?
2624
-        if (isset($this->_req_data['category_identifier'])) {
2625
-            $term_args['slug'] = $this->_req_data['category_identifier'];
2626
-        }
2627
-        $insert_ids = $update
2628
-            ? wp_update_term($cat_id, 'espresso_event_categories', $term_args)
2629
-            : wp_insert_term($category_name, 'espresso_event_categories', $term_args);
2630
-        if ( ! is_array($insert_ids)) {
2631
-            $msg = esc_html__(
2632
-                'An error occurred and the category has not been saved to the database.',
2633
-                'event_espresso'
2634
-            );
2635
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2636
-        } else {
2637
-            $cat_id = $insert_ids['term_id'];
2638
-            $msg = sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2639
-            EE_Error::add_success($msg);
2640
-        }
2641
-        return $cat_id;
2642
-    }
2643
-
2644
-
2645
-
2646
-    /**
2647
-     * Gets categories or count of categories matching the arguments in the request.
2648
-     * @param int  $per_page
2649
-     * @param int  $current_page
2650
-     * @param bool $count
2651
-     * @return EE_Base_Class[]|EE_Term_Taxonomy[]|int
2652
-     */
2653
-    public function get_categories($per_page = 10, $current_page = 1, $count = false)
2654
-    {
2655
-        //testing term stuff
2656
-        $orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'Term.term_id';
2657
-        $order = isset($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2658
-        $limit = ($current_page - 1) * $per_page;
2659
-        $where = array('taxonomy' => 'espresso_event_categories');
2660
-        if (isset($this->_req_data['s'])) {
2661
-            $sstr = '%' . $this->_req_data['s'] . '%';
2662
-            $where['OR'] = array(
2663
-                'Term.name'   => array('LIKE', $sstr),
2664
-                'description' => array('LIKE', $sstr),
2665
-            );
2666
-        }
2667
-        $query_params = array(
2668
-            $where,
2669
-            'order_by'   => array($orderby => $order),
2670
-            'limit'      => $limit . ',' . $per_page,
2671
-            'force_join' => array('Term'),
2672
-        );
2673
-        $categories = $count
2674
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2675
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2676
-        return $categories;
2677
-    }
2678
-
2679
-    /* end category stuff */
2680
-    /**************/
2681
-
2682
-
2683
-    /**
2684
-     * Callback for the `ee_save_timezone_setting` ajax action.
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function save_timezonestring_setting()
2688
-    {
2689
-        $timezone_string = isset($this->_req_data['timezone_selected'])
2690
-            ? $this->_req_data['timezone_selected']
2691
-            : '';
2692
-        if  (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false))
2693
-        {
2694
-            EE_Error::add_error(
2695
-                esc_html('An invalid timezone string submitted.', 'event_espresso'),
2696
-                __FILE__, __FUNCTION__, __LINE__
2697
-            );
2698
-            $this->_template_args['error'] = true;
2699
-            $this->_return_json();
2700
-        }
2701
-
2702
-        update_option('timezone_string', $timezone_string);
2703
-        EE_Error::add_success(
2704
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2705
-        );
2706
-        $this->_template_args['success'] = true;
2707
-        $this->_return_json(true, array('action' => 'create_new'));
2708
-    }
394
+				'qtips'         => array('EE_Event_Editor_Decaf_Tips'),
395
+				'require_nonce' => false,
396
+			),
397
+			'default_event_settings' => array(
398
+				'nav'           => array(
399
+					'label' => esc_html__('Default Settings', 'event_espresso'),
400
+					'order' => 40,
401
+				),
402
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
403
+				'labels'        => array(
404
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
405
+				),
406
+				'help_tabs'     => array(
407
+					'default_settings_help_tab'        => array(
408
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
409
+						'filename' => 'events_default_settings',
410
+					),
411
+					'default_settings_status_help_tab' => array(
412
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
413
+						'filename' => 'events_default_settings_status',
414
+					),
415
+					'default_maximum_tickets_help_tab' => array(
416
+						'title' => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
417
+						'filename' => 'events_default_settings_max_tickets',
418
+					)
419
+				),
420
+				'help_tour'     => array('Event_Default_Settings_Help_Tour'),
421
+				'require_nonce' => false,
422
+			),
423
+			//template settings
424
+			'template_settings'      => array(
425
+				'nav'           => array(
426
+					'label' => esc_html__('Templates', 'event_espresso'),
427
+					'order' => 30,
428
+				),
429
+				'metaboxes'     => $this->_default_espresso_metaboxes,
430
+				'help_tabs'     => array(
431
+					'general_settings_templates_help_tab' => array(
432
+						'title'    => esc_html__('Templates', 'event_espresso'),
433
+						'filename' => 'general_settings_templates',
434
+					),
435
+				),
436
+				'help_tour'     => array('Templates_Help_Tour'),
437
+				'require_nonce' => false,
438
+			),
439
+			//event category stuff
440
+			'add_category'           => array(
441
+				'nav'           => array(
442
+					'label'      => esc_html__('Add Category', 'event_espresso'),
443
+					'order'      => 15,
444
+					'persistent' => false,
445
+				),
446
+				'help_tabs'     => array(
447
+					'add_category_help_tab' => array(
448
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
449
+						'filename' => 'events_add_category',
450
+					),
451
+				),
452
+				'help_tour'     => array('Event_Add_Category_Help_Tour'),
453
+				'metaboxes'     => array('_publish_post_box'),
454
+				'require_nonce' => false,
455
+			),
456
+			'edit_category'          => array(
457
+				'nav'           => array(
458
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
459
+					'order'      => 15,
460
+					'persistent' => false,
461
+					'url'        => isset($this->_req_data['EVT_CAT_ID'])
462
+						? add_query_arg(
463
+							array('EVT_CAT_ID' => $this->_req_data['EVT_CAT_ID']),
464
+							$this->_current_page_view_url
465
+						)
466
+						: $this->_admin_base_url,
467
+				),
468
+				'help_tabs'     => array(
469
+					'edit_category_help_tab' => array(
470
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
471
+						'filename' => 'events_edit_category',
472
+					),
473
+				),
474
+				/*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
475
+				'metaboxes'     => array('_publish_post_box'),
476
+				'require_nonce' => false,
477
+			),
478
+			'category_list'          => array(
479
+				'nav'           => array(
480
+					'label' => esc_html__('Categories', 'event_espresso'),
481
+					'order' => 20,
482
+				),
483
+				'list_table'    => 'Event_Categories_Admin_List_Table',
484
+				'help_tabs'     => array(
485
+					'events_categories_help_tab'                       => array(
486
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
487
+						'filename' => 'events_categories',
488
+					),
489
+					'events_categories_table_column_headings_help_tab' => array(
490
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
491
+						'filename' => 'events_categories_table_column_headings',
492
+					),
493
+					'events_categories_view_help_tab'                  => array(
494
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
495
+						'filename' => 'events_categories_views',
496
+					),
497
+					'events_categories_other_help_tab'                 => array(
498
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
499
+						'filename' => 'events_categories_other',
500
+					),
501
+				),
502
+				'help_tour'     => array(
503
+					'Event_Categories_Help_Tour',
504
+				),
505
+				'metaboxes'     => $this->_default_espresso_metaboxes,
506
+				'require_nonce' => false,
507
+			),
508
+		);
509
+	}
510
+
511
+
512
+	/**
513
+	 * Used to register any global screen options if necessary for every route in this admin page group.
514
+	 */
515
+	protected function _add_screen_options()
516
+	{
517
+	}
518
+
519
+
520
+	/**
521
+	 * Implementing the screen options for the 'default' route.
522
+	 */
523
+	protected function _add_screen_options_default()
524
+	{
525
+		$this->_per_page_screen_option();
526
+	}
527
+
528
+
529
+	/**
530
+	 * Implementing screen options for the category list route.
531
+	 */
532
+	protected function _add_screen_options_category_list()
533
+	{
534
+		$page_title = $this->_admin_page_title;
535
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
536
+		$this->_per_page_screen_option();
537
+		$this->_admin_page_title = $page_title;
538
+	}
539
+
540
+
541
+	/**
542
+	 * Used to register any global feature pointers for the admin page group.
543
+	 */
544
+	protected function _add_feature_pointers()
545
+	{
546
+	}
547
+
548
+
549
+	/**
550
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
551
+	 */
552
+	public function load_scripts_styles()
553
+	{
554
+		wp_register_style(
555
+			'events-admin-css',
556
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
557
+			array(),
558
+			EVENT_ESPRESSO_VERSION
559
+		);
560
+		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', array(), EVENT_ESPRESSO_VERSION);
561
+		wp_enqueue_style('events-admin-css');
562
+		wp_enqueue_style('ee-cat-admin');
563
+		//todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
564
+		//registers for all views
565
+		//scripts
566
+		wp_register_script(
567
+			'event_editor_js',
568
+			EVENTS_ASSETS_URL . 'event_editor.js',
569
+			array('ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'),
570
+			EVENT_ESPRESSO_VERSION,
571
+			true
572
+		);
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * Enqueuing scripts and styles specific to this view
579
+	 */
580
+	public function load_scripts_styles_create_new()
581
+	{
582
+		$this->load_scripts_styles_edit();
583
+	}
584
+
585
+
586
+
587
+	/**
588
+	 * Enqueuing scripts and styles specific to this view
589
+	 */
590
+	public function load_scripts_styles_edit()
591
+	{
592
+		//styles
593
+		wp_enqueue_style('espresso-ui-theme');
594
+		wp_register_style(
595
+			'event-editor-css',
596
+			EVENTS_ASSETS_URL . 'event-editor.css',
597
+			array('ee-admin-css'),
598
+			EVENT_ESPRESSO_VERSION
599
+		);
600
+		wp_enqueue_style('event-editor-css');
601
+		//scripts
602
+		wp_register_script(
603
+			'event-datetime-metabox',
604
+			EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
605
+			array('event_editor_js', 'ee-datepicker'),
606
+			EVENT_ESPRESSO_VERSION
607
+		);
608
+		wp_enqueue_script('event-datetime-metabox');
609
+	}
610
+
611
+
612
+	/**
613
+	 * Populating the _views property for the category list table view.
614
+	 */
615
+	protected function _set_list_table_views_category_list()
616
+	{
617
+		$this->_views = array(
618
+			'all' => array(
619
+				'slug'        => 'all',
620
+				'label'       => esc_html__('All', 'event_espresso'),
621
+				'count'       => 0,
622
+				'bulk_action' => array(
623
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
624
+				),
625
+			),
626
+		);
627
+	}
628
+
629
+
630
+	/**
631
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
632
+	 */
633
+	public function admin_init()
634
+	{
635
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
636
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
637
+			'event_espresso'
638
+		);
639
+	}
640
+
641
+
642
+	/**
643
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page group.
644
+	 */
645
+	public function admin_notices()
646
+	{
647
+	}
648
+
649
+
650
+	/**
651
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
652
+	 * this admin page group.
653
+	 */
654
+	public function admin_footer_scripts()
655
+	{
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
662
+	 * warning (via EE_Error::add_error());
663
+	 *
664
+	 * @param  EE_Event $event Event object
665
+	 * @param string    $req_type
666
+	 * @return void
667
+	 * @throws EE_Error
668
+	 * @access public
669
+	 */
670
+	public function verify_event_edit($event = null, $req_type = '')
671
+	{
672
+		// don't need to do this when processing
673
+		if(!empty($req_type)) {
674
+			return;
675
+		}
676
+		// no event?
677
+		if (empty($event)) {
678
+			// set event
679
+			$event = $this->_cpt_model_obj;
680
+		}
681
+		// STILL no event?
682
+		if (! $event instanceof EE_Event) {
683
+			return;
684
+		}
685
+		$orig_status = $event->status();
686
+		// first check if event is active.
687
+		if (
688
+			$orig_status === EEM_Event::cancelled
689
+			|| $orig_status === EEM_Event::postponed
690
+			|| $event->is_expired()
691
+			|| $event->is_inactive()
692
+		) {
693
+			return;
694
+		}
695
+		//made it here so it IS active... next check that any of the tickets are sold.
696
+		if ($event->is_sold_out(true)) {
697
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
698
+				EE_Error::add_attention(
699
+					sprintf(
700
+						esc_html__(
701
+							'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.',
702
+							'event_espresso'
703
+						),
704
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
705
+					)
706
+				);
707
+			}
708
+			return;
709
+		} else if ($orig_status === EEM_Event::sold_out) {
710
+			EE_Error::add_attention(
711
+				sprintf(
712
+					esc_html__(
713
+						'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.',
714
+						'event_espresso'
715
+					),
716
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
717
+				)
718
+			);
719
+		}
720
+		//now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
721
+		if ( ! $event->tickets_on_sale()) {
722
+			return;
723
+		}
724
+		//made it here so show warning
725
+		$this->_edit_event_warning();
726
+	}
727
+
728
+
729
+
730
+	/**
731
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
732
+	 * When needed, hook this into a EE_Error::add_error() notice.
733
+	 *
734
+	 * @access protected
735
+	 * @return void
736
+	 */
737
+	protected function _edit_event_warning()
738
+	{
739
+		// we don't want to add warnings during these requests
740
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'editpost') {
741
+			return;
742
+		}
743
+		EE_Error::add_attention(
744
+			esc_html__(
745
+				'Please be advised that this event has been published and is open for registrations on your website. If you update any registration-related details (i.e. custom questions, messages, tickets, datetimes, etc.) while a registration is in process, the registration process could be interrupted and result in errors for the person registering and potentially incorrect registration or transaction data inside Event Espresso. We recommend editing events during a period of slow traffic, or even temporarily changing the status of an event to "Draft" until your edits are complete.',
746
+				'event_espresso'
747
+			)
748
+		);
749
+	}
750
+
751
+
752
+
753
+	/**
754
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
755
+	 * Otherwise, do the normal logic
756
+	 *
757
+	 * @return string
758
+	 * @throws \EE_Error
759
+	 */
760
+	protected function _create_new_cpt_item()
761
+	{
762
+		$has_timezone_string = get_option('timezone_string');
763
+		//only nag them about setting their timezone if it's their first event, and they haven't already done it
764
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists(array())) {
765
+			EE_Error::add_attention(
766
+				sprintf(
767
+					__(
768
+						'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',
769
+						'event_espresso'
770
+					),
771
+					'<br>',
772
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
773
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
774
+					. '</select>',
775
+					'<button class="button button-secondary timezone-submit">',
776
+					'</button><span class="spinner"></span>'
777
+				),
778
+				__FILE__,
779
+				__FUNCTION__,
780
+				__LINE__
781
+			);
782
+		}
783
+		return parent::_create_new_cpt_item();
784
+	}
785
+
786
+
787
+	/**
788
+	 * Sets the _views property for the default route in this admin page group.
789
+	 */
790
+	protected function _set_list_table_views_default()
791
+	{
792
+		$this->_views = array(
793
+			'all'   => array(
794
+				'slug'        => 'all',
795
+				'label'       => esc_html__('View All Events', 'event_espresso'),
796
+				'count'       => 0,
797
+				'bulk_action' => array(
798
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
799
+				),
800
+			),
801
+			'draft' => array(
802
+				'slug'        => 'draft',
803
+				'label'       => esc_html__('Draft', 'event_espresso'),
804
+				'count'       => 0,
805
+				'bulk_action' => array(
806
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
807
+				),
808
+			),
809
+		);
810
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
811
+			$this->_views['trash'] = array(
812
+				'slug'        => 'trash',
813
+				'label'       => esc_html__('Trash', 'event_espresso'),
814
+				'count'       => 0,
815
+				'bulk_action' => array(
816
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
817
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
818
+				),
819
+			);
820
+		}
821
+	}
822
+
823
+
824
+
825
+	/**
826
+	 * Provides the legend item array for the default list table view.
827
+	 * @return array
828
+	 */
829
+	protected function _event_legend_items()
830
+	{
831
+		$items = array(
832
+			'view_details'   => array(
833
+				'class' => 'dashicons dashicons-search',
834
+				'desc'  => esc_html__('View Event', 'event_espresso'),
835
+			),
836
+			'edit_event'     => array(
837
+				'class' => 'ee-icon ee-icon-calendar-edit',
838
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
839
+			),
840
+			'view_attendees' => array(
841
+				'class' => 'dashicons dashicons-groups',
842
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
843
+			),
844
+		);
845
+		$items = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
846
+		$statuses = array(
847
+			'sold_out_status'  => array(
848
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
849
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
850
+			),
851
+			'active_status'    => array(
852
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
853
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
854
+			),
855
+			'upcoming_status'  => array(
856
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
857
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
858
+			),
859
+			'postponed_status' => array(
860
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
861
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
862
+			),
863
+			'cancelled_status' => array(
864
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
865
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
866
+			),
867
+			'expired_status'   => array(
868
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
869
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
870
+			),
871
+			'inactive_status'  => array(
872
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
873
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
874
+			),
875
+		);
876
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
877
+		return array_merge($items, $statuses);
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 * @return EEM_Event
884
+	 */
885
+	private function _event_model()
886
+	{
887
+		if ( ! $this->_event_model instanceof EEM_Event) {
888
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
889
+		}
890
+		return $this->_event_model;
891
+	}
892
+
893
+
894
+
895
+	/**
896
+	 * Adds extra buttons to the WP CPT permalink field row.
897
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
898
+	 *
899
+	 * @param  string $return    the current html
900
+	 * @param  int    $id        the post id for the page
901
+	 * @param  string $new_title What the title is
902
+	 * @param  string $new_slug  what the slug is
903
+	 * @return string            The new html string for the permalink area
904
+	 */
905
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
906
+	{
907
+		//make sure this is only when editing
908
+		if ( ! empty($id)) {
909
+			$post = get_post($id);
910
+			$return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
911
+					   . esc_html__('Shortcode', 'event_espresso')
912
+					   . '</a> ';
913
+			$return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
914
+					   . $post->ID
915
+					   . ']">';
916
+		}
917
+		return $return;
918
+	}
919
+
920
+
921
+
922
+	/**
923
+	 * _events_overview_list_table
924
+	 * This contains the logic for showing the events_overview list
925
+	 *
926
+	 * @access protected
927
+	 * @return void
928
+	 * @throws \EE_Error
929
+	 */
930
+	protected function _events_overview_list_table()
931
+	{
932
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
933
+		$this->_template_args['after_list_table'] = ! empty($this->_template_args['after_list_table'])
934
+			? (array)$this->_template_args['after_list_table']
935
+			: array();
936
+		$this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
937
+																			  . EEH_Template::get_button_or_link(
938
+				get_post_type_archive_link('espresso_events'),
939
+				esc_html__("View Event Archive Page", "event_espresso"),
940
+				'button'
941
+			);
942
+		$this->_template_args['after_list_table']['legend'] = $this->_display_legend($this->_event_legend_items());
943
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
944
+				'create_new',
945
+				'add',
946
+				array(),
947
+				'add-new-h2'
948
+			);
949
+		$this->display_admin_list_table_page_with_no_sidebar();
950
+	}
951
+
952
+
953
+
954
+	/**
955
+	 * this allows for extra misc actions in the default WP publish box
956
+	 *
957
+	 * @return void
958
+	 */
959
+	public function extra_misc_actions_publish_box()
960
+	{
961
+		$this->_generate_publish_box_extra_content();
962
+	}
963
+
964
+
965
+
966
+	/**
967
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been saved.
968
+	 * Typically you would use this to save any additional data.
969
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
970
+	 * ALSO very important.  When a post transitions from scheduled to published,
971
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from other meta saves.
972
+	 * So MAKE sure that you handle this accordingly.
973
+	 *
974
+	 * @access protected
975
+	 * @abstract
976
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
977
+	 * @param  object $post    The post object of the cpt that was saved.
978
+	 * @return void
979
+	 * @throws \EE_Error
980
+	 */
981
+	protected function _insert_update_cpt_item($post_id, $post)
982
+	{
983
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
984
+			//get out we're not processing an event save.
985
+			return;
986
+		}
987
+		$event_values = array(
988
+			'EVT_display_desc'                => ! empty($this->_req_data['display_desc']) ? 1 : 0,
989
+			'EVT_display_ticket_selector'     => ! empty($this->_req_data['display_ticket_selector']) ? 1 : 0,
990
+			'EVT_additional_limit'            => min(
991
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
992
+				! empty($this->_req_data['additional_limit']) ? $this->_req_data['additional_limit'] : null
993
+			),
994
+			'EVT_default_registration_status' => ! empty($this->_req_data['EVT_default_registration_status'])
995
+				? $this->_req_data['EVT_default_registration_status']
996
+				: EE_Registry::instance()->CFG->registration->default_STS_ID,
997
+			'EVT_member_only'                 => ! empty($this->_req_data['member_only']) ? 1 : 0,
998
+			'EVT_allow_overflow'              => ! empty($this->_req_data['EVT_allow_overflow']) ? 1 : 0,
999
+			'EVT_timezone_string'             => ! empty($this->_req_data['timezone_string'])
1000
+				? $this->_req_data['timezone_string'] : null,
1001
+			'EVT_external_URL'                => ! empty($this->_req_data['externalURL'])
1002
+				? $this->_req_data['externalURL'] : null,
1003
+			'EVT_phone'                       => ! empty($this->_req_data['event_phone'])
1004
+				? $this->_req_data['event_phone'] : null,
1005
+		);
1006
+		//update event
1007
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1008
+		//get event_object for other metaboxes... though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id ).. i have to setup where conditions to override the filters in the model that filter out autodraft and inherit statuses so we GET the inherit id!
1009
+		$get_one_where = array(
1010
+			$this->_event_model()->primary_key_name() => $post_id,
1011
+			'OR' => array(
1012
+				'status' => $post->post_status,
1013
+				// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1014
+				// but the returned object here has a status of "publish", so use the original post status as well
1015
+				'status*1' => $this->_req_data['original_post_status'],
1016
+			)
1017
+		);
1018
+		$event = $this->_event_model()->get_one(array($get_one_where));
1019
+		//the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1020
+		$event_update_callbacks = apply_filters(
1021
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1022
+			array(
1023
+				array($this, '_default_venue_update'),
1024
+				array($this, '_default_tickets_update')
1025
+			)
1026
+		);
1027
+		$att_success = true;
1028
+		foreach ($event_update_callbacks as $e_callback) {
1029
+			$_success = is_callable($e_callback)
1030
+				? call_user_func($e_callback, $event, $this->_req_data)
1031
+				: false;
1032
+			//if ANY of these updates fail then we want the appropriate global error message
1033
+			$att_success = ! $att_success ? $att_success : $_success;
1034
+		}
1035
+		//any errors?
1036
+		if ($success && false === $att_success) {
1037
+			EE_Error::add_error(
1038
+				esc_html__(
1039
+					'Event Details saved successfully but something went wrong with saving attachments.',
1040
+					'event_espresso'
1041
+				),
1042
+				__FILE__,
1043
+				__FUNCTION__,
1044
+				__LINE__
1045
+			);
1046
+		} else if ($success === false) {
1047
+			EE_Error::add_error(
1048
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1049
+				__FILE__,
1050
+				__FUNCTION__,
1051
+				__LINE__
1052
+			);
1053
+		}
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * @see parent::restore_item()
1060
+	 * @param int $post_id
1061
+	 * @param int $revision_id
1062
+	 */
1063
+	protected function _restore_cpt_item($post_id, $revision_id)
1064
+	{
1065
+		//copy existing event meta to new post
1066
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1067
+		if ($post_evt instanceof EE_Event) {
1068
+			//meta revision restore
1069
+			$post_evt->restore_revision($revision_id);
1070
+			//related objs restore
1071
+			$post_evt->restore_revision($revision_id, array('Venue', 'Datetime', 'Price'));
1072
+		}
1073
+	}
1074
+
1075
+
1076
+
1077
+	/**
1078
+	 * Attach the venue to the Event
1079
+	 *
1080
+	 * @param  \EE_Event $evtobj Event Object to add the venue to
1081
+	 * @param  array     $data   The request data from the form
1082
+	 * @return bool           Success or fail.
1083
+	 */
1084
+	protected function _default_venue_update(\EE_Event $evtobj, $data)
1085
+	{
1086
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1087
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1088
+		$rows_affected = null;
1089
+		$venue_id = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1090
+		// very important.  If we don't have a venue name...
1091
+		// then we'll get out because not necessary to create empty venue
1092
+		if (empty($data['venue_title'])) {
1093
+			return false;
1094
+		}
1095
+		$venue_array = array(
1096
+			'VNU_wp_user'         => $evtobj->get('EVT_wp_user'),
1097
+			'VNU_name'            => ! empty($data['venue_title']) ? $data['venue_title'] : null,
1098
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1099
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1100
+			'VNU_short_desc'      => ! empty($data['venue_short_description']) ? $data['venue_short_description']
1101
+				: null,
1102
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1103
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1104
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1105
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1106
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1107
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1108
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1109
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1110
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1111
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1112
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1113
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1114
+			'status'              => 'publish',
1115
+		);
1116
+		//if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1117
+		if ( ! empty($venue_id)) {
1118
+			$update_where = array($venue_model->primary_key_name() => $venue_id);
1119
+			$rows_affected = $venue_model->update($venue_array, array($update_where));
1120
+			//we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1121
+			$evtobj->_add_relation_to($venue_id, 'Venue');
1122
+			return $rows_affected > 0 ? true : false;
1123
+		} else {
1124
+			//we insert the venue
1125
+			$venue_id = $venue_model->insert($venue_array);
1126
+			$evtobj->_add_relation_to($venue_id, 'Venue');
1127
+			return ! empty($venue_id) ? true : false;
1128
+		}
1129
+		//when we have the ancestor come in it's already been handled by the revision save.
1130
+	}
1131
+
1132
+
1133
+
1134
+	/**
1135
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1136
+	 *
1137
+	 * @param  EE_Event $evtobj The Event object we're attaching data to
1138
+	 * @param  array    $data   The request data from the form
1139
+	 * @return array
1140
+	 */
1141
+	protected function _default_tickets_update(EE_Event $evtobj, $data)
1142
+	{
1143
+		$success = true;
1144
+		$saved_dtt = null;
1145
+		$saved_tickets = array();
1146
+		$incoming_date_formats = array('Y-m-d', 'h:i a');
1147
+		foreach ($data['edit_event_datetimes'] as $row => $dtt) {
1148
+			//trim all values to ensure any excess whitespace is removed.
1149
+			$dtt = array_map('trim', $dtt);
1150
+			$dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end']
1151
+				: $dtt['DTT_EVT_start'];
1152
+			$datetime_values = array(
1153
+				'DTT_ID'        => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
1154
+				'DTT_EVT_start' => $dtt['DTT_EVT_start'],
1155
+				'DTT_EVT_end'   => $dtt['DTT_EVT_end'],
1156
+				'DTT_reg_limit' => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
1157
+				'DTT_order'     => $row,
1158
+			);
1159
+			//if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
1160
+			if ( ! empty($dtt['DTT_ID'])) {
1161
+				$DTM = EE_Registry::instance()
1162
+								  ->load_model('Datetime', array($evtobj->get_timezone()))
1163
+								  ->get_one_by_ID($dtt['DTT_ID']);
1164
+				$DTM->set_date_format($incoming_date_formats[0]);
1165
+				$DTM->set_time_format($incoming_date_formats[1]);
1166
+				foreach ($datetime_values as $field => $value) {
1167
+					$DTM->set($field, $value);
1168
+				}
1169
+				//make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.  We need to do this so we dont' TRASH the parent DTT.
1170
+				$saved_dtts[$DTM->ID()] = $DTM;
1171
+			} else {
1172
+				$DTM = EE_Registry::instance()->load_class(
1173
+					'Datetime',
1174
+					array($datetime_values, $evtobj->get_timezone(), $incoming_date_formats),
1175
+					false,
1176
+					false
1177
+				);
1178
+				foreach ($datetime_values as $field => $value) {
1179
+					$DTM->set($field, $value);
1180
+				}
1181
+			}
1182
+			$DTM->save();
1183
+			$DTT = $evtobj->_add_relation_to($DTM, 'Datetime');
1184
+			//load DTT helper
1185
+			//before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1186
+			if ($DTT->get_raw('DTT_EVT_start') > $DTT->get_raw('DTT_EVT_end')) {
1187
+				$DTT->set('DTT_EVT_end', $DTT->get('DTT_EVT_start'));
1188
+				$DTT = EEH_DTT_Helper::date_time_add($DTT, 'DTT_EVT_end', 'days');
1189
+				$DTT->save();
1190
+			}
1191
+			//now we got to make sure we add the new DTT_ID to the $saved_dtts array  because it is possible there was a new one created for the autosave.
1192
+			$saved_dtt = $DTT;
1193
+			$success = ! $success ? $success : $DTT;
1194
+			//if ANY of these updates fail then we want the appropriate global error message.
1195
+			// //todo this is actually sucky we need a better error message but this is what it is for now.
1196
+		}
1197
+		//no dtts get deleted so we don't do any of that logic here.
1198
+		//update tickets next
1199
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
1200
+		foreach ($data['edit_tickets'] as $row => $tkt) {
1201
+			$incoming_date_formats = array('Y-m-d', 'h:i a');
1202
+			$update_prices = false;
1203
+			$ticket_price = isset($data['edit_prices'][$row][1]['PRC_amount'])
1204
+				? $data['edit_prices'][$row][1]['PRC_amount'] : 0;
1205
+			// trim inputs to ensure any excess whitespace is removed.
1206
+			$tkt = array_map('trim', $tkt);
1207
+			if (empty($tkt['TKT_start_date'])) {
1208
+				//let's use now in the set timezone.
1209
+				$now = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
1210
+				$tkt['TKT_start_date'] = $now->format($incoming_date_formats[0] . ' ' . $incoming_date_formats[1]);
1211
+			}
1212
+			if (empty($tkt['TKT_end_date'])) {
1213
+				//use the start date of the first datetime
1214
+				$dtt = $evtobj->first_datetime();
1215
+				$tkt['TKT_end_date'] = $dtt->start_date_and_time(
1216
+					$incoming_date_formats[0],
1217
+					$incoming_date_formats[1]
1218
+				);
1219
+			}
1220
+			$TKT_values = array(
1221
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
1222
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
1223
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
1224
+				'TKT_description' => ! empty($tkt['TKT_description']) ? $tkt['TKT_description'] : '',
1225
+				'TKT_start_date'  => $tkt['TKT_start_date'],
1226
+				'TKT_end_date'    => $tkt['TKT_end_date'],
1227
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
1228
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
1229
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
1230
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
1231
+				'TKT_row'         => $row,
1232
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : $row,
1233
+				'TKT_price'       => $ticket_price,
1234
+			);
1235
+			//if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
1236
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
1237
+				$TKT_values['TKT_ID'] = 0;
1238
+				$TKT_values['TKT_is_default'] = 0;
1239
+				$TKT_values['TKT_price'] = $ticket_price;
1240
+				$update_prices = true;
1241
+			}
1242
+			//if we have a TKT_ID then we need to get that existing TKT_obj and update it
1243
+			//we actually do our saves a head of doing any add_relations to because its entirely possible that this ticket didn't removed or added to any datetime in the session but DID have it's items modified.
1244
+			//keep in mind that if the TKT has been sold (and we have changed pricing information), then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1245
+			if ( ! empty($tkt['TKT_ID'])) {
1246
+				$TKT = EE_Registry::instance()
1247
+								  ->load_model('Ticket', array($evtobj->get_timezone()))
1248
+								  ->get_one_by_ID($tkt['TKT_ID']);
1249
+				if ($TKT instanceof EE_Ticket) {
1250
+					$ticket_sold = $TKT->count_related(
1251
+						'Registration',
1252
+						array(
1253
+							array(
1254
+								'STS_ID' => array(
1255
+									'NOT IN',
1256
+									array(EEM_Registration::status_id_incomplete),
1257
+								),
1258
+							),
1259
+						)
1260
+					) > 0 ? true : false;
1261
+					//let's just check the total price for the existing ticket and determine if it matches the new total price.  if they are different then we create a new ticket (if tkts sold) if they aren't different then we go ahead and modify existing ticket.
1262
+					$create_new_TKT = $ticket_sold && $ticket_price != $TKT->get('TKT_price')
1263
+									  && ! $TKT->get(
1264
+						'TKT_deleted'
1265
+					) ? true : false;
1266
+					$TKT->set_date_format($incoming_date_formats[0]);
1267
+					$TKT->set_time_format($incoming_date_formats[1]);
1268
+					//set new values
1269
+					foreach ($TKT_values as $field => $value) {
1270
+						if ($field == 'TKT_qty') {
1271
+							$TKT->set_qty($value);
1272
+						} else {
1273
+							$TKT->set($field, $value);
1274
+						}
1275
+					}
1276
+					//if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
1277
+					if ($create_new_TKT) {
1278
+						//archive the old ticket first
1279
+						$TKT->set('TKT_deleted', 1);
1280
+						$TKT->save();
1281
+						//make sure this ticket is still recorded in our saved_tkts so we don't run it through the regular trash routine.
1282
+						$saved_tickets[$TKT->ID()] = $TKT;
1283
+						//create new ticket that's a copy of the existing except a new id of course (and not archived) AND has the new TKT_price associated with it.
1284
+						$TKT = clone $TKT;
1285
+						$TKT->set('TKT_ID', 0);
1286
+						$TKT->set('TKT_deleted', 0);
1287
+						$TKT->set('TKT_price', $ticket_price);
1288
+						$TKT->set('TKT_sold', 0);
1289
+						//now we need to make sure that $new prices are created as well and attached to new ticket.
1290
+						$update_prices = true;
1291
+					}
1292
+					//make sure price is set if it hasn't been already
1293
+					$TKT->set('TKT_price', $ticket_price);
1294
+				}
1295
+			} else {
1296
+				//no TKT_id so a new TKT
1297
+				$TKT_values['TKT_price'] = $ticket_price;
1298
+				$TKT = EE_Registry::instance()->load_class('Ticket', array($TKT_values), false, false);
1299
+				if ($TKT instanceof EE_Ticket) {
1300
+					//need to reset values to properly account for the date formats
1301
+					$TKT->set_date_format($incoming_date_formats[0]);
1302
+					$TKT->set_time_format($incoming_date_formats[1]);
1303
+					$TKT->set_timezone($evtobj->get_timezone());
1304
+					//set new values
1305
+					foreach ($TKT_values as $field => $value) {
1306
+						if ($field == 'TKT_qty') {
1307
+							$TKT->set_qty($value);
1308
+						} else {
1309
+							$TKT->set($field, $value);
1310
+						}
1311
+					}
1312
+					$update_prices = true;
1313
+				}
1314
+			}
1315
+			// cap ticket qty by datetime reg limits
1316
+			$TKT->set_qty(min($TKT->qty(), $TKT->qty('reg_limit')));
1317
+			//update ticket.
1318
+			$TKT->save();
1319
+			//before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
1320
+			if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
1321
+				$TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
1322
+				$TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
1323
+				$TKT->save();
1324
+			}
1325
+			//initially let's add the ticket to the dtt
1326
+			$saved_dtt->_add_relation_to($TKT, 'Ticket');
1327
+			$saved_tickets[$TKT->ID()] = $TKT;
1328
+			//add prices to ticket
1329
+			$this->_add_prices_to_ticket($data['edit_prices'][$row], $TKT, $update_prices);
1330
+		}
1331
+		//however now we need to handle permanently deleting tickets via the ui.  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.  However, it does allow for deleting tickets that have no tickets sold, in which case we want to get rid of permanently because there is no need to save in db.
1332
+		$old_tickets = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
1333
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1334
+		foreach ($tickets_removed as $id) {
1335
+			$id = absint($id);
1336
+			//get the ticket for this id
1337
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
1338
+			//need to get all the related datetimes on this ticket and remove from every single one of them (remember this process can ONLY kick off if there are NO tkts_sold)
1339
+			$dtts = $tkt_to_remove->get_many_related('Datetime');
1340
+			foreach ($dtts as $dtt) {
1341
+				$tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
1342
+			}
1343
+			//need to do the same for prices (except these prices can also be deleted because again, tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1344
+			$tkt_to_remove->delete_related_permanently('Price');
1345
+			//finally let's delete this ticket (which should not be blocked at this point b/c we've removed all our relationships)
1346
+			$tkt_to_remove->delete_permanently();
1347
+		}
1348
+		return array($saved_dtt, $saved_tickets);
1349
+	}
1350
+
1351
+
1352
+
1353
+	/**
1354
+	 * This attaches a list of given prices to a ticket.
1355
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1356
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1357
+	 * price info and prices are automatically "archived" via the ticket.
1358
+	 *
1359
+	 * @access  private
1360
+	 * @param array     $prices     Array of prices from the form.
1361
+	 * @param EE_Ticket $ticket     EE_Ticket object that prices are being attached to.
1362
+	 * @param bool      $new_prices Whether attach existing incoming prices or create new ones.
1363
+	 * @return  void
1364
+	 */
1365
+	private function _add_prices_to_ticket($prices, EE_Ticket $ticket, $new_prices = false)
1366
+	{
1367
+		foreach ($prices as $row => $prc) {
1368
+			$PRC_values = array(
1369
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
1370
+				'PRT_ID'         => ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null,
1371
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
1372
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
1373
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
1374
+				'PRC_is_default' => 0, //make sure prices are NOT set as default from this context
1375
+				'PRC_order'      => $row,
1376
+			);
1377
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
1378
+				$PRC_values['PRC_ID'] = 0;
1379
+				$PRC = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
1380
+			} else {
1381
+				$PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
1382
+				//update this price with new values
1383
+				foreach ($PRC_values as $field => $newprc) {
1384
+					$PRC->set($field, $newprc);
1385
+				}
1386
+				$PRC->save();
1387
+			}
1388
+			$ticket->_add_relation_to($PRC, 'Price');
1389
+		}
1390
+	}
1391
+
1392
+
1393
+
1394
+	/**
1395
+	 * Add in our autosave ajax handlers
1396
+	 *
1397
+	 */
1398
+	protected function _ee_autosave_create_new()
1399
+	{
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * More autosave handlers.
1405
+	 */
1406
+	protected function _ee_autosave_edit()
1407
+	{
1408
+		return; //TEMPORARILY EXITING CAUSE THIS IS A TODO
1409
+	}
1410
+
1411
+
1412
+
1413
+	/**
1414
+	 *    _generate_publish_box_extra_content
1415
+	 */
1416
+	private function _generate_publish_box_extra_content()
1417
+	{
1418
+		//load formatter helper
1419
+		//args for getting related registrations
1420
+		$approved_query_args = array(
1421
+			array(
1422
+				'REG_deleted' => 0,
1423
+				'STS_ID'      => EEM_Registration::status_id_approved,
1424
+			),
1425
+		);
1426
+		$not_approved_query_args = array(
1427
+			array(
1428
+				'REG_deleted' => 0,
1429
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1430
+			),
1431
+		);
1432
+		$pending_payment_query_args = array(
1433
+			array(
1434
+				'REG_deleted' => 0,
1435
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1436
+			),
1437
+		);
1438
+		// publish box
1439
+		$publish_box_extra_args = array(
1440
+			'view_approved_reg_url'        => add_query_arg(
1441
+				array(
1442
+					'action'      => 'default',
1443
+					'event_id'    => $this->_cpt_model_obj->ID(),
1444
+					'_reg_status' => EEM_Registration::status_id_approved,
1445
+				),
1446
+				REG_ADMIN_URL
1447
+			),
1448
+			'view_not_approved_reg_url'    => add_query_arg(
1449
+				array(
1450
+					'action'      => 'default',
1451
+					'event_id'    => $this->_cpt_model_obj->ID(),
1452
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1453
+				),
1454
+				REG_ADMIN_URL
1455
+			),
1456
+			'view_pending_payment_reg_url' => add_query_arg(
1457
+				array(
1458
+					'action'      => 'default',
1459
+					'event_id'    => $this->_cpt_model_obj->ID(),
1460
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1461
+				),
1462
+				REG_ADMIN_URL
1463
+			),
1464
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1465
+				'Registration',
1466
+				$approved_query_args
1467
+			),
1468
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1469
+				'Registration',
1470
+				$not_approved_query_args
1471
+			),
1472
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1473
+				'Registration',
1474
+				$pending_payment_query_args
1475
+			),
1476
+			'misc_pub_section_class'       => apply_filters(
1477
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1478
+				'misc-pub-section'
1479
+			),
1480
+		);
1481
+		ob_start();
1482
+		do_action(
1483
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1484
+			$this->_cpt_model_obj
1485
+		);
1486
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1487
+		// load template
1488
+		EEH_Template::display_template(
1489
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1490
+			$publish_box_extra_args
1491
+		);
1492
+	}
1493
+
1494
+
1495
+
1496
+	/**
1497
+	 * @return EE_Event
1498
+	 */
1499
+	public function get_event_object()
1500
+	{
1501
+		return $this->_cpt_model_obj;
1502
+	}
1503
+
1504
+
1505
+
1506
+
1507
+	/** METABOXES * */
1508
+	/**
1509
+	 * _register_event_editor_meta_boxes
1510
+	 * add all metaboxes related to the event_editor
1511
+	 *
1512
+	 * @return void
1513
+	 */
1514
+	protected function _register_event_editor_meta_boxes()
1515
+	{
1516
+		$this->verify_cpt_object();
1517
+		add_meta_box(
1518
+			'espresso_event_editor_tickets',
1519
+			esc_html__('Event Datetime & Ticket', 'event_espresso'),
1520
+			array($this, 'ticket_metabox'),
1521
+			$this->page_slug,
1522
+			'normal',
1523
+			'high'
1524
+		);
1525
+		add_meta_box(
1526
+			'espresso_event_editor_event_options',
1527
+			esc_html__('Event Registration Options', 'event_espresso'),
1528
+			array($this, 'registration_options_meta_box'),
1529
+			$this->page_slug,
1530
+			'side',
1531
+			'default'
1532
+		);
1533
+		// NOTE: if you're looking for other metaboxes in here,
1534
+		// where a metabox has a related management page in the admin
1535
+		// you will find it setup in the related management page's "_Hooks" file.
1536
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1537
+	}
1538
+
1539
+
1540
+	/**
1541
+	 * @throws DomainException
1542
+	 * @throws EE_Error
1543
+	 */
1544
+	public function ticket_metabox()
1545
+	{
1546
+		$existing_datetime_ids = $existing_ticket_ids = array();
1547
+		//defaults for template args
1548
+		$template_args = array(
1549
+			'existing_datetime_ids'    => '',
1550
+			'event_datetime_help_link' => '',
1551
+			'ticket_options_help_link' => '',
1552
+			'time'                     => null,
1553
+			'ticket_rows'              => '',
1554
+			'existing_ticket_ids'      => '',
1555
+			'total_ticket_rows'        => 1,
1556
+			'ticket_js_structure'      => '',
1557
+			'trash_icon'               => 'ee-lock-icon',
1558
+			'disabled'                 => '',
1559
+		);
1560
+		$event_id = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1561
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1562
+		/**
1563
+		 * 1. Start with retrieving Datetimes
1564
+		 * 2. Fore each datetime get related tickets
1565
+		 * 3. For each ticket get related prices
1566
+		 */
1567
+		$times = EE_Registry::instance()->load_model('Datetime')->get_all_event_dates($event_id);
1568
+		/** @type EE_Datetime $first_datetime */
1569
+		$first_datetime = reset($times);
1570
+		//do we get related tickets?
1571
+		if ($first_datetime instanceof EE_Datetime
1572
+			&& $first_datetime->ID() !== 0
1573
+		) {
1574
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1575
+			$template_args['time'] = $first_datetime;
1576
+			$related_tickets = $first_datetime->tickets(
1577
+				array(
1578
+					array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
1579
+					'default_where_conditions' => 'none',
1580
+				)
1581
+			);
1582
+			if ( ! empty($related_tickets)) {
1583
+				$template_args['total_ticket_rows'] = count($related_tickets);
1584
+				$row = 0;
1585
+				foreach ($related_tickets as $ticket) {
1586
+					$existing_ticket_ids[] = $ticket->get('TKT_ID');
1587
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1588
+					$row++;
1589
+				}
1590
+			} else {
1591
+				$template_args['total_ticket_rows'] = 1;
1592
+				/** @type EE_Ticket $ticket */
1593
+				$ticket = EE_Registry::instance()->load_model('Ticket')->create_default_object();
1594
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1595
+			}
1596
+		} else {
1597
+			$template_args['time'] = $times[0];
1598
+			/** @type EE_Ticket $ticket */
1599
+			$ticket = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
1600
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket[1]);
1601
+			// NOTE: we're just sending the first default row
1602
+			// (decaf can't manage default tickets so this should be sufficient);
1603
+		}
1604
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1605
+			'event_editor_event_datetimes_help_tab'
1606
+		);
1607
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1608
+		$template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1609
+		$template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1610
+		$template_args['ticket_js_structure'] = $this->_get_ticket_row(
1611
+			EE_Registry::instance()->load_model('Ticket')->create_default_object(),
1612
+			true
1613
+		);
1614
+		$template = apply_filters(
1615
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1616
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1617
+		);
1618
+		EEH_Template::display_template($template, $template_args);
1619
+	}
1620
+
1621
+
1622
+
1623
+	/**
1624
+	 * Setup an individual ticket form for the decaf event editor page
1625
+	 *
1626
+	 * @access private
1627
+	 * @param  EE_Ticket $ticket   the ticket object
1628
+	 * @param  boolean   $skeleton whether we're generating a skeleton for js manipulation
1629
+	 * @param int        $row
1630
+	 * @return string generated html for the ticket row.
1631
+	 */
1632
+	private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1633
+	{
1634
+		$template_args = array(
1635
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1636
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1637
+				: '',
1638
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1639
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1640
+			'TKT_name'            => $ticket->get('TKT_name'),
1641
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1642
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1643
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1644
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1645
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1646
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1647
+			'trash_icon'          => ($skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')))
1648
+									 && ( ! empty($ticket) && $ticket->get('TKT_sold') === 0)
1649
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1650
+			'disabled'            => $skeleton || ( ! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1651
+				: ' disabled=disabled',
1652
+		);
1653
+		$price = $ticket->ID() !== 0
1654
+			? $ticket->get_first_related('Price', array('default_where_conditions' => 'none'))
1655
+			: EE_Registry::instance()->load_model('Price')->create_default_object();
1656
+		$price_args = array(
1657
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1658
+			'PRC_amount'            => $price->get('PRC_amount'),
1659
+			'PRT_ID'                => $price->get('PRT_ID'),
1660
+			'PRC_ID'                => $price->get('PRC_ID'),
1661
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1662
+		);
1663
+		//make sure we have default start and end dates if skeleton
1664
+		//handle rows that should NOT be empty
1665
+		if (empty($template_args['TKT_start_date'])) {
1666
+			//if empty then the start date will be now.
1667
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1668
+		}
1669
+		if (empty($template_args['TKT_end_date'])) {
1670
+			//get the earliest datetime (if present);
1671
+			$earliest_dtt = $this->_cpt_model_obj->ID() > 0
1672
+				? $this->_cpt_model_obj->get_first_related(
1673
+					'Datetime',
1674
+					array('order_by' => array('DTT_EVT_start' => 'ASC'))
1675
+				)
1676
+				: null;
1677
+			if ( ! empty($earliest_dtt)) {
1678
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a');
1679
+			} else {
1680
+				$template_args['TKT_end_date'] = date(
1681
+					'Y-m-d h:i a',
1682
+					mktime(0, 0, 0, date("m"), date("d") + 7, date("Y"))
1683
+				);
1684
+			}
1685
+		}
1686
+		$template_args = array_merge($template_args, $price_args);
1687
+		$template = apply_filters(
1688
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1689
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1690
+			$ticket
1691
+		);
1692
+		return EEH_Template::display_template($template, $template_args, true);
1693
+	}
1694
+
1695
+
1696
+	/**
1697
+	 * @throws DomainException
1698
+	 */
1699
+	public function registration_options_meta_box()
1700
+	{
1701
+		$yes_no_values = array(
1702
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
1703
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
1704
+		);
1705
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1706
+			array(
1707
+				EEM_Registration::status_id_cancelled,
1708
+				EEM_Registration::status_id_declined,
1709
+				EEM_Registration::status_id_incomplete,
1710
+			),
1711
+			true
1712
+		);
1713
+		//$template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1714
+		$template_args['_event'] = $this->_cpt_model_obj;
1715
+		$template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1716
+		$template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1717
+		$template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1718
+			'default_reg_status',
1719
+			$default_reg_status_values,
1720
+			$this->_cpt_model_obj->default_registration_status()
1721
+		);
1722
+		$template_args['display_description'] = EEH_Form_Fields::select_input(
1723
+			'display_desc',
1724
+			$yes_no_values,
1725
+			$this->_cpt_model_obj->display_description()
1726
+		);
1727
+		$template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1728
+			'display_ticket_selector',
1729
+			$yes_no_values,
1730
+			$this->_cpt_model_obj->display_ticket_selector(),
1731
+			'',
1732
+			'',
1733
+			false
1734
+		);
1735
+		$template_args['additional_registration_options'] = apply_filters(
1736
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1737
+			'',
1738
+			$template_args,
1739
+			$yes_no_values,
1740
+			$default_reg_status_values
1741
+		);
1742
+		EEH_Template::display_template(
1743
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1744
+			$template_args
1745
+		);
1746
+	}
1747
+
1748
+
1749
+
1750
+	/**
1751
+	 * _get_events()
1752
+	 * This method simply returns all the events (for the given _view and paging)
1753
+	 *
1754
+	 * @access public
1755
+	 * @param int  $per_page     count of items per page (20 default);
1756
+	 * @param int  $current_page what is the current page being viewed.
1757
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1758
+	 *                           If FALSE then we return an array of event objects
1759
+	 *                           that match the given _view and paging parameters.
1760
+	 * @return array an array of event objects.
1761
+	 */
1762
+	public function get_events($per_page = 10, $current_page = 1, $count = false)
1763
+	{
1764
+		$EEME = $this->_event_model();
1765
+		$offset = ($current_page - 1) * $per_page;
1766
+		$limit = $count ? null : $offset . ',' . $per_page;
1767
+		$orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'EVT_ID';
1768
+		$order = isset($this->_req_data['order']) ? $this->_req_data['order'] : "DESC";
1769
+		if (isset($this->_req_data['month_range'])) {
1770
+			$pieces = explode(' ', $this->_req_data['month_range'], 3);
1771
+			//simulate the FIRST day of the month, that fixes issues for months like February
1772
+			//where PHP doesn't know what to assume for date.
1773
+			//@see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1774
+			$month_r = ! empty($pieces[0]) ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1775
+			$year_r = ! empty($pieces[1]) ? $pieces[1] : '';
1776
+		}
1777
+		$where = array();
1778
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1779
+		//determine what post_status our condition will have for the query.
1780
+		switch ($status) {
1781
+			case 'month' :
1782
+			case 'today' :
1783
+			case null :
1784
+			case 'all' :
1785
+				break;
1786
+			case 'draft' :
1787
+				$where['status'] = array('IN', array('draft', 'auto-draft'));
1788
+				break;
1789
+			default :
1790
+				$where['status'] = $status;
1791
+		}
1792
+		//categories?
1793
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1794
+			? $this->_req_data['EVT_CAT'] : null;
1795
+		if ( ! empty ($category)) {
1796
+			$where['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1797
+			$where['Term_Taxonomy.term_id'] = $category;
1798
+		}
1799
+		//date where conditions
1800
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1801
+		if (isset($this->_req_data['month_range']) && $this->_req_data['month_range'] != '') {
1802
+			$DateTime = new DateTime(
1803
+				$year_r . '-' . $month_r . '-01 00:00:00',
1804
+				new DateTimeZone(EEM_Datetime::instance()->get_timezone())
1805
+			);
1806
+			$start = $DateTime->format(implode(' ', $start_formats));
1807
+			$end = $DateTime->setDate($year_r, $month_r, $DateTime
1808
+				->format('t'))->setTime(23, 59, 59)
1809
+							->format(implode(' ', $start_formats));
1810
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1811
+		} else if (isset($this->_req_data['status']) && $this->_req_data['status'] == 'today') {
1812
+			$DateTime = new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1813
+			$start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1814
+			$end = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1815
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1816
+		} else if (isset($this->_req_data['status']) && $this->_req_data['status'] == 'month') {
1817
+			$now = date('Y-m-01');
1818
+			$DateTime = new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1819
+			$start = $DateTime->setTime(0, 0, 0)->format(implode(' ', $start_formats));
1820
+			$end = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1821
+							->setTime(23, 59, 59)
1822
+							->format(implode(' ', $start_formats));
1823
+			$where['Datetime.DTT_EVT_start'] = array('BETWEEN', array($start, $end));
1824
+		}
1825
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1826
+			$where['EVT_wp_user'] = get_current_user_id();
1827
+		} else {
1828
+			if ( ! isset($where['status'])) {
1829
+				if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1830
+					$where['OR'] = array(
1831
+						'status*restrict_private' => array('!=', 'private'),
1832
+						'AND'                     => array(
1833
+							'status*inclusive' => array('=', 'private'),
1834
+							'EVT_wp_user'      => get_current_user_id(),
1835
+						),
1836
+					);
1837
+				}
1838
+			}
1839
+		}
1840
+		if (isset($this->_req_data['EVT_wp_user'])) {
1841
+			if ($this->_req_data['EVT_wp_user'] != get_current_user_id()
1842
+				&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1843
+			) {
1844
+				$where['EVT_wp_user'] = $this->_req_data['EVT_wp_user'];
1845
+			}
1846
+		}
1847
+		//search query handling
1848
+		if (isset($this->_req_data['s'])) {
1849
+			$search_string = '%' . $this->_req_data['s'] . '%';
1850
+			$where['OR'] = array(
1851
+				'EVT_name'       => array('LIKE', $search_string),
1852
+				'EVT_desc'       => array('LIKE', $search_string),
1853
+				'EVT_short_desc' => array('LIKE', $search_string),
1854
+			);
1855
+		}
1856
+		$where = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $this->_req_data);
1857
+		$query_params = apply_filters(
1858
+			'FHEE__Events_Admin_Page__get_events__query_params',
1859
+			array(
1860
+				$where,
1861
+				'limit'    => $limit,
1862
+				'order_by' => $orderby,
1863
+				'order'    => $order,
1864
+				'group_by' => 'EVT_ID',
1865
+			),
1866
+			$this->_req_data
1867
+		);
1868
+		//let's first check if we have special requests coming in.
1869
+		if (isset($this->_req_data['active_status'])) {
1870
+			switch ($this->_req_data['active_status']) {
1871
+				case 'upcoming' :
1872
+					return $EEME->get_upcoming_events($query_params, $count);
1873
+					break;
1874
+				case 'expired' :
1875
+					return $EEME->get_expired_events($query_params, $count);
1876
+					break;
1877
+				case 'active' :
1878
+					return $EEME->get_active_events($query_params, $count);
1879
+					break;
1880
+				case 'inactive' :
1881
+					return $EEME->get_inactive_events($query_params, $count);
1882
+					break;
1883
+			}
1884
+		}
1885
+		$events = $count ? $EEME->count(array($where), 'EVT_ID', true) : $EEME->get_all($query_params);
1886
+		return $events;
1887
+	}
1888
+
1889
+
1890
+
1891
+	/**
1892
+	 * handling for WordPress CPT actions (trash, restore, delete)
1893
+	 *
1894
+	 * @param string $post_id
1895
+	 */
1896
+	public function trash_cpt_item($post_id)
1897
+	{
1898
+		$this->_req_data['EVT_ID'] = $post_id;
1899
+		$this->_trash_or_restore_event('trash', false);
1900
+	}
1901
+
1902
+
1903
+
1904
+	/**
1905
+	 * @param string $post_id
1906
+	 */
1907
+	public function restore_cpt_item($post_id)
1908
+	{
1909
+		$this->_req_data['EVT_ID'] = $post_id;
1910
+		$this->_trash_or_restore_event('draft', false);
1911
+	}
1912
+
1913
+
1914
+
1915
+	/**
1916
+	 * @param string $post_id
1917
+	 */
1918
+	public function delete_cpt_item($post_id)
1919
+	{
1920
+		$this->_req_data['EVT_ID'] = $post_id;
1921
+		$this->_delete_event(false);
1922
+	}
1923
+
1924
+
1925
+
1926
+	/**
1927
+	 * _trash_or_restore_event
1928
+	 *
1929
+	 * @access protected
1930
+	 * @param  string $event_status
1931
+	 * @param bool    $redirect_after
1932
+	 */
1933
+	protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
1934
+	{
1935
+		//determine the event id and set to array.
1936
+		$EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : false;
1937
+		// loop thru events
1938
+		if ($EVT_ID) {
1939
+			// clean status
1940
+			$event_status = sanitize_key($event_status);
1941
+			// grab status
1942
+			if ( ! empty($event_status)) {
1943
+				$success = $this->_change_event_status($EVT_ID, $event_status);
1944
+			} else {
1945
+				$success = false;
1946
+				$msg = esc_html__(
1947
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
1948
+					'event_espresso'
1949
+				);
1950
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1951
+			}
1952
+		} else {
1953
+			$success = false;
1954
+			$msg = esc_html__(
1955
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
1956
+				'event_espresso'
1957
+			);
1958
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1959
+		}
1960
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
1961
+		if ($redirect_after) {
1962
+			$this->_redirect_after_action($success, 'Event', $action, array('action' => 'default'));
1963
+		}
1964
+	}
1965
+
1966
+
1967
+
1968
+	/**
1969
+	 * _trash_or_restore_events
1970
+	 *
1971
+	 * @access protected
1972
+	 * @param  string $event_status
1973
+	 * @return void
1974
+	 */
1975
+	protected function _trash_or_restore_events($event_status = 'trash')
1976
+	{
1977
+		// clean status
1978
+		$event_status = sanitize_key($event_status);
1979
+		// grab status
1980
+		if ( ! empty($event_status)) {
1981
+			$success = true;
1982
+			//determine the event id and set to array.
1983
+			$EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array)$this->_req_data['EVT_IDs'] : array();
1984
+			// loop thru events
1985
+			foreach ($EVT_IDs as $EVT_ID) {
1986
+				if ($EVT_ID = absint($EVT_ID)) {
1987
+					$results = $this->_change_event_status($EVT_ID, $event_status);
1988
+					$success = $results !== false ? $success : false;
1989
+				} else {
1990
+					$msg = sprintf(
1991
+						esc_html__(
1992
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
1993
+							'event_espresso'
1994
+						),
1995
+						$EVT_ID
1996
+					);
1997
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1998
+					$success = false;
1999
+				}
2000
+			}
2001
+		} else {
2002
+			$success = false;
2003
+			$msg = esc_html__(
2004
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2005
+				'event_espresso'
2006
+			);
2007
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2008
+		}
2009
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2010
+		$success = $success ? 2 : false;
2011
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2012
+		$this->_redirect_after_action($success, 'Events', $action, array('action' => 'default'));
2013
+	}
2014
+
2015
+
2016
+
2017
+	/**
2018
+	 * _trash_or_restore_events
2019
+	 *
2020
+	 * @access  private
2021
+	 * @param  int    $EVT_ID
2022
+	 * @param  string $event_status
2023
+	 * @return bool
2024
+	 */
2025
+	private function _change_event_status($EVT_ID = 0, $event_status = '')
2026
+	{
2027
+		// grab event id
2028
+		if ( ! $EVT_ID) {
2029
+			$msg = esc_html__(
2030
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2031
+				'event_espresso'
2032
+			);
2033
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2034
+			return false;
2035
+		}
2036
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2037
+		// clean status
2038
+		$event_status = sanitize_key($event_status);
2039
+		// grab status
2040
+		if (empty($event_status)) {
2041
+			$msg = esc_html__(
2042
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2043
+				'event_espresso'
2044
+			);
2045
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2046
+			return false;
2047
+		}
2048
+		// was event trashed or restored ?
2049
+		switch ($event_status) {
2050
+			case 'draft' :
2051
+				$action = 'restored from the trash';
2052
+				$hook = 'AHEE_event_restored_from_trash';
2053
+				break;
2054
+			case 'trash' :
2055
+				$action = 'moved to the trash';
2056
+				$hook = 'AHEE_event_moved_to_trash';
2057
+				break;
2058
+			default :
2059
+				$action = 'updated';
2060
+				$hook = false;
2061
+		}
2062
+		//use class to change status
2063
+		$this->_cpt_model_obj->set_status($event_status);
2064
+		$success = $this->_cpt_model_obj->save();
2065
+		if ($success === false) {
2066
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2067
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2068
+			return false;
2069
+		}
2070
+		if ($hook) {
2071
+			do_action($hook);
2072
+		}
2073
+		return true;
2074
+	}
2075
+
2076
+
2077
+
2078
+	/**
2079
+	 * _delete_event
2080
+	 *
2081
+	 * @access protected
2082
+	 * @param bool $redirect_after
2083
+	 */
2084
+	protected function _delete_event($redirect_after = true)
2085
+	{
2086
+		//determine the event id and set to array.
2087
+		$EVT_ID = isset($this->_req_data['EVT_ID']) ? absint($this->_req_data['EVT_ID']) : null;
2088
+		$EVT_ID = isset($this->_req_data['post']) ? absint($this->_req_data['post']) : $EVT_ID;
2089
+		// loop thru events
2090
+		if ($EVT_ID) {
2091
+			$success = $this->_permanently_delete_event($EVT_ID);
2092
+			// get list of events with no prices
2093
+			$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', array());
2094
+			// remove this event from the list of events with no prices
2095
+			if (isset($espresso_no_ticket_prices[$EVT_ID])) {
2096
+				unset($espresso_no_ticket_prices[$EVT_ID]);
2097
+			}
2098
+			update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
2099
+		} else {
2100
+			$success = false;
2101
+			$msg = esc_html__(
2102
+				'An error occurred. An event could not be deleted because a valid event ID was not not supplied.',
2103
+				'event_espresso'
2104
+			);
2105
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2106
+		}
2107
+		if ($redirect_after) {
2108
+			$this->_redirect_after_action(
2109
+				$success,
2110
+				'Event',
2111
+				'deleted',
2112
+				array('action' => 'default', 'status' => 'trash')
2113
+			);
2114
+		}
2115
+	}
2116
+
2117
+
2118
+
2119
+	/**
2120
+	 * _delete_events
2121
+	 *
2122
+	 * @access protected
2123
+	 * @return void
2124
+	 */
2125
+	protected function _delete_events()
2126
+	{
2127
+		$success = true;
2128
+		// get list of events with no prices
2129
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', array());
2130
+		//determine the event id and set to array.
2131
+		$EVT_IDs = isset($this->_req_data['EVT_IDs']) ? (array)$this->_req_data['EVT_IDs'] : array();
2132
+		// loop thru events
2133
+		foreach ($EVT_IDs as $EVT_ID) {
2134
+			$EVT_ID = absint($EVT_ID);
2135
+			if ($EVT_ID) {
2136
+				$results = $this->_permanently_delete_event($EVT_ID);
2137
+				$success = $results !== false ? $success : false;
2138
+				// remove this event from the list of events with no prices
2139
+				unset($espresso_no_ticket_prices[$EVT_ID]);
2140
+			} else {
2141
+				$success = false;
2142
+				$msg = esc_html__(
2143
+					'An error occurred. An event could not be deleted because a valid event ID was not not supplied.',
2144
+					'event_espresso'
2145
+				);
2146
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2147
+			}
2148
+		}
2149
+		update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
2150
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2151
+		$success = $success ? 2 : false;
2152
+		$this->_redirect_after_action($success, 'Events', 'deleted', array('action' => 'default'));
2153
+	}
2154
+
2155
+
2156
+
2157
+	/**
2158
+	 * _permanently_delete_event
2159
+	 *
2160
+	 * @access  private
2161
+	 * @param  int $EVT_ID
2162
+	 * @return bool
2163
+	 */
2164
+	private function _permanently_delete_event($EVT_ID = 0)
2165
+	{
2166
+		// grab event id
2167
+		if ( ! $EVT_ID) {
2168
+			$msg = esc_html__(
2169
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2170
+				'event_espresso'
2171
+			);
2172
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2173
+			return false;
2174
+		}
2175
+		if (
2176
+			! $this->_cpt_model_obj instanceof EE_Event
2177
+			|| $this->_cpt_model_obj->ID() !== $EVT_ID
2178
+		) {
2179
+			$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2180
+		}
2181
+		if ( ! $this->_cpt_model_obj instanceof EE_Event) {
2182
+			return false;
2183
+		}
2184
+		//need to delete related tickets and prices first.
2185
+		$datetimes = $this->_cpt_model_obj->get_many_related('Datetime');
2186
+		foreach ($datetimes as $datetime) {
2187
+			$this->_cpt_model_obj->_remove_relation_to($datetime, 'Datetime');
2188
+			$tickets = $datetime->get_many_related('Ticket');
2189
+			foreach ($tickets as $ticket) {
2190
+				$ticket->_remove_relation_to($datetime, 'Datetime');
2191
+				$ticket->delete_related_permanently('Price');
2192
+				$ticket->delete_permanently();
2193
+			}
2194
+			$datetime->delete();
2195
+		}
2196
+		//what about related venues or terms?
2197
+		$venues = $this->_cpt_model_obj->get_many_related('Venue');
2198
+		foreach ($venues as $venue) {
2199
+			$this->_cpt_model_obj->_remove_relation_to($venue, 'Venue');
2200
+		}
2201
+		//any attached question groups?
2202
+		$question_groups = $this->_cpt_model_obj->get_many_related('Question_Group');
2203
+		if ( ! empty($question_groups)) {
2204
+			foreach ($question_groups as $question_group) {
2205
+				$this->_cpt_model_obj->_remove_relation_to($question_group, 'Question_Group');
2206
+			}
2207
+		}
2208
+		//Message Template Groups
2209
+		$this->_cpt_model_obj->_remove_relations('Message_Template_Group');
2210
+		/** @type EE_Term_Taxonomy[] $term_taxonomies */
2211
+		$term_taxonomies = $this->_cpt_model_obj->term_taxonomies();
2212
+		foreach ($term_taxonomies as $term_taxonomy) {
2213
+			$this->_cpt_model_obj->remove_relation_to_term_taxonomy($term_taxonomy);
2214
+		}
2215
+		$success = $this->_cpt_model_obj->delete_permanently();
2216
+		// did it all go as planned ?
2217
+		if ($success) {
2218
+			$msg = sprintf(esc_html__('Event ID # %d has been deleted.', 'event_espresso'), $EVT_ID);
2219
+			EE_Error::add_success($msg);
2220
+		} else {
2221
+			$msg = sprintf(
2222
+				esc_html__('An error occurred. Event ID # %d could not be deleted.', 'event_espresso'),
2223
+				$EVT_ID
2224
+			);
2225
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2226
+			return false;
2227
+		}
2228
+		do_action('AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted', $EVT_ID);
2229
+		return true;
2230
+	}
2231
+
2232
+
2233
+
2234
+	/**
2235
+	 * get total number of events
2236
+	 *
2237
+	 * @access public
2238
+	 * @return int
2239
+	 */
2240
+	public function total_events()
2241
+	{
2242
+		$count = EEM_Event::instance()->count(array('caps' => 'read_admin'), 'EVT_ID', true);
2243
+		return $count;
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * get total number of draft events
2250
+	 *
2251
+	 * @access public
2252
+	 * @return int
2253
+	 */
2254
+	public function total_events_draft()
2255
+	{
2256
+		$where = array(
2257
+			'status' => array('IN', array('draft', 'auto-draft')),
2258
+		);
2259
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2260
+		return $count;
2261
+	}
2262
+
2263
+
2264
+
2265
+	/**
2266
+	 * get total number of trashed events
2267
+	 *
2268
+	 * @access public
2269
+	 * @return int
2270
+	 */
2271
+	public function total_trashed_events()
2272
+	{
2273
+		$where = array(
2274
+			'status' => 'trash',
2275
+		);
2276
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
2277
+		return $count;
2278
+	}
2279
+
2280
+
2281
+	/**
2282
+	 *    _default_event_settings
2283
+	 *    This generates the Default Settings Tab
2284
+	 *
2285
+	 * @return void
2286
+	 * @throws EE_Error
2287
+	 */
2288
+	protected function _default_event_settings()
2289
+	{
2290
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2291
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
2292
+		$this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2293
+		$this->display_admin_page_with_sidebar();
2294
+	}
2295
+
2296
+
2297
+	/**
2298
+	 * Return the form for event settings.
2299
+	 * @return EE_Form_Section_Proper
2300
+	 */
2301
+	protected function _default_event_settings_form()
2302
+	{
2303
+		$registration_config = EE_Registry::instance()->CFG->registration;
2304
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2305
+		//exclude
2306
+			array(
2307
+				EEM_Registration::status_id_cancelled,
2308
+				EEM_Registration::status_id_declined,
2309
+				EEM_Registration::status_id_incomplete,
2310
+				EEM_Registration::status_id_wait_list,
2311
+			),
2312
+			true
2313
+		);
2314
+		return new EE_Form_Section_Proper(
2315
+			array(
2316
+				'name' => 'update_default_event_settings',
2317
+				'html_id' => 'update_default_event_settings',
2318
+				'html_class' => 'form-table',
2319
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2320
+				'subsections' => apply_filters(
2321
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2322
+					array(
2323
+						'default_reg_status' => new EE_Select_Input(
2324
+							$registration_stati_for_selection,
2325
+							array(
2326
+								'default' => isset($registration_config->default_STS_ID)
2327
+											 && array_key_exists(
2328
+												$registration_config->default_STS_ID,
2329
+												$registration_stati_for_selection
2330
+											 )
2331
+											? sanitize_text_field($registration_config->default_STS_ID)
2332
+											: EEM_Registration::status_id_pending_payment,
2333
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2334
+													. EEH_Template::get_help_tab_link(
2335
+														'default_settings_status_help_tab'
2336
+													),
2337
+								'html_help_text' => esc_html__(
2338
+									'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.',
2339
+									'event_espresso'
2340
+								)
2341
+							)
2342
+						),
2343
+						'default_max_tickets' => new EE_Integer_Input(
2344
+							array(
2345
+								'default' => isset($registration_config->default_maximum_number_of_tickets)
2346
+									? $registration_config->default_maximum_number_of_tickets
2347
+									: EEM_Event::get_default_additional_limit(),
2348
+								'html_label_text' => esc_html__(
2349
+									'Default Maximum Tickets Allowed Per Order:',
2350
+									'event_espresso'
2351
+								) . EEH_Template::get_help_tab_link(
2352
+									'default_maximum_tickets_help_tab"'
2353
+									),
2354
+								'html_help_text' => esc_html__(
2355
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2356
+									'event_espresso'
2357
+								)
2358
+							)
2359
+						)
2360
+					)
2361
+				)
2362
+			)
2363
+		);
2364
+	}
2365
+
2366
+
2367
+	/**
2368
+	 * _update_default_event_settings
2369
+	 *
2370
+	 * @access protected
2371
+	 * @return void
2372
+	 * @throws EE_Error
2373
+	 */
2374
+	protected function _update_default_event_settings()
2375
+	{
2376
+		$registration_config = EE_Registry::instance()->CFG->registration;
2377
+		$form = $this->_default_event_settings_form();
2378
+		if ($form->was_submitted()) {
2379
+			$form->receive_form_submission();
2380
+			if ($form->is_valid()) {
2381
+				$valid_data = $form->valid_data();
2382
+				if (isset($valid_data['default_reg_status'])) {
2383
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2384
+				}
2385
+				if (isset($valid_data['default_max_tickets'])) {
2386
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2387
+				}
2388
+				//update because data was valid!
2389
+				EE_Registry::instance()->CFG->update_espresso_config();
2390
+				EE_Error::overwrite_success();
2391
+				EE_Error::add_success(
2392
+					__('Default Event Settings were updated', 'event_espresso')
2393
+				);
2394
+			}
2395
+		}
2396
+		$this->_redirect_after_action(0, '', '', array('action' => 'default_event_settings'), true);
2397
+	}
2398
+
2399
+
2400
+
2401
+	/*************        Templates        *************/
2402
+	protected function _template_settings()
2403
+	{
2404
+		$this->_admin_page_title = esc_html__('Template Settings (Preview)', 'event_espresso');
2405
+		$this->_template_args['preview_img'] = '<img src="'
2406
+											   . EVENTS_ASSETS_URL
2407
+											   . DS
2408
+											   . 'images'
2409
+											   . DS
2410
+											   . 'caffeinated_template_features.jpg" alt="'
2411
+											   . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2412
+											   . '" />';
2413
+		$this->_template_args['preview_text'] = '<strong>' . esc_html__(
2414
+				'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.',
2415
+				'event_espresso'
2416
+			) . '</strong>';
2417
+		$this->display_admin_caf_preview_page('template_settings_tab');
2418
+	}
2419
+
2420
+
2421
+	/** Event Category Stuff **/
2422
+	/**
2423
+	 * set the _category property with the category object for the loaded page.
2424
+	 *
2425
+	 * @access private
2426
+	 * @return void
2427
+	 */
2428
+	private function _set_category_object()
2429
+	{
2430
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2431
+			return;
2432
+		} //already have the category object so get out.
2433
+		//set default category object
2434
+		$this->_set_empty_category_object();
2435
+		//only set if we've got an id
2436
+		if ( ! isset($this->_req_data['EVT_CAT_ID'])) {
2437
+			return;
2438
+		}
2439
+		$category_id = absint($this->_req_data['EVT_CAT_ID']);
2440
+		$term = get_term($category_id, 'espresso_event_categories');
2441
+		if ( ! empty($term)) {
2442
+			$this->_category->category_name = $term->name;
2443
+			$this->_category->category_identifier = $term->slug;
2444
+			$this->_category->category_desc = $term->description;
2445
+			$this->_category->id = $term->term_id;
2446
+			$this->_category->parent = $term->parent;
2447
+		}
2448
+	}
2449
+
2450
+
2451
+	/**
2452
+	 * Clears out category properties.
2453
+	 */
2454
+	private function _set_empty_category_object()
2455
+	{
2456
+		$this->_category = new stdClass();
2457
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2458
+		$this->_category->id = $this->_category->parent = 0;
2459
+	}
2460
+
2461
+
2462
+	/**
2463
+	 * @throws EE_Error
2464
+	 */
2465
+	protected function _category_list_table()
2466
+	{
2467
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2468
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2469
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2470
+				'add_category',
2471
+				'add_category',
2472
+				array(),
2473
+				'add-new-h2'
2474
+			);
2475
+		$this->display_admin_list_table_page_with_sidebar();
2476
+	}
2477
+
2478
+
2479
+
2480
+	/**
2481
+	 * Output category details view.
2482
+	 */
2483
+	protected function _category_details($view)
2484
+	{
2485
+		//load formatter helper
2486
+		//load field generator helper
2487
+		$route = $view == 'edit' ? 'update_category' : 'insert_category';
2488
+		$this->_set_add_edit_form_tags($route);
2489
+		$this->_set_category_object();
2490
+		$id = ! empty($this->_category->id) ? $this->_category->id : '';
2491
+		$delete_action = 'delete_category';
2492
+		//custom redirect
2493
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2494
+			array('action' => 'category_list'),
2495
+			$this->_admin_base_url
2496
+		);
2497
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2498
+		//take care of contents
2499
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2500
+		$this->display_admin_page_with_sidebar();
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Output category details content.
2507
+	 */
2508
+	protected function _category_details_content()
2509
+	{
2510
+		$editor_args['category_desc'] = array(
2511
+			'type'          => 'wp_editor',
2512
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2513
+			'class'         => 'my_editor_custom',
2514
+			'wpeditor_args' => array('media_buttons' => false),
2515
+		);
2516
+		$_wp_editor = $this->_generate_admin_form_fields($editor_args, 'array');
2517
+		$all_terms = get_terms(
2518
+			array('espresso_event_categories'),
2519
+			array('hide_empty' => 0, 'exclude' => array($this->_category->id))
2520
+		);
2521
+		//setup category select for term parents.
2522
+		$category_select_values[] = array(
2523
+			'text' => esc_html__('No Parent', 'event_espresso'),
2524
+			'id'   => 0,
2525
+		);
2526
+		foreach ($all_terms as $term) {
2527
+			$category_select_values[] = array(
2528
+				'text' => $term->name,
2529
+				'id'   => $term->term_id,
2530
+			);
2531
+		}
2532
+		$category_select = EEH_Form_Fields::select_input(
2533
+			'category_parent',
2534
+			$category_select_values,
2535
+			$this->_category->parent
2536
+		);
2537
+		$template_args = array(
2538
+			'category'                 => $this->_category,
2539
+			'category_select'          => $category_select,
2540
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2541
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2542
+			'disable'                  => '',
2543
+			'disabled_message'         => false,
2544
+		);
2545
+		$template = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2546
+		return EEH_Template::display_template($template, $template_args, true);
2547
+	}
2548
+
2549
+
2550
+	/**
2551
+	 * Handles deleting categories.
2552
+	 */
2553
+	protected function _delete_categories()
2554
+	{
2555
+		$cat_ids = isset($this->_req_data['EVT_CAT_ID']) ? (array)$this->_req_data['EVT_CAT_ID']
2556
+			: (array)$this->_req_data['category_id'];
2557
+		foreach ($cat_ids as $cat_id) {
2558
+			$this->_delete_category($cat_id);
2559
+		}
2560
+		//doesn't matter what page we're coming from... we're going to the same place after delete.
2561
+		$query_args = array(
2562
+			'action' => 'category_list',
2563
+		);
2564
+		$this->_redirect_after_action(0, '', '', $query_args);
2565
+	}
2566
+
2567
+
2568
+
2569
+	/**
2570
+	 * Handles deleting specific category.
2571
+	 * @param int $cat_id
2572
+	 */
2573
+	protected function _delete_category($cat_id)
2574
+	{
2575
+		$cat_id = absint($cat_id);
2576
+		wp_delete_term($cat_id, 'espresso_event_categories');
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Handles triggering the update or insertion of a new category.
2583
+	 * @param bool $new_category  true means we're triggering the insert of a new category.
2584
+	 */
2585
+	protected function _insert_or_update_category($new_category)
2586
+	{
2587
+		$cat_id = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2588
+		$success = 0; //we already have a success message so lets not send another.
2589
+		if ($cat_id) {
2590
+			$query_args = array(
2591
+				'action'     => 'edit_category',
2592
+				'EVT_CAT_ID' => $cat_id,
2593
+			);
2594
+		} else {
2595
+			$query_args = array('action' => 'add_category');
2596
+		}
2597
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2598
+	}
2599
+
2600
+
2601
+
2602
+	/**
2603
+	 * Inserts or updates category
2604
+	 * @param bool $update (true indicates we're updating a category).
2605
+	 * @return bool|mixed|string
2606
+	 */
2607
+	private function _insert_category($update = false)
2608
+	{
2609
+		$cat_id = $update ? $this->_req_data['EVT_CAT_ID'] : '';
2610
+		$category_name = isset($this->_req_data['category_name']) ? $this->_req_data['category_name'] : '';
2611
+		$category_desc = isset($this->_req_data['category_desc']) ? $this->_req_data['category_desc'] : '';
2612
+		$category_parent = isset($this->_req_data['category_parent']) ? $this->_req_data['category_parent'] : 0;
2613
+		if (empty($category_name)) {
2614
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2615
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2616
+			return false;
2617
+		}
2618
+		$term_args = array(
2619
+			'name'        => $category_name,
2620
+			'description' => $category_desc,
2621
+			'parent'      => $category_parent,
2622
+		);
2623
+		//was the category_identifier input disabled?
2624
+		if (isset($this->_req_data['category_identifier'])) {
2625
+			$term_args['slug'] = $this->_req_data['category_identifier'];
2626
+		}
2627
+		$insert_ids = $update
2628
+			? wp_update_term($cat_id, 'espresso_event_categories', $term_args)
2629
+			: wp_insert_term($category_name, 'espresso_event_categories', $term_args);
2630
+		if ( ! is_array($insert_ids)) {
2631
+			$msg = esc_html__(
2632
+				'An error occurred and the category has not been saved to the database.',
2633
+				'event_espresso'
2634
+			);
2635
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2636
+		} else {
2637
+			$cat_id = $insert_ids['term_id'];
2638
+			$msg = sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2639
+			EE_Error::add_success($msg);
2640
+		}
2641
+		return $cat_id;
2642
+	}
2643
+
2644
+
2645
+
2646
+	/**
2647
+	 * Gets categories or count of categories matching the arguments in the request.
2648
+	 * @param int  $per_page
2649
+	 * @param int  $current_page
2650
+	 * @param bool $count
2651
+	 * @return EE_Base_Class[]|EE_Term_Taxonomy[]|int
2652
+	 */
2653
+	public function get_categories($per_page = 10, $current_page = 1, $count = false)
2654
+	{
2655
+		//testing term stuff
2656
+		$orderby = isset($this->_req_data['orderby']) ? $this->_req_data['orderby'] : 'Term.term_id';
2657
+		$order = isset($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2658
+		$limit = ($current_page - 1) * $per_page;
2659
+		$where = array('taxonomy' => 'espresso_event_categories');
2660
+		if (isset($this->_req_data['s'])) {
2661
+			$sstr = '%' . $this->_req_data['s'] . '%';
2662
+			$where['OR'] = array(
2663
+				'Term.name'   => array('LIKE', $sstr),
2664
+				'description' => array('LIKE', $sstr),
2665
+			);
2666
+		}
2667
+		$query_params = array(
2668
+			$where,
2669
+			'order_by'   => array($orderby => $order),
2670
+			'limit'      => $limit . ',' . $per_page,
2671
+			'force_join' => array('Term'),
2672
+		);
2673
+		$categories = $count
2674
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2675
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2676
+		return $categories;
2677
+	}
2678
+
2679
+	/* end category stuff */
2680
+	/**************/
2681
+
2682
+
2683
+	/**
2684
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function save_timezonestring_setting()
2688
+	{
2689
+		$timezone_string = isset($this->_req_data['timezone_selected'])
2690
+			? $this->_req_data['timezone_selected']
2691
+			: '';
2692
+		if  (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false))
2693
+		{
2694
+			EE_Error::add_error(
2695
+				esc_html('An invalid timezone string submitted.', 'event_espresso'),
2696
+				__FILE__, __FUNCTION__, __LINE__
2697
+			);
2698
+			$this->_template_args['error'] = true;
2699
+			$this->_return_json();
2700
+		}
2701
+
2702
+		update_option('timezone_string', $timezone_string);
2703
+		EE_Error::add_success(
2704
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2705
+		);
2706
+		$this->_template_args['success'] = true;
2707
+		$this->_return_json(true, array('action' => 'create_new'));
2708
+	}
2709 2709
 }
2710 2710
 //end class Events_Admin_Page
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
156 156
         } else {
157 157
             //set default formats for date and time
158
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
159
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
158
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
159
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
160 160
         }
161 161
         //if db model is instantiating
162 162
         if ($bydb) {
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
      */
479 479
     public function get_format($full = true)
480 480
     {
481
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
481
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
482 482
     }
483 483
 
484 484
 
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
         $model = $this->get_model();
588 588
         $model->field_settings_for($fieldname);
589 589
         $cache_type = $pretty ? 'pretty' : 'standard';
590
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
590
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
591 591
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
592 592
             return $this->_cached_properties[$fieldname][$cache_type];
593 593
         }
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
         $current_cache_id = ''
803 803
     ) {
804 804
         // verify that incoming object is of the correct type
805
-        $obj_class = 'EE_' . $relationName;
805
+        $obj_class = 'EE_'.$relationName;
806 806
         if ($newly_saved_object instanceof $obj_class) {
807 807
             /* @type EE_Base_Class $newly_saved_object */
808 808
             // now get the type of relation
@@ -1288,7 +1288,7 @@  discard block
 block discarded – undo
1288 1288
      */
1289 1289
     public function get_i18n_datetime($field_name, $format = '')
1290 1290
     {
1291
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1291
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1292 1292
         return date_i18n(
1293 1293
             $format,
1294 1294
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1426,8 +1426,8 @@  discard block
 block discarded – undo
1426 1426
         }
1427 1427
         $original_timezone = $this->_timezone;
1428 1428
         $this->set_timezone($timezone);
1429
-        $fn = (array)$field_name;
1430
-        $args = array_merge($fn, (array)$args);
1429
+        $fn = (array) $field_name;
1430
+        $args = array_merge($fn, (array) $args);
1431 1431
         if ( ! method_exists($this, $callback)) {
1432 1432
             throw new EE_Error(
1433 1433
                 sprintf(
@@ -1439,8 +1439,8 @@  discard block
 block discarded – undo
1439 1439
                 )
1440 1440
             );
1441 1441
         }
1442
-        $args = (array)$args;
1443
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1442
+        $args = (array) $args;
1443
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1444 1444
         $this->set_timezone($original_timezone);
1445 1445
         return $return;
1446 1446
     }
@@ -1579,14 +1579,14 @@  discard block
 block discarded – undo
1579 1579
          * @param array         $set_cols_n_values
1580 1580
          * @param EE_Base_Class $model_object
1581 1581
          */
1582
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1582
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1583 1583
             $this);
1584 1584
         //set attributes as provided in $set_cols_n_values
1585 1585
         foreach ($set_cols_n_values as $column => $value) {
1586 1586
             $this->set($column, $value);
1587 1587
         }
1588 1588
         // no changes ? then don't do anything
1589
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1589
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1590 1590
             return 0;
1591 1591
         }
1592 1592
         /**
@@ -1638,8 +1638,8 @@  discard block
 block discarded – undo
1638 1638
                                 __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1639 1639
                                     'event_espresso'),
1640 1640
                                 get_class($this),
1641
-                                get_class($model) . '::instance()->add_to_entity_map()',
1642
-                                get_class($model) . '::instance()->get_one_by_ID()',
1641
+                                get_class($model).'::instance()->add_to_entity_map()',
1642
+                                get_class($model).'::instance()->get_one_by_ID()',
1643 1643
                                 '<br />'
1644 1644
                             )
1645 1645
                         );
@@ -1772,7 +1772,7 @@  discard block
 block discarded – undo
1772 1772
      */
1773 1773
     public function get_model()
1774 1774
     {
1775
-        if( ! $this->_model){
1775
+        if ( ! $this->_model) {
1776 1776
             $modelName = self::_get_model_classname(get_class($this));
1777 1777
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1778 1778
         } else {
@@ -1915,7 +1915,7 @@  discard block
 block discarded – undo
1915 1915
         if (strpos($model_name, "EE_") === 0) {
1916 1916
             $model_classname = str_replace("EE_", "EEM_", $model_name);
1917 1917
         } else {
1918
-            $model_classname = "EEM_" . $model_name;
1918
+            $model_classname = "EEM_".$model_name;
1919 1919
         }
1920 1920
         return $model_classname;
1921 1921
     }
@@ -2302,7 +2302,7 @@  discard block
 block discarded – undo
2302 2302
      */
2303 2303
     protected function _property_exists($properties)
2304 2304
     {
2305
-        foreach ((array)$properties as $property_name) {
2305
+        foreach ((array) $properties as $property_name) {
2306 2306
             //first make sure this property exists
2307 2307
             if ( ! $this->_fields[$property_name]) {
2308 2308
                 throw new EE_Error(
@@ -2632,8 +2632,8 @@  discard block
 block discarded – undo
2632 2632
                         __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2633 2633
                             'event_espresso'),
2634 2634
                         $this->ID(),
2635
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2636
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2635
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2636
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2637 2637
                     )
2638 2638
                 );
2639 2639
             }
@@ -2693,7 +2693,7 @@  discard block
 block discarded – undo
2693 2693
         $model = $this->get_model();
2694 2694
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2695 2695
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2696
-                $classname = 'EE_' . $model->get_this_model_name();
2696
+                $classname = 'EE_'.$model->get_this_model_name();
2697 2697
                 if (
2698 2698
                     $this->get_one_from_cache($relation_name) instanceof $classname
2699 2699
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.
Indentation   +2709 added lines, -2709 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2714 +25,2714 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-    /**
109
-     * @var boolean indicating whether or not this model object's properties have changed since construction
110
-     */
111
-    protected $_has_changes = false;
112
-
113
-    /**
114
-     * @var EEM_Base
115
-     */
116
-    protected $_model;
117
-
118
-
119
-
120
-    /**
121
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
-     * play nice
123
-     *
124
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
-     *                                                         TXN_amount, QST_name, etc) and values are their values
127
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
-     *                                                         corresponding db model or not.
129
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
-     *                                                         be in when instantiating a EE_Base_Class object.
131
-     * @param array   $date_formats                            An array of date formats to set on construct where first
132
-     *                                                         value is the date_format and second value is the time
133
-     *                                                         format.
134
-     * @throws EE_Error
135
-     */
136
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
137
-    {
138
-        $className = get_class($this);
139
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
140
-        $model = $this->get_model();
141
-        $model_fields = $model->field_settings(false);
142
-        // ensure $fieldValues is an array
143
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
144
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
145
-        // verify client code has not passed any invalid field names
146
-        foreach ($fieldValues as $field_name => $field_value) {
147
-            if ( ! isset($model_fields[$field_name])) {
148
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
149
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
150
-            }
151
-        }
152
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
153
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
-        if ( ! empty($date_formats) && is_array($date_formats)) {
155
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
156
-        } else {
157
-            //set default formats for date and time
158
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
159
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
160
-        }
161
-        //if db model is instantiating
162
-        if ($bydb) {
163
-            //client code has indicated these field values are from the database
164
-            foreach ($model_fields as $fieldName => $field) {
165
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
166
-            }
167
-        } else {
168
-            //we're constructing a brand
169
-            //new instance of the model object. Generally, this means we'll need to do more field validation
170
-            foreach ($model_fields as $fieldName => $field) {
171
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
172
-            }
173
-        }
174
-        //remember what values were passed to this constructor
175
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
176
-        //remember in entity mapper
177
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
178
-            $model->add_to_entity_map($this);
179
-        }
180
-        //setup all the relations
181
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
182
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
183
-                $this->_model_relations[$relation_name] = null;
184
-            } else {
185
-                $this->_model_relations[$relation_name] = array();
186
-            }
187
-        }
188
-        /**
189
-         * Action done at the end of each model object construction
190
-         *
191
-         * @param EE_Base_Class $this the model object just created
192
-         */
193
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
200
-     *
201
-     * @return boolean
202
-     */
203
-    public function allow_persist()
204
-    {
205
-        return $this->_allow_persist;
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     * Sets whether or not this model object should be allowed to be saved to the DB.
212
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
-     * you got new information that somehow made you change your mind.
214
-     *
215
-     * @param boolean $allow_persist
216
-     * @return boolean
217
-     */
218
-    public function set_allow_persist($allow_persist)
219
-    {
220
-        return $this->_allow_persist = $allow_persist;
221
-    }
222
-
223
-
224
-
225
-    /**
226
-     * Gets the field's original value when this object was constructed during this request.
227
-     * This can be helpful when determining if a model object has changed or not
228
-     *
229
-     * @param string $field_name
230
-     * @return mixed|null
231
-     * @throws \EE_Error
232
-     */
233
-    public function get_original($field_name)
234
-    {
235
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
236
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
237
-        ) {
238
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
239
-        } else {
240
-            return null;
241
-        }
242
-    }
243
-
244
-
245
-
246
-    /**
247
-     * @param EE_Base_Class $obj
248
-     * @return string
249
-     */
250
-    public function get_class($obj)
251
-    {
252
-        return get_class($obj);
253
-    }
254
-
255
-
256
-
257
-    /**
258
-     * Overrides parent because parent expects old models.
259
-     * This also doesn't do any validation, and won't work for serialized arrays
260
-     *
261
-     * @param    string $field_name
262
-     * @param    mixed  $field_value
263
-     * @param bool      $use_default
264
-     * @throws \EE_Error
265
-     */
266
-    public function set($field_name, $field_value, $use_default = false)
267
-    {
268
-        // if not using default and nothing has changed, and object has already been setup (has ID),
269
-        // then don't do anything
270
-        if (
271
-            ! $use_default
272
-            && $this->_fields[$field_name] === $field_value
273
-            && $this->ID()
274
-        ) {
275
-            return;
276
-        }
277
-        $model = $this->get_model();
278
-        $this->_has_changes = true;
279
-        $field_obj = $model->field_settings_for($field_name);
280
-        if ($field_obj instanceof EE_Model_Field_Base) {
281
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
282
-            if ($field_obj instanceof EE_Datetime_Field) {
283
-                $field_obj->set_timezone($this->_timezone);
284
-                $field_obj->set_date_format($this->_dt_frmt);
285
-                $field_obj->set_time_format($this->_tm_frmt);
286
-            }
287
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
288
-            //should the value be null?
289
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
290
-                $this->_fields[$field_name] = $field_obj->get_default_value();
291
-                /**
292
-                 * To save having to refactor all the models, if a default value is used for a
293
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
294
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
295
-                 * object.
296
-                 *
297
-                 * @since 4.6.10+
298
-                 */
299
-                if (
300
-                    $field_obj instanceof EE_Datetime_Field
301
-                    && $this->_fields[$field_name] !== null
302
-                    && ! $this->_fields[$field_name] instanceof DateTime
303
-                ) {
304
-                    empty($this->_fields[$field_name])
305
-                        ? $this->set($field_name, time())
306
-                        : $this->set($field_name, $this->_fields[$field_name]);
307
-                }
308
-            } else {
309
-                $this->_fields[$field_name] = $holder_of_value;
310
-            }
311
-            //if we're not in the constructor...
312
-            //now check if what we set was a primary key
313
-            if (
314
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
-                $this->_props_n_values_provided_in_constructor
316
-                && $field_value
317
-                && $field_name === $model->primary_key_name()
318
-            ) {
319
-                //if so, we want all this object's fields to be filled either with
320
-                //what we've explicitly set on this model
321
-                //or what we have in the db
322
-                // echo "setting primary key!";
323
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
324
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
-                foreach ($fields_on_model as $field_obj) {
326
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
327
-                         && $field_obj->get_name() !== $field_name
328
-                    ) {
329
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
330
-                    }
331
-                }
332
-                //oh this model object has an ID? well make sure its in the entity mapper
333
-                $model->add_to_entity_map($this);
334
-            }
335
-            //let's unset any cache for this field_name from the $_cached_properties property.
336
-            $this->_clear_cached_property($field_name);
337
-        } else {
338
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
339
-                "event_espresso"), $field_name));
340
-        }
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * This sets the field value on the db column if it exists for the given $column_name or
347
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
348
-     *
349
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
350
-     * @param string $field_name  Must be the exact column name.
351
-     * @param mixed  $field_value The value to set.
352
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
353
-     * @throws \EE_Error
354
-     */
355
-    public function set_field_or_extra_meta($field_name, $field_value)
356
-    {
357
-        if ($this->get_model()->has_field($field_name)) {
358
-            $this->set($field_name, $field_value);
359
-            return true;
360
-        } else {
361
-            //ensure this object is saved first so that extra meta can be properly related.
362
-            $this->save();
363
-            return $this->update_extra_meta($field_name, $field_value);
364
-        }
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * This retrieves the value of the db column set on this class or if that's not present
371
-     * it will attempt to retrieve from extra_meta if found.
372
-     * Example Usage:
373
-     * Via EE_Message child class:
374
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
375
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
376
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
377
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
378
-     * value for those extra fields dynamically via the EE_message object.
379
-     *
380
-     * @param  string $field_name expecting the fully qualified field name.
381
-     * @return mixed|null  value for the field if found.  null if not found.
382
-     * @throws \EE_Error
383
-     */
384
-    public function get_field_or_extra_meta($field_name)
385
-    {
386
-        if ($this->get_model()->has_field($field_name)) {
387
-            $column_value = $this->get($field_name);
388
-        } else {
389
-            //This isn't a column in the main table, let's see if it is in the extra meta.
390
-            $column_value = $this->get_extra_meta($field_name, true, null);
391
-        }
392
-        return $column_value;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
399
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
400
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
401
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
402
-     *
403
-     * @access public
404
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
405
-     * @return void
406
-     * @throws \EE_Error
407
-     */
408
-    public function set_timezone($timezone = '')
409
-    {
410
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
411
-        //make sure we clear all cached properties because they won't be relevant now
412
-        $this->_clear_cached_properties();
413
-        //make sure we update field settings and the date for all EE_Datetime_Fields
414
-        $model_fields = $this->get_model()->field_settings(false);
415
-        foreach ($model_fields as $field_name => $field_obj) {
416
-            if ($field_obj instanceof EE_Datetime_Field) {
417
-                $field_obj->set_timezone($this->_timezone);
418
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
419
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
420
-                }
421
-            }
422
-        }
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * This just returns whatever is set for the current timezone.
429
-     *
430
-     * @access public
431
-     * @return string timezone string
432
-     */
433
-    public function get_timezone()
434
-    {
435
-        return $this->_timezone;
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * This sets the internal date format to what is sent in to be used as the new default for the class
442
-     * internally instead of wp set date format options
443
-     *
444
-     * @since 4.6
445
-     * @param string $format should be a format recognizable by PHP date() functions.
446
-     */
447
-    public function set_date_format($format)
448
-    {
449
-        $this->_dt_frmt = $format;
450
-        //clear cached_properties because they won't be relevant now.
451
-        $this->_clear_cached_properties();
452
-    }
453
-
454
-
455
-
456
-    /**
457
-     * This sets the internal time format string to what is sent in to be used as the new default for the
458
-     * class internally instead of wp set time format options.
459
-     *
460
-     * @since 4.6
461
-     * @param string $format should be a format recognizable by PHP date() functions.
462
-     */
463
-    public function set_time_format($format)
464
-    {
465
-        $this->_tm_frmt = $format;
466
-        //clear cached_properties because they won't be relevant now.
467
-        $this->_clear_cached_properties();
468
-    }
469
-
470
-
471
-
472
-    /**
473
-     * This returns the current internal set format for the date and time formats.
474
-     *
475
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
476
-     *                             where the first value is the date format and the second value is the time format.
477
-     * @return mixed string|array
478
-     */
479
-    public function get_format($full = true)
480
-    {
481
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * cache
488
-     * stores the passed model object on the current model object.
489
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
490
-     *
491
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
492
-     *                                       'Registration' associated with this model object
493
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
494
-     *                                       that could be a payment or a registration)
495
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
496
-     *                                       items which will be stored in an array on this object
497
-     * @throws EE_Error
498
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
499
-     *                  related thing, no array)
500
-     */
501
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
502
-    {
503
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
504
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
505
-            return false;
506
-        }
507
-        // also get "how" the object is related, or throw an error
508
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
509
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
510
-                $relationName, get_class($this)));
511
-        }
512
-        // how many things are related ?
513
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
514
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
515
-            // so for these model objects just set it to be cached
516
-            $this->_model_relations[$relationName] = $object_to_cache;
517
-            $return = true;
518
-        } else {
519
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
520
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
521
-            if ( ! is_array($this->_model_relations[$relationName])) {
522
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
523
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
524
-                    ? array($this->_model_relations[$relationName]) : array();
525
-            }
526
-            // first check for a cache_id which is normally empty
527
-            if ( ! empty($cache_id)) {
528
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
529
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
530
-                $return = $cache_id;
531
-            } elseif ($object_to_cache->ID()) {
532
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
533
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
534
-                $return = $object_to_cache->ID();
535
-            } else {
536
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
537
-                $this->_model_relations[$relationName][] = $object_to_cache;
538
-                // move the internal pointer to the end of the array
539
-                end($this->_model_relations[$relationName]);
540
-                // and grab the key so that we can return it
541
-                $return = key($this->_model_relations[$relationName]);
542
-            }
543
-        }
544
-        return $return;
545
-    }
546
-
547
-
548
-
549
-    /**
550
-     * For adding an item to the cached_properties property.
551
-     *
552
-     * @access protected
553
-     * @param string      $fieldname the property item the corresponding value is for.
554
-     * @param mixed       $value     The value we are caching.
555
-     * @param string|null $cache_type
556
-     * @return void
557
-     * @throws \EE_Error
558
-     */
559
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
560
-    {
561
-        //first make sure this property exists
562
-        $this->get_model()->field_settings_for($fieldname);
563
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
564
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
565
-    }
566
-
567
-
568
-
569
-    /**
570
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
571
-     * This also SETS the cache if we return the actual property!
572
-     *
573
-     * @param string $fieldname        the name of the property we're trying to retrieve
574
-     * @param bool   $pretty
575
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
576
-     *                                 (in cases where the same property may be used for different outputs
577
-     *                                 - i.e. datetime, money etc.)
578
-     *                                 It can also accept certain pre-defined "schema" strings
579
-     *                                 to define how to output the property.
580
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
581
-     * @return mixed                   whatever the value for the property is we're retrieving
582
-     * @throws \EE_Error
583
-     */
584
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
585
-    {
586
-        //verify the field exists
587
-        $model = $this->get_model();
588
-        $model->field_settings_for($fieldname);
589
-        $cache_type = $pretty ? 'pretty' : 'standard';
590
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
591
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
592
-            return $this->_cached_properties[$fieldname][$cache_type];
593
-        }
594
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
595
-        $this->_set_cached_property($fieldname, $value, $cache_type);
596
-        return $value;
597
-    }
598
-
599
-
600
-
601
-    /**
602
-     * If the cache didn't fetch the needed item, this fetches it.
603
-     * @param string $fieldname
604
-     * @param bool $pretty
605
-     * @param string $extra_cache_ref
606
-     * @return mixed
607
-     */
608
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
609
-    {
610
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
611
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
612
-        if ($field_obj instanceof EE_Datetime_Field) {
613
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
614
-        }
615
-        if ( ! isset($this->_fields[$fieldname])) {
616
-            $this->_fields[$fieldname] = null;
617
-        }
618
-        $value = $pretty
619
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
620
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
621
-        return $value;
622
-    }
623
-
624
-
625
-
626
-    /**
627
-     * set timezone, formats, and output for EE_Datetime_Field objects
628
-     *
629
-     * @param \EE_Datetime_Field $datetime_field
630
-     * @param bool               $pretty
631
-     * @param null $date_or_time
632
-     * @return void
633
-     * @throws \EE_Error
634
-     */
635
-    protected function _prepare_datetime_field(
636
-        EE_Datetime_Field $datetime_field,
637
-        $pretty = false,
638
-        $date_or_time = null
639
-    ) {
640
-        $datetime_field->set_timezone($this->_timezone);
641
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
642
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
643
-        //set the output returned
644
-        switch ($date_or_time) {
645
-            case 'D' :
646
-                $datetime_field->set_date_time_output('date');
647
-                break;
648
-            case 'T' :
649
-                $datetime_field->set_date_time_output('time');
650
-                break;
651
-            default :
652
-                $datetime_field->set_date_time_output();
653
-        }
654
-    }
655
-
656
-
657
-
658
-    /**
659
-     * This just takes care of clearing out the cached_properties
660
-     *
661
-     * @return void
662
-     */
663
-    protected function _clear_cached_properties()
664
-    {
665
-        $this->_cached_properties = array();
666
-    }
667
-
668
-
669
-
670
-    /**
671
-     * This just clears out ONE property if it exists in the cache
672
-     *
673
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
674
-     * @return void
675
-     */
676
-    protected function _clear_cached_property($property_name)
677
-    {
678
-        if (isset($this->_cached_properties[$property_name])) {
679
-            unset($this->_cached_properties[$property_name]);
680
-        }
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * Ensures that this related thing is a model object.
687
-     *
688
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
689
-     * @param string $model_name   name of the related thing, eg 'Attendee',
690
-     * @return EE_Base_Class
691
-     * @throws \EE_Error
692
-     */
693
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
694
-    {
695
-        $other_model_instance = self::_get_model_instance_with_name(
696
-            self::_get_model_classname($model_name),
697
-            $this->_timezone
698
-        );
699
-        return $other_model_instance->ensure_is_obj($object_or_id);
700
-    }
701
-
702
-
703
-
704
-    /**
705
-     * Forgets the cached model of the given relation Name. So the next time we request it,
706
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
707
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
708
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
709
-     *
710
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
711
-     *                                                     Eg 'Registration'
712
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
713
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
714
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
715
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
716
-     *                                                     this is HasMany or HABTM.
717
-     * @throws EE_Error
718
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
719
-     *                       relation from all
720
-     */
721
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
722
-    {
723
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
724
-        $index_in_cache = '';
725
-        if ( ! $relationship_to_model) {
726
-            throw new EE_Error(
727
-                sprintf(
728
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
729
-                    $relationName,
730
-                    get_class($this)
731
-                )
732
-            );
733
-        }
734
-        if ($clear_all) {
735
-            $obj_removed = true;
736
-            $this->_model_relations[$relationName] = null;
737
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
738
-            $obj_removed = $this->_model_relations[$relationName];
739
-            $this->_model_relations[$relationName] = null;
740
-        } else {
741
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
742
-                && $object_to_remove_or_index_into_array->ID()
743
-            ) {
744
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
745
-                if (is_array($this->_model_relations[$relationName])
746
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
747
-                ) {
748
-                    $index_found_at = null;
749
-                    //find this object in the array even though it has a different key
750
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
751
-                        if (
752
-                            $obj instanceof EE_Base_Class
753
-                            && (
754
-                                $obj == $object_to_remove_or_index_into_array
755
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
756
-                            )
757
-                        ) {
758
-                            $index_found_at = $index;
759
-                            break;
760
-                        }
761
-                    }
762
-                    if ($index_found_at) {
763
-                        $index_in_cache = $index_found_at;
764
-                    } else {
765
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
766
-                        //if it wasn't in it to begin with. So we're done
767
-                        return $object_to_remove_or_index_into_array;
768
-                    }
769
-                }
770
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
771
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
772
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
773
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
774
-                        $index_in_cache = $index;
775
-                    }
776
-                }
777
-            } else {
778
-                $index_in_cache = $object_to_remove_or_index_into_array;
779
-            }
780
-            //supposedly we've found it. But it could just be that the client code
781
-            //provided a bad index/object
782
-            if (
783
-            isset(
784
-                $this->_model_relations[$relationName],
785
-                $this->_model_relations[$relationName][$index_in_cache]
786
-            )
787
-            ) {
788
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
789
-                unset($this->_model_relations[$relationName][$index_in_cache]);
790
-            } else {
791
-                //that thing was never cached anyways.
792
-                $obj_removed = null;
793
-            }
794
-        }
795
-        return $obj_removed;
796
-    }
797
-
798
-
799
-
800
-    /**
801
-     * update_cache_after_object_save
802
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
803
-     * obtained after being saved to the db
804
-     *
805
-     * @param string         $relationName       - the type of object that is cached
806
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
807
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
808
-     * @return boolean TRUE on success, FALSE on fail
809
-     * @throws \EE_Error
810
-     */
811
-    public function update_cache_after_object_save(
812
-        $relationName,
813
-        EE_Base_Class $newly_saved_object,
814
-        $current_cache_id = ''
815
-    ) {
816
-        // verify that incoming object is of the correct type
817
-        $obj_class = 'EE_' . $relationName;
818
-        if ($newly_saved_object instanceof $obj_class) {
819
-            /* @type EE_Base_Class $newly_saved_object */
820
-            // now get the type of relation
821
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
822
-            // if this is a 1:1 relationship
823
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
824
-                // then just replace the cached object with the newly saved object
825
-                $this->_model_relations[$relationName] = $newly_saved_object;
826
-                return true;
827
-                // or if it's some kind of sordid feral polyamorous relationship...
828
-            } elseif (is_array($this->_model_relations[$relationName])
829
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
830
-            ) {
831
-                // then remove the current cached item
832
-                unset($this->_model_relations[$relationName][$current_cache_id]);
833
-                // and cache the newly saved object using it's new ID
834
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
835
-                return true;
836
-            }
837
-        }
838
-        return false;
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
845
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
846
-     *
847
-     * @param string $relationName
848
-     * @return EE_Base_Class
849
-     */
850
-    public function get_one_from_cache($relationName)
851
-    {
852
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
853
-            : null;
854
-        if (is_array($cached_array_or_object)) {
855
-            return array_shift($cached_array_or_object);
856
-        } else {
857
-            return $cached_array_or_object;
858
-        }
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
865
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
866
-     *
867
-     * @param string $relationName
868
-     * @throws \EE_Error
869
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
870
-     */
871
-    public function get_all_from_cache($relationName)
872
-    {
873
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
874
-        // if the result is not an array, but exists, make it an array
875
-        $objects = is_array($objects) ? $objects : array($objects);
876
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
877
-        //basically, if this model object was stored in the session, and these cached model objects
878
-        //already have IDs, let's make sure they're in their model's entity mapper
879
-        //otherwise we will have duplicates next time we call
880
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
881
-        $model = EE_Registry::instance()->load_model($relationName);
882
-        foreach ($objects as $model_object) {
883
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
884
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
885
-                if ($model_object->ID()) {
886
-                    $model->add_to_entity_map($model_object);
887
-                }
888
-            } else {
889
-                throw new EE_Error(
890
-                    sprintf(
891
-                        __(
892
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
893
-                            'event_espresso'
894
-                        ),
895
-                        $relationName,
896
-                        gettype($model_object)
897
-                    )
898
-                );
899
-            }
900
-        }
901
-        return $objects;
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
908
-     * matching the given query conditions.
909
-     *
910
-     * @param null  $field_to_order_by  What field is being used as the reference point.
911
-     * @param int   $limit              How many objects to return.
912
-     * @param array $query_params       Any additional conditions on the query.
913
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
914
-     *                                  you can indicate just the columns you want returned
915
-     * @return array|EE_Base_Class[]
916
-     * @throws \EE_Error
917
-     */
918
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
919
-    {
920
-        $model = $this->get_model();
921
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
922
-            ? $model->get_primary_key_field()->get_name()
923
-            : $field_to_order_by;
924
-        $current_value = ! empty($field) ? $this->get($field) : null;
925
-        if (empty($field) || empty($current_value)) {
926
-            return array();
927
-        }
928
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
935
-     * matching the given query conditions.
936
-     *
937
-     * @param null  $field_to_order_by  What field is being used as the reference point.
938
-     * @param int   $limit              How many objects to return.
939
-     * @param array $query_params       Any additional conditions on the query.
940
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
941
-     *                                  you can indicate just the columns you want returned
942
-     * @return array|EE_Base_Class[]
943
-     * @throws \EE_Error
944
-     */
945
-    public function previous_x(
946
-        $field_to_order_by = null,
947
-        $limit = 1,
948
-        $query_params = array(),
949
-        $columns_to_select = null
950
-    ) {
951
-        $model = $this->get_model();
952
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
953
-            ? $model->get_primary_key_field()->get_name()
954
-            : $field_to_order_by;
955
-        $current_value = ! empty($field) ? $this->get($field) : null;
956
-        if (empty($field) || empty($current_value)) {
957
-            return array();
958
-        }
959
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
960
-    }
961
-
962
-
963
-
964
-    /**
965
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
966
-     * matching the given query conditions.
967
-     *
968
-     * @param null  $field_to_order_by  What field is being used as the reference point.
969
-     * @param array $query_params       Any additional conditions on the query.
970
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
971
-     *                                  you can indicate just the columns you want returned
972
-     * @return array|EE_Base_Class
973
-     * @throws \EE_Error
974
-     */
975
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
976
-    {
977
-        $model = $this->get_model();
978
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
979
-            ? $model->get_primary_key_field()->get_name()
980
-            : $field_to_order_by;
981
-        $current_value = ! empty($field) ? $this->get($field) : null;
982
-        if (empty($field) || empty($current_value)) {
983
-            return array();
984
-        }
985
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
992
-     * matching the given query conditions.
993
-     *
994
-     * @param null  $field_to_order_by  What field is being used as the reference point.
995
-     * @param array $query_params       Any additional conditions on the query.
996
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
997
-     *                                  you can indicate just the column you want returned
998
-     * @return array|EE_Base_Class
999
-     * @throws \EE_Error
1000
-     */
1001
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1002
-    {
1003
-        $model = $this->get_model();
1004
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1005
-            ? $model->get_primary_key_field()->get_name()
1006
-            : $field_to_order_by;
1007
-        $current_value = ! empty($field) ? $this->get($field) : null;
1008
-        if (empty($field) || empty($current_value)) {
1009
-            return array();
1010
-        }
1011
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1012
-    }
1013
-
1014
-
1015
-
1016
-    /**
1017
-     * Overrides parent because parent expects old models.
1018
-     * This also doesn't do any validation, and won't work for serialized arrays
1019
-     *
1020
-     * @param string $field_name
1021
-     * @param mixed  $field_value_from_db
1022
-     * @throws \EE_Error
1023
-     */
1024
-    public function set_from_db($field_name, $field_value_from_db)
1025
-    {
1026
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1027
-        if ($field_obj instanceof EE_Model_Field_Base) {
1028
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1029
-            //eg, a CPT model object could have an entry in the posts table, but no
1030
-            //entry in the meta table. Meaning that all its columns in the meta table
1031
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1032
-            if ($field_value_from_db === null) {
1033
-                if ($field_obj->is_nullable()) {
1034
-                    //if the field allows nulls, then let it be null
1035
-                    $field_value = null;
1036
-                } else {
1037
-                    $field_value = $field_obj->get_default_value();
1038
-                }
1039
-            } else {
1040
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1041
-            }
1042
-            $this->_fields[$field_name] = $field_value;
1043
-            $this->_clear_cached_property($field_name);
1044
-        }
1045
-    }
1046
-
1047
-
1048
-
1049
-    /**
1050
-     * verifies that the specified field is of the correct type
1051
-     *
1052
-     * @param string $field_name
1053
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1054
-     *                                (in cases where the same property may be used for different outputs
1055
-     *                                - i.e. datetime, money etc.)
1056
-     * @return mixed
1057
-     * @throws \EE_Error
1058
-     */
1059
-    public function get($field_name, $extra_cache_ref = null)
1060
-    {
1061
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1062
-    }
1063
-
1064
-
1065
-
1066
-    /**
1067
-     * This method simply returns the RAW unprocessed value for the given property in this class
1068
-     *
1069
-     * @param  string $field_name A valid fieldname
1070
-     * @return mixed              Whatever the raw value stored on the property is.
1071
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1072
-     */
1073
-    public function get_raw($field_name)
1074
-    {
1075
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1076
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1077
-            ? $this->_fields[$field_name]->format('U')
1078
-            : $this->_fields[$field_name];
1079
-    }
1080
-
1081
-
1082
-
1083
-    /**
1084
-     * This is used to return the internal DateTime object used for a field that is a
1085
-     * EE_Datetime_Field.
1086
-     *
1087
-     * @param string $field_name               The field name retrieving the DateTime object.
1088
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1089
-     * @throws \EE_Error
1090
-     *                                         an error is set and false returned.  If the field IS an
1091
-     *                                         EE_Datetime_Field and but the field value is null, then
1092
-     *                                         just null is returned (because that indicates that likely
1093
-     *                                         this field is nullable).
1094
-     */
1095
-    public function get_DateTime_object($field_name)
1096
-    {
1097
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1098
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1099
-            EE_Error::add_error(
1100
-                sprintf(
1101
-                    __(
1102
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1103
-                        'event_espresso'
1104
-                    ),
1105
-                    $field_name
1106
-                ),
1107
-                __FILE__,
1108
-                __FUNCTION__,
1109
-                __LINE__
1110
-            );
1111
-            return false;
1112
-        }
1113
-        return $this->_fields[$field_name];
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * To be used in template to immediately echo out the value, and format it for output.
1120
-     * Eg, should call stripslashes and whatnot before echoing
1121
-     *
1122
-     * @param string $field_name      the name of the field as it appears in the DB
1123
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1124
-     *                                (in cases where the same property may be used for different outputs
1125
-     *                                - i.e. datetime, money etc.)
1126
-     * @return void
1127
-     * @throws \EE_Error
1128
-     */
1129
-    public function e($field_name, $extra_cache_ref = null)
1130
-    {
1131
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1132
-    }
1133
-
1134
-
1135
-
1136
-    /**
1137
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1138
-     * can be easily used as the value of form input.
1139
-     *
1140
-     * @param string $field_name
1141
-     * @return void
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function f($field_name)
1145
-    {
1146
-        $this->e($field_name, 'form_input');
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1153
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1154
-     * to see what options are available.
1155
-     * @param string $field_name
1156
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
-     *                                (in cases where the same property may be used for different outputs
1158
-     *                                - i.e. datetime, money etc.)
1159
-     * @return mixed
1160
-     * @throws \EE_Error
1161
-     */
1162
-    public function get_pretty($field_name, $extra_cache_ref = null)
1163
-    {
1164
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1165
-    }
1166
-
1167
-
1168
-
1169
-    /**
1170
-     * This simply returns the datetime for the given field name
1171
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1172
-     * (and the equivalent e_date, e_time, e_datetime).
1173
-     *
1174
-     * @access   protected
1175
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1176
-     * @param string   $dt_frmt      valid datetime format used for date
1177
-     *                               (if '' then we just use the default on the field,
1178
-     *                               if NULL we use the last-used format)
1179
-     * @param string   $tm_frmt      Same as above except this is for time format
1180
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1181
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1182
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1183
-     *                               if field is not a valid dtt field, or void if echoing
1184
-     * @throws \EE_Error
1185
-     */
1186
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1187
-    {
1188
-        // clear cached property
1189
-        $this->_clear_cached_property($field_name);
1190
-        //reset format properties because they are used in get()
1191
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1192
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1193
-        if ($echo) {
1194
-            $this->e($field_name, $date_or_time);
1195
-            return '';
1196
-        }
1197
-        return $this->get($field_name, $date_or_time);
1198
-    }
1199
-
1200
-
1201
-
1202
-    /**
1203
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1204
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1205
-     * other echoes the pretty value for dtt)
1206
-     *
1207
-     * @param  string $field_name name of model object datetime field holding the value
1208
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1209
-     * @return string            datetime value formatted
1210
-     * @throws \EE_Error
1211
-     */
1212
-    public function get_date($field_name, $format = '')
1213
-    {
1214
-        return $this->_get_datetime($field_name, $format, null, 'D');
1215
-    }
1216
-
1217
-
1218
-
1219
-    /**
1220
-     * @param      $field_name
1221
-     * @param string $format
1222
-     * @throws \EE_Error
1223
-     */
1224
-    public function e_date($field_name, $format = '')
1225
-    {
1226
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1233
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1234
-     * other echoes the pretty value for dtt)
1235
-     *
1236
-     * @param  string $field_name name of model object datetime field holding the value
1237
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1238
-     * @return string             datetime value formatted
1239
-     * @throws \EE_Error
1240
-     */
1241
-    public function get_time($field_name, $format = '')
1242
-    {
1243
-        return $this->_get_datetime($field_name, null, $format, 'T');
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     * @param      $field_name
1250
-     * @param string $format
1251
-     * @throws \EE_Error
1252
-     */
1253
-    public function e_time($field_name, $format = '')
1254
-    {
1255
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1256
-    }
1257
-
1258
-
1259
-
1260
-    /**
1261
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1262
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1263
-     * other echoes the pretty value for dtt)
1264
-     *
1265
-     * @param  string $field_name name of model object datetime field holding the value
1266
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1267
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1268
-     * @return string             datetime value formatted
1269
-     * @throws \EE_Error
1270
-     */
1271
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1272
-    {
1273
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1274
-    }
1275
-
1276
-
1277
-
1278
-    /**
1279
-     * @param string $field_name
1280
-     * @param string $dt_frmt
1281
-     * @param string $tm_frmt
1282
-     * @throws \EE_Error
1283
-     */
1284
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1285
-    {
1286
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1287
-    }
1288
-
1289
-
1290
-
1291
-    /**
1292
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1293
-     *
1294
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1295
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1296
-     *                           on the object will be used.
1297
-     * @return string Date and time string in set locale or false if no field exists for the given
1298
-     * @throws \EE_Error
1299
-     *                           field name.
1300
-     */
1301
-    public function get_i18n_datetime($field_name, $format = '')
1302
-    {
1303
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1304
-        return date_i18n(
1305
-            $format,
1306
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1307
-        );
1308
-    }
1309
-
1310
-
1311
-
1312
-    /**
1313
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1314
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1315
-     * thrown.
1316
-     *
1317
-     * @param  string $field_name The field name being checked
1318
-     * @throws EE_Error
1319
-     * @return EE_Datetime_Field
1320
-     */
1321
-    protected function _get_dtt_field_settings($field_name)
1322
-    {
1323
-        $field = $this->get_model()->field_settings_for($field_name);
1324
-        //check if field is dtt
1325
-        if ($field instanceof EE_Datetime_Field) {
1326
-            return $field;
1327
-        } else {
1328
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1329
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1330
-        }
1331
-    }
1332
-
1333
-
1334
-
1335
-
1336
-    /**
1337
-     * NOTE ABOUT BELOW:
1338
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1339
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1340
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1341
-     * method and make sure you send the entire datetime value for setting.
1342
-     */
1343
-    /**
1344
-     * sets the time on a datetime property
1345
-     *
1346
-     * @access protected
1347
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1348
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1349
-     * @throws \EE_Error
1350
-     */
1351
-    protected function _set_time_for($time, $fieldname)
1352
-    {
1353
-        $this->_set_date_time('T', $time, $fieldname);
1354
-    }
1355
-
1356
-
1357
-
1358
-    /**
1359
-     * sets the date on a datetime property
1360
-     *
1361
-     * @access protected
1362
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1363
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1364
-     * @throws \EE_Error
1365
-     */
1366
-    protected function _set_date_for($date, $fieldname)
1367
-    {
1368
-        $this->_set_date_time('D', $date, $fieldname);
1369
-    }
1370
-
1371
-
1372
-
1373
-    /**
1374
-     * This takes care of setting a date or time independently on a given model object property. This method also
1375
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1376
-     *
1377
-     * @access protected
1378
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1379
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1380
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1381
-     *                                        EE_Datetime_Field property)
1382
-     * @throws \EE_Error
1383
-     */
1384
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1385
-    {
1386
-        $field = $this->_get_dtt_field_settings($fieldname);
1387
-        $field->set_timezone($this->_timezone);
1388
-        $field->set_date_format($this->_dt_frmt);
1389
-        $field->set_time_format($this->_tm_frmt);
1390
-        switch ($what) {
1391
-            case 'T' :
1392
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1393
-                    $datetime_value,
1394
-                    $this->_fields[$fieldname]
1395
-                );
1396
-                break;
1397
-            case 'D' :
1398
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1399
-                    $datetime_value,
1400
-                    $this->_fields[$fieldname]
1401
-                );
1402
-                break;
1403
-            case 'B' :
1404
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1405
-                break;
1406
-        }
1407
-        $this->_clear_cached_property($fieldname);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1414
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1415
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1416
-     * that could lead to some unexpected results!
1417
-     *
1418
-     * @access public
1419
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1420
-     *                                         value being returned.
1421
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1422
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1423
-     * @param string               $prepend    You can include something to prepend on the timestamp
1424
-     * @param string               $append     You can include something to append on the timestamp
1425
-     * @throws EE_Error
1426
-     * @return string timestamp
1427
-     */
1428
-    public function display_in_my_timezone(
1429
-        $field_name,
1430
-        $callback = 'get_datetime',
1431
-        $args = null,
1432
-        $prepend = '',
1433
-        $append = ''
1434
-    ) {
1435
-        $timezone = EEH_DTT_Helper::get_timezone();
1436
-        if ($timezone === $this->_timezone) {
1437
-            return '';
1438
-        }
1439
-        $original_timezone = $this->_timezone;
1440
-        $this->set_timezone($timezone);
1441
-        $fn = (array)$field_name;
1442
-        $args = array_merge($fn, (array)$args);
1443
-        if ( ! method_exists($this, $callback)) {
1444
-            throw new EE_Error(
1445
-                sprintf(
1446
-                    __(
1447
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1448
-                        'event_espresso'
1449
-                    ),
1450
-                    $callback
1451
-                )
1452
-            );
1453
-        }
1454
-        $args = (array)$args;
1455
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1456
-        $this->set_timezone($original_timezone);
1457
-        return $return;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * Deletes this model object.
1464
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1465
-     * override
1466
-     * `EE_Base_Class::_delete` NOT this class.
1467
-     *
1468
-     * @return boolean | int
1469
-     * @throws \EE_Error
1470
-     */
1471
-    public function delete()
1472
-    {
1473
-        /**
1474
-         * Called just before the `EE_Base_Class::_delete` method call.
1475
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1476
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1477
-         * soft deletes (trash) the object and does not permanently delete it.
1478
-         *
1479
-         * @param EE_Base_Class $model_object about to be 'deleted'
1480
-         */
1481
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1482
-        $result = $this->_delete();
1483
-        /**
1484
-         * Called just after the `EE_Base_Class::_delete` method call.
1485
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1486
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1487
-         * soft deletes (trash) the object and does not permanently delete it.
1488
-         *
1489
-         * @param EE_Base_Class $model_object that was just 'deleted'
1490
-         * @param boolean       $result
1491
-         */
1492
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1493
-        return $result;
1494
-    }
1495
-
1496
-
1497
-
1498
-    /**
1499
-     * Calls the specific delete method for the instantiated class.
1500
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1501
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1502
-     * `EE_Base_Class::delete`
1503
-     *
1504
-     * @return bool|int
1505
-     * @throws \EE_Error
1506
-     */
1507
-    protected function _delete()
1508
-    {
1509
-        return $this->delete_permanently();
1510
-    }
1511
-
1512
-
1513
-
1514
-    /**
1515
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1516
-     * error)
1517
-     *
1518
-     * @return bool | int
1519
-     * @throws \EE_Error
1520
-     */
1521
-    public function delete_permanently()
1522
-    {
1523
-        /**
1524
-         * Called just before HARD deleting a model object
1525
-         *
1526
-         * @param EE_Base_Class $model_object about to be 'deleted'
1527
-         */
1528
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1529
-        $model = $this->get_model();
1530
-        $result = $model->delete_permanently_by_ID($this->ID());
1531
-        $this->refresh_cache_of_related_objects();
1532
-        /**
1533
-         * Called just after HARD deleting a model object
1534
-         *
1535
-         * @param EE_Base_Class $model_object that was just 'deleted'
1536
-         * @param boolean       $result
1537
-         */
1538
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1539
-        return $result;
1540
-    }
1541
-
1542
-
1543
-
1544
-    /**
1545
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1546
-     * related model objects
1547
-     *
1548
-     * @throws \EE_Error
1549
-     */
1550
-    public function refresh_cache_of_related_objects()
1551
-    {
1552
-        $model = $this->get_model();
1553
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1554
-            if ( ! empty($this->_model_relations[$relation_name])) {
1555
-                $related_objects = $this->_model_relations[$relation_name];
1556
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1557
-                    //this relation only stores a single model object, not an array
1558
-                    //but let's make it consistent
1559
-                    $related_objects = array($related_objects);
1560
-                }
1561
-                foreach ($related_objects as $related_object) {
1562
-                    //only refresh their cache if they're in memory
1563
-                    if ($related_object instanceof EE_Base_Class) {
1564
-                        $related_object->clear_cache($model->get_this_model_name(), $this);
1565
-                    }
1566
-                }
1567
-            }
1568
-        }
1569
-    }
1570
-
1571
-
1572
-
1573
-    /**
1574
-     *        Saves this object to the database. An array may be supplied to set some values on this
1575
-     * object just before saving.
1576
-     *
1577
-     * @access public
1578
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1579
-     *                                 if provided during the save() method (often client code will change the fields'
1580
-     *                                 values before calling save)
1581
-     * @throws \EE_Error
1582
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1583
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1584
-     */
1585
-    public function save($set_cols_n_values = array())
1586
-    {
1587
-        $model = $this->get_model();
1588
-        /**
1589
-         * Filters the fields we're about to save on the model object
1590
-         *
1591
-         * @param array         $set_cols_n_values
1592
-         * @param EE_Base_Class $model_object
1593
-         */
1594
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1595
-            $this);
1596
-        //set attributes as provided in $set_cols_n_values
1597
-        foreach ($set_cols_n_values as $column => $value) {
1598
-            $this->set($column, $value);
1599
-        }
1600
-        // no changes ? then don't do anything
1601
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1602
-            return 0;
1603
-        }
1604
-        /**
1605
-         * Saving a model object.
1606
-         * Before we perform a save, this action is fired.
1607
-         *
1608
-         * @param EE_Base_Class $model_object the model object about to be saved.
1609
-         */
1610
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1611
-        if ( ! $this->allow_persist()) {
1612
-            return 0;
1613
-        }
1614
-        //now get current attribute values
1615
-        $save_cols_n_values = $this->_fields;
1616
-        //if the object already has an ID, update it. Otherwise, insert it
1617
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1618
-        $old_assumption_concerning_value_preparation = $model
1619
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1620
-        $model->assume_values_already_prepared_by_model_object(true);
1621
-        //does this model have an autoincrement PK?
1622
-        if ($model->has_primary_key_field()) {
1623
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1624
-                //ok check if it's set, if so: update; if not, insert
1625
-                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1626
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1627
-                } else {
1628
-                    unset($save_cols_n_values[$model->primary_key_name()]);
1629
-                    $results = $model->insert($save_cols_n_values);
1630
-                    if ($results) {
1631
-                        //if successful, set the primary key
1632
-                        //but don't use the normal SET method, because it will check if
1633
-                        //an item with the same ID exists in the mapper & db, then
1634
-                        //will find it in the db (because we just added it) and THAT object
1635
-                        //will get added to the mapper before we can add this one!
1636
-                        //but if we just avoid using the SET method, all that headache can be avoided
1637
-                        $pk_field_name = $model->primary_key_name();
1638
-                        $this->_fields[$pk_field_name] = $results;
1639
-                        $this->_clear_cached_property($pk_field_name);
1640
-                        $model->add_to_entity_map($this);
1641
-                        $this->_update_cached_related_model_objs_fks();
1642
-                    }
1643
-                }
1644
-            } else {//PK is NOT auto-increment
1645
-                //so check if one like it already exists in the db
1646
-                if ($model->exists_by_ID($this->ID())) {
1647
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1648
-                        throw new EE_Error(
1649
-                            sprintf(
1650
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1651
-                                    'event_espresso'),
1652
-                                get_class($this),
1653
-                                get_class($model) . '::instance()->add_to_entity_map()',
1654
-                                get_class($model) . '::instance()->get_one_by_ID()',
1655
-                                '<br />'
1656
-                            )
1657
-                        );
1658
-                    }
1659
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1660
-                } else {
1661
-                    $results = $model->insert($save_cols_n_values);
1662
-                    $this->_update_cached_related_model_objs_fks();
1663
-                }
1664
-            }
1665
-        } else {//there is NO primary key
1666
-            $already_in_db = false;
1667
-            foreach ($model->unique_indexes() as $index) {
1668
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1669
-                if ($model->exists(array($uniqueness_where_params))) {
1670
-                    $already_in_db = true;
1671
-                }
1672
-            }
1673
-            if ($already_in_db) {
1674
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1675
-                    $model->get_combined_primary_key_fields());
1676
-                $results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1677
-            } else {
1678
-                $results = $model->insert($save_cols_n_values);
1679
-            }
1680
-        }
1681
-        //restore the old assumption about values being prepared by the model object
1682
-        $model
1683
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1684
-        /**
1685
-         * After saving the model object this action is called
1686
-         *
1687
-         * @param EE_Base_Class $model_object which was just saved
1688
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1689
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1690
-         */
1691
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1692
-        $this->_has_changes = false;
1693
-        return $results;
1694
-    }
1695
-
1696
-
1697
-
1698
-    /**
1699
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1700
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1701
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1702
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1703
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1704
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1705
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1706
-     *
1707
-     * @return void
1708
-     * @throws \EE_Error
1709
-     */
1710
-    protected function _update_cached_related_model_objs_fks()
1711
-    {
1712
-        $model = $this->get_model();
1713
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1714
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1715
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1716
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1717
-                        $model->get_this_model_name()
1718
-                    );
1719
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1720
-                    if ($related_model_obj_in_cache->ID()) {
1721
-                        $related_model_obj_in_cache->save();
1722
-                    }
1723
-                }
1724
-            }
1725
-        }
1726
-    }
1727
-
1728
-
1729
-
1730
-    /**
1731
-     * Saves this model object and its NEW cached relations to the database.
1732
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1733
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1734
-     * because otherwise, there's a potential for infinite looping of saving
1735
-     * Saves the cached related model objects, and ensures the relation between them
1736
-     * and this object and properly setup
1737
-     *
1738
-     * @return int ID of new model object on save; 0 on failure+
1739
-     * @throws \EE_Error
1740
-     */
1741
-    public function save_new_cached_related_model_objs()
1742
-    {
1743
-        //make sure this has been saved
1744
-        if ( ! $this->ID()) {
1745
-            $id = $this->save();
1746
-        } else {
1747
-            $id = $this->ID();
1748
-        }
1749
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1750
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1751
-            if ($this->_model_relations[$relationName]) {
1752
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1753
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1754
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1755
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1756
-                    //but ONLY if it DOES NOT exist in the DB
1757
-                    /* @var $related_model_obj EE_Base_Class */
1758
-                    $related_model_obj = $this->_model_relations[$relationName];
1759
-                    //					if( ! $related_model_obj->ID()){
1760
-                    $this->_add_relation_to($related_model_obj, $relationName);
1761
-                    $related_model_obj->save_new_cached_related_model_objs();
1762
-                    //					}
1763
-                } else {
1764
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1765
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1766
-                        //but ONLY if it DOES NOT exist in the DB
1767
-                        //						if( ! $related_model_obj->ID()){
1768
-                        $this->_add_relation_to($related_model_obj, $relationName);
1769
-                        $related_model_obj->save_new_cached_related_model_objs();
1770
-                        //						}
1771
-                    }
1772
-                }
1773
-            }
1774
-        }
1775
-        return $id;
1776
-    }
1777
-
1778
-
1779
-
1780
-    /**
1781
-     * for getting a model while instantiated.
1782
-     *
1783
-     * @return \EEM_Base | \EEM_CPT_Base
1784
-     */
1785
-    public function get_model()
1786
-    {
1787
-        if( ! $this->_model){
1788
-            $modelName = self::_get_model_classname(get_class($this));
1789
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1790
-        } else {
1791
-            $this->_model->set_timezone($this->_timezone);
1792
-        }
1793
-
1794
-        return $this->_model;
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * @param $props_n_values
1801
-     * @param $classname
1802
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1803
-     * @throws \EE_Error
1804
-     */
1805
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1806
-    {
1807
-        //TODO: will not work for Term_Relationships because they have no PK!
1808
-        $primary_id_ref = self::_get_primary_key_name($classname);
1809
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1810
-            $id = $props_n_values[$primary_id_ref];
1811
-            return self::_get_model($classname)->get_from_entity_map($id);
1812
-        }
1813
-        return false;
1814
-    }
1815
-
1816
-
1817
-
1818
-    /**
1819
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1820
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1821
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1822
-     * we return false.
1823
-     *
1824
-     * @param  array  $props_n_values   incoming array of properties and their values
1825
-     * @param  string $classname        the classname of the child class
1826
-     * @param null    $timezone
1827
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1828
-     *                                  date_format and the second value is the time format
1829
-     * @return mixed (EE_Base_Class|bool)
1830
-     * @throws \EE_Error
1831
-     */
1832
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1833
-    {
1834
-        $existing = null;
1835
-        $model = self::_get_model($classname, $timezone);
1836
-        if ($model->has_primary_key_field()) {
1837
-            $primary_id_ref = self::_get_primary_key_name($classname);
1838
-            if (array_key_exists($primary_id_ref, $props_n_values)
1839
-                && ! empty($props_n_values[$primary_id_ref])
1840
-            ) {
1841
-                $existing = $model->get_one_by_ID(
1842
-                    $props_n_values[$primary_id_ref]
1843
-                );
1844
-            }
1845
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1846
-            //no primary key on this model, but there's still a matching item in the DB
1847
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1848
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1849
-            );
1850
-        }
1851
-        if ($existing) {
1852
-            //set date formats if present before setting values
1853
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1854
-                $existing->set_date_format($date_formats[0]);
1855
-                $existing->set_time_format($date_formats[1]);
1856
-            } else {
1857
-                //set default formats for date and time
1858
-                $existing->set_date_format(get_option('date_format'));
1859
-                $existing->set_time_format(get_option('time_format'));
1860
-            }
1861
-            foreach ($props_n_values as $property => $field_value) {
1862
-                $existing->set($property, $field_value);
1863
-            }
1864
-            return $existing;
1865
-        } else {
1866
-            return false;
1867
-        }
1868
-    }
1869
-
1870
-
1871
-
1872
-    /**
1873
-     * Gets the EEM_*_Model for this class
1874
-     *
1875
-     * @access public now, as this is more convenient
1876
-     * @param      $classname
1877
-     * @param null $timezone
1878
-     * @throws EE_Error
1879
-     * @return EEM_Base
1880
-     */
1881
-    protected static function _get_model($classname, $timezone = null)
1882
-    {
1883
-        //find model for this class
1884
-        if ( ! $classname) {
1885
-            throw new EE_Error(
1886
-                sprintf(
1887
-                    __(
1888
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1889
-                        "event_espresso"
1890
-                    ),
1891
-                    $classname
1892
-                )
1893
-            );
1894
-        }
1895
-        $modelName = self::_get_model_classname($classname);
1896
-        return self::_get_model_instance_with_name($modelName, $timezone);
1897
-    }
1898
-
1899
-
1900
-
1901
-    /**
1902
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1903
-     *
1904
-     * @param string $model_classname
1905
-     * @param null   $timezone
1906
-     * @return EEM_Base
1907
-     */
1908
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1909
-    {
1910
-        $model_classname = str_replace('EEM_', '', $model_classname);
1911
-        $model = EE_Registry::instance()->load_model($model_classname);
1912
-        $model->set_timezone($timezone);
1913
-        return $model;
1914
-    }
1915
-
1916
-
1917
-
1918
-    /**
1919
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1920
-     * Also works if a model class's classname is provided (eg EE_Registration).
1921
-     *
1922
-     * @param null $model_name
1923
-     * @return string like EEM_Attendee
1924
-     */
1925
-    private static function _get_model_classname($model_name = null)
1926
-    {
1927
-        if (strpos($model_name, "EE_") === 0) {
1928
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1929
-        } else {
1930
-            $model_classname = "EEM_" . $model_name;
1931
-        }
1932
-        return $model_classname;
1933
-    }
1934
-
1935
-
1936
-
1937
-    /**
1938
-     * returns the name of the primary key attribute
1939
-     *
1940
-     * @param null $classname
1941
-     * @throws EE_Error
1942
-     * @return string
1943
-     */
1944
-    protected static function _get_primary_key_name($classname = null)
1945
-    {
1946
-        if ( ! $classname) {
1947
-            throw new EE_Error(
1948
-                sprintf(
1949
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1950
-                    $classname
1951
-                )
1952
-            );
1953
-        }
1954
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1955
-    }
1956
-
1957
-
1958
-
1959
-    /**
1960
-     * Gets the value of the primary key.
1961
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1962
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1963
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1964
-     *
1965
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1966
-     * @throws \EE_Error
1967
-     */
1968
-    public function ID()
1969
-    {
1970
-        $model = $this->get_model();
1971
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1972
-        if ($model->has_primary_key_field()) {
1973
-            return $this->_fields[$model->primary_key_name()];
1974
-        } else {
1975
-            return $model->get_index_primary_key_string($this->_fields);
1976
-        }
1977
-    }
1978
-
1979
-
1980
-
1981
-    /**
1982
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1983
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1984
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1985
-     *
1986
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1987
-     * @param string $relationName                     eg 'Events','Question',etc.
1988
-     *                                                 an attendee to a group, you also want to specify which role they
1989
-     *                                                 will have in that group. So you would use this parameter to
1990
-     *                                                 specify array('role-column-name'=>'role-id')
1991
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1992
-     *                                                 allow you to further constrict the relation to being added.
1993
-     *                                                 However, keep in mind that the columns (keys) given must match a
1994
-     *                                                 column on the JOIN table and currently only the HABTM models
1995
-     *                                                 accept these additional conditions.  Also remember that if an
1996
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
1997
-     *                                                 NEW row is created in the join table.
1998
-     * @param null   $cache_id
1999
-     * @throws EE_Error
2000
-     * @return EE_Base_Class the object the relation was added to
2001
-     */
2002
-    public function _add_relation_to(
2003
-        $otherObjectModelObjectOrID,
2004
-        $relationName,
2005
-        $extra_join_model_fields_n_values = array(),
2006
-        $cache_id = null
2007
-    ) {
2008
-        $model = $this->get_model();
2009
-        //if this thing exists in the DB, save the relation to the DB
2010
-        if ($this->ID()) {
2011
-            $otherObject = $model
2012
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2013
-                                    $extra_join_model_fields_n_values);
2014
-            //clear cache so future get_many_related and get_first_related() return new results.
2015
-            $this->clear_cache($relationName, $otherObject, true);
2016
-            if ($otherObject instanceof EE_Base_Class) {
2017
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2018
-            }
2019
-        } else {
2020
-            //this thing doesn't exist in the DB,  so just cache it
2021
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2022
-                throw new EE_Error(sprintf(
2023
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2024
-                        'event_espresso'),
2025
-                    $otherObjectModelObjectOrID,
2026
-                    get_class($this)
2027
-                ));
2028
-            } else {
2029
-                $otherObject = $otherObjectModelObjectOrID;
2030
-            }
2031
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2032
-        }
2033
-        if ($otherObject instanceof EE_Base_Class) {
2034
-            //fix the reciprocal relation too
2035
-            if ($otherObject->ID()) {
2036
-                //its saved so assumed relations exist in the DB, so we can just
2037
-                //clear the cache so future queries use the updated info in the DB
2038
-                $otherObject->clear_cache($model->get_this_model_name(), null, true);
2039
-            } else {
2040
-                //it's not saved, so it caches relations like this
2041
-                $otherObject->cache($model->get_this_model_name(), $this);
2042
-            }
2043
-        }
2044
-        return $otherObject;
2045
-    }
2046
-
2047
-
2048
-
2049
-    /**
2050
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2051
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2052
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2053
-     * from the cache
2054
-     *
2055
-     * @param mixed  $otherObjectModelObjectOrID
2056
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2057
-     *                to the DB yet
2058
-     * @param string $relationName
2059
-     * @param array  $where_query
2060
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2061
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2062
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2063
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2064
-     *                created in the join table.
2065
-     * @return EE_Base_Class the relation was removed from
2066
-     * @throws \EE_Error
2067
-     */
2068
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2069
-    {
2070
-        if ($this->ID()) {
2071
-            //if this exists in the DB, save the relation change to the DB too
2072
-            $otherObject = $this->get_model()
2073
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2074
-                                    $where_query);
2075
-            $this->clear_cache($relationName, $otherObject);
2076
-        } else {
2077
-            //this doesn't exist in the DB, just remove it from the cache
2078
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2079
-        }
2080
-        if ($otherObject instanceof EE_Base_Class) {
2081
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2082
-        }
2083
-        return $otherObject;
2084
-    }
2085
-
2086
-
2087
-
2088
-    /**
2089
-     * Removes ALL the related things for the $relationName.
2090
-     *
2091
-     * @param string $relationName
2092
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2093
-     * @return EE_Base_Class
2094
-     * @throws \EE_Error
2095
-     */
2096
-    public function _remove_relations($relationName, $where_query_params = array())
2097
-    {
2098
-        if ($this->ID()) {
2099
-            //if this exists in the DB, save the relation change to the DB too
2100
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2101
-            $this->clear_cache($relationName, null, true);
2102
-        } else {
2103
-            //this doesn't exist in the DB, just remove it from the cache
2104
-            $otherObjects = $this->clear_cache($relationName, null, true);
2105
-        }
2106
-        if (is_array($otherObjects)) {
2107
-            foreach ($otherObjects as $otherObject) {
2108
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2109
-            }
2110
-        }
2111
-        return $otherObjects;
2112
-    }
2113
-
2114
-
2115
-
2116
-    /**
2117
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2118
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2119
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2120
-     * because we want to get even deleted items etc.
2121
-     *
2122
-     * @param string $relationName key in the model's _model_relations array
2123
-     * @param array  $query_params like EEM_Base::get_all
2124
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2125
-     * @throws \EE_Error
2126
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2127
-     *                             you want IDs
2128
-     */
2129
-    public function get_many_related($relationName, $query_params = array())
2130
-    {
2131
-        if ($this->ID()) {
2132
-            //this exists in the DB, so get the related things from either the cache or the DB
2133
-            //if there are query parameters, forget about caching the related model objects.
2134
-            if ($query_params) {
2135
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2136
-            } else {
2137
-                //did we already cache the result of this query?
2138
-                $cached_results = $this->get_all_from_cache($relationName);
2139
-                if ( ! $cached_results) {
2140
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2141
-                    //if no query parameters were passed, then we got all the related model objects
2142
-                    //for that relation. We can cache them then.
2143
-                    foreach ($related_model_objects as $related_model_object) {
2144
-                        $this->cache($relationName, $related_model_object);
2145
-                    }
2146
-                } else {
2147
-                    $related_model_objects = $cached_results;
2148
-                }
2149
-            }
2150
-        } else {
2151
-            //this doesn't exist in the DB, so just get the related things from the cache
2152
-            $related_model_objects = $this->get_all_from_cache($relationName);
2153
-        }
2154
-        return $related_model_objects;
2155
-    }
2156
-
2157
-
2158
-
2159
-    /**
2160
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2161
-     * unless otherwise specified in the $query_params
2162
-     *
2163
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2164
-     * @param array  $query_params   like EEM_Base::get_all's
2165
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2166
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2167
-     *                               that by the setting $distinct to TRUE;
2168
-     * @return int
2169
-     */
2170
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2171
-    {
2172
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2173
-    }
2174
-
2175
-
2176
-
2177
-    /**
2178
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2179
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2180
-     *
2181
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2182
-     * @param array  $query_params  like EEM_Base::get_all's
2183
-     * @param string $field_to_sum  name of field to count by.
2184
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2185
-     *                              change it)
2186
-     * @return int
2187
-     */
2188
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2189
-    {
2190
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2191
-    }
2192
-
2193
-
2194
-
2195
-    /**
2196
-     * Gets the first (ie, one) related model object of the specified type.
2197
-     *
2198
-     * @param string $relationName key in the model's _model_relations array
2199
-     * @param array  $query_params like EEM_Base::get_all
2200
-     * @return EE_Base_Class (not an array, a single object)
2201
-     * @throws \EE_Error
2202
-     */
2203
-    public function get_first_related($relationName, $query_params = array())
2204
-    {
2205
-        $model = $this->get_model();
2206
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2207
-            //if they've provided some query parameters, don't bother trying to cache the result
2208
-            //also make sure we're not caching the result of get_first_related
2209
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2210
-            if ($query_params
2211
-                || ! $model->related_settings_for($relationName)
2212
-                     instanceof
2213
-                     EE_Belongs_To_Relation
2214
-            ) {
2215
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2216
-            } else {
2217
-                //first, check if we've already cached the result of this query
2218
-                $cached_result = $this->get_one_from_cache($relationName);
2219
-                if ( ! $cached_result) {
2220
-                    $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2221
-                    $this->cache($relationName, $related_model_object);
2222
-                } else {
2223
-                    $related_model_object = $cached_result;
2224
-                }
2225
-            }
2226
-        } else {
2227
-            $related_model_object = null;
2228
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2229
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2230
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2231
-            }
2232
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2233
-            if ( ! $related_model_object) {
2234
-                $related_model_object = $this->get_one_from_cache($relationName);
2235
-            }
2236
-        }
2237
-        return $related_model_object;
2238
-    }
2239
-
2240
-
2241
-
2242
-    /**
2243
-     * Does a delete on all related objects of type $relationName and removes
2244
-     * the current model object's relation to them. If they can't be deleted (because
2245
-     * of blocking related model objects) does nothing. If the related model objects are
2246
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2247
-     * If this model object doesn't exist yet in the DB, just removes its related things
2248
-     *
2249
-     * @param string $relationName
2250
-     * @param array  $query_params like EEM_Base::get_all's
2251
-     * @return int how many deleted
2252
-     * @throws \EE_Error
2253
-     */
2254
-    public function delete_related($relationName, $query_params = array())
2255
-    {
2256
-        if ($this->ID()) {
2257
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2258
-        } else {
2259
-            $count = count($this->get_all_from_cache($relationName));
2260
-            $this->clear_cache($relationName, null, true);
2261
-        }
2262
-        return $count;
2263
-    }
2264
-
2265
-
2266
-
2267
-    /**
2268
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2269
-     * the current model object's relation to them. If they can't be deleted (because
2270
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2271
-     * If the related thing isn't a soft-deletable model object, this function is identical
2272
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2273
-     *
2274
-     * @param string $relationName
2275
-     * @param array  $query_params like EEM_Base::get_all's
2276
-     * @return int how many deleted (including those soft deleted)
2277
-     * @throws \EE_Error
2278
-     */
2279
-    public function delete_related_permanently($relationName, $query_params = array())
2280
-    {
2281
-        if ($this->ID()) {
2282
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2283
-        } else {
2284
-            $count = count($this->get_all_from_cache($relationName));
2285
-        }
2286
-        $this->clear_cache($relationName, null, true);
2287
-        return $count;
2288
-    }
2289
-
2290
-
2291
-
2292
-    /**
2293
-     * is_set
2294
-     * Just a simple utility function children can use for checking if property exists
2295
-     *
2296
-     * @access  public
2297
-     * @param  string $field_name property to check
2298
-     * @return bool                              TRUE if existing,FALSE if not.
2299
-     */
2300
-    public function is_set($field_name)
2301
-    {
2302
-        return isset($this->_fields[$field_name]);
2303
-    }
2304
-
2305
-
2306
-
2307
-    /**
2308
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2309
-     * EE_Error exception if they don't
2310
-     *
2311
-     * @param  mixed (string|array) $properties properties to check
2312
-     * @throws EE_Error
2313
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2314
-     */
2315
-    protected function _property_exists($properties)
2316
-    {
2317
-        foreach ((array)$properties as $property_name) {
2318
-            //first make sure this property exists
2319
-            if ( ! $this->_fields[$property_name]) {
2320
-                throw new EE_Error(
2321
-                    sprintf(
2322
-                        __(
2323
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2324
-                            'event_espresso'
2325
-                        ),
2326
-                        $property_name
2327
-                    )
2328
-                );
2329
-            }
2330
-        }
2331
-        return true;
2332
-    }
2333
-
2334
-
2335
-
2336
-    /**
2337
-     * This simply returns an array of model fields for this object
2338
-     *
2339
-     * @return array
2340
-     * @throws \EE_Error
2341
-     */
2342
-    public function model_field_array()
2343
-    {
2344
-        $fields = $this->get_model()->field_settings(false);
2345
-        $properties = array();
2346
-        //remove prepended underscore
2347
-        foreach ($fields as $field_name => $settings) {
2348
-            $properties[$field_name] = $this->get($field_name);
2349
-        }
2350
-        return $properties;
2351
-    }
2352
-
2353
-
2354
-
2355
-    /**
2356
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2357
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2358
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2359
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2360
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2361
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2362
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2363
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2364
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2365
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2366
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2367
-     *        return $previousReturnValue.$returnString;
2368
-     * }
2369
-     * require('EE_Answer.class.php');
2370
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2371
-     * echo $answer->my_callback('monkeys',100);
2372
-     * //will output "you called my_callback! and passed args:monkeys,100"
2373
-     *
2374
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2375
-     * @param array  $args       array of original arguments passed to the function
2376
-     * @throws EE_Error
2377
-     * @return mixed whatever the plugin which calls add_filter decides
2378
-     */
2379
-    public function __call($methodName, $args)
2380
-    {
2381
-        $className = get_class($this);
2382
-        $tagName = "FHEE__{$className}__{$methodName}";
2383
-        if ( ! has_filter($tagName)) {
2384
-            throw new EE_Error(
2385
-                sprintf(
2386
-                    __(
2387
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2388
-                        "event_espresso"
2389
-                    ),
2390
-                    $methodName,
2391
-                    $className,
2392
-                    $tagName
2393
-                )
2394
-            );
2395
-        }
2396
-        return apply_filters($tagName, null, $this, $args);
2397
-    }
2398
-
2399
-
2400
-
2401
-    /**
2402
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2403
-     * A $previous_value can be specified in case there are many meta rows with the same key
2404
-     *
2405
-     * @param string $meta_key
2406
-     * @param mixed  $meta_value
2407
-     * @param mixed  $previous_value
2408
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2409
-     * @throws \EE_Error
2410
-     * NOTE: if the values haven't changed, returns 0
2411
-     */
2412
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2413
-    {
2414
-        $query_params = array(
2415
-            array(
2416
-                'EXM_key'  => $meta_key,
2417
-                'OBJ_ID'   => $this->ID(),
2418
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2419
-            ),
2420
-        );
2421
-        if ($previous_value !== null) {
2422
-            $query_params[0]['EXM_value'] = $meta_value;
2423
-        }
2424
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2425
-        if ( ! $existing_rows_like_that) {
2426
-            return $this->add_extra_meta($meta_key, $meta_value);
2427
-        }
2428
-        foreach ($existing_rows_like_that as $existing_row) {
2429
-            $existing_row->save(array('EXM_value' => $meta_value));
2430
-        }
2431
-        return count($existing_rows_like_that);
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2438
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2439
-     * extra meta row was entered, false if not
2440
-     *
2441
-     * @param string  $meta_key
2442
-     * @param mixed   $meta_value
2443
-     * @param boolean $unique
2444
-     * @return boolean
2445
-     * @throws \EE_Error
2446
-     */
2447
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2448
-    {
2449
-        if ($unique) {
2450
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2451
-                array(
2452
-                    array(
2453
-                        'EXM_key'  => $meta_key,
2454
-                        'OBJ_ID'   => $this->ID(),
2455
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2456
-                    ),
2457
-                )
2458
-            );
2459
-            if ($existing_extra_meta) {
2460
-                return false;
2461
-            }
2462
-        }
2463
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2464
-            array(
2465
-                'EXM_key'   => $meta_key,
2466
-                'EXM_value' => $meta_value,
2467
-                'OBJ_ID'    => $this->ID(),
2468
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2469
-            )
2470
-        );
2471
-        $new_extra_meta->save();
2472
-        return true;
2473
-    }
2474
-
2475
-
2476
-
2477
-    /**
2478
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2479
-     * is specified, only deletes extra meta records with that value.
2480
-     *
2481
-     * @param string $meta_key
2482
-     * @param mixed  $meta_value
2483
-     * @return int number of extra meta rows deleted
2484
-     * @throws \EE_Error
2485
-     */
2486
-    public function delete_extra_meta($meta_key, $meta_value = null)
2487
-    {
2488
-        $query_params = array(
2489
-            array(
2490
-                'EXM_key'  => $meta_key,
2491
-                'OBJ_ID'   => $this->ID(),
2492
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2493
-            ),
2494
-        );
2495
-        if ($meta_value !== null) {
2496
-            $query_params[0]['EXM_value'] = $meta_value;
2497
-        }
2498
-        return EEM_Extra_Meta::instance()->delete($query_params);
2499
-    }
2500
-
2501
-
2502
-
2503
-    /**
2504
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2505
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2506
-     * You can specify $default is case you haven't found the extra meta
2507
-     *
2508
-     * @param string  $meta_key
2509
-     * @param boolean $single
2510
-     * @param mixed   $default if we don't find anything, what should we return?
2511
-     * @return mixed single value if $single; array if ! $single
2512
-     * @throws \EE_Error
2513
-     */
2514
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2515
-    {
2516
-        if ($single) {
2517
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2518
-            if ($result instanceof EE_Extra_Meta) {
2519
-                return $result->value();
2520
-            } else {
2521
-                return $default;
2522
-            }
2523
-        } else {
2524
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2525
-            if ($results) {
2526
-                $values = array();
2527
-                foreach ($results as $result) {
2528
-                    if ($result instanceof EE_Extra_Meta) {
2529
-                        $values[$result->ID()] = $result->value();
2530
-                    }
2531
-                }
2532
-                return $values;
2533
-            } else {
2534
-                return $default;
2535
-            }
2536
-        }
2537
-    }
2538
-
2539
-
2540
-
2541
-    /**
2542
-     * Returns a simple array of all the extra meta associated with this model object.
2543
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2544
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2545
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2546
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2547
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2548
-     * finally the extra meta's value as each sub-value. (eg
2549
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2550
-     *
2551
-     * @param boolean $one_of_each_key
2552
-     * @return array
2553
-     * @throws \EE_Error
2554
-     */
2555
-    public function all_extra_meta_array($one_of_each_key = true)
2556
-    {
2557
-        $return_array = array();
2558
-        if ($one_of_each_key) {
2559
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2560
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2561
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2562
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2563
-                }
2564
-            }
2565
-        } else {
2566
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2567
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2568
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2569
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2570
-                        $return_array[$extra_meta_obj->key()] = array();
2571
-                    }
2572
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2573
-                }
2574
-            }
2575
-        }
2576
-        return $return_array;
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2583
-     *
2584
-     * @return string
2585
-     * @throws \EE_Error
2586
-     */
2587
-    public function name()
2588
-    {
2589
-        //find a field that's not a text field
2590
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2591
-        if ($field_we_can_use) {
2592
-            return $this->get($field_we_can_use->get_name());
2593
-        } else {
2594
-            $first_few_properties = $this->model_field_array();
2595
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2596
-            $name_parts = array();
2597
-            foreach ($first_few_properties as $name => $value) {
2598
-                $name_parts[] = "$name:$value";
2599
-            }
2600
-            return implode(",", $name_parts);
2601
-        }
2602
-    }
2603
-
2604
-
2605
-
2606
-    /**
2607
-     * in_entity_map
2608
-     * Checks if this model object has been proven to already be in the entity map
2609
-     *
2610
-     * @return boolean
2611
-     * @throws \EE_Error
2612
-     */
2613
-    public function in_entity_map()
2614
-    {
2615
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2616
-            //well, if we looked, did we find it in the entity map?
2617
-            return true;
2618
-        } else {
2619
-            return false;
2620
-        }
2621
-    }
2622
-
2623
-
2624
-
2625
-    /**
2626
-     * refresh_from_db
2627
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2628
-     *
2629
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2630
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2631
-     */
2632
-    public function refresh_from_db()
2633
-    {
2634
-        if ($this->ID() && $this->in_entity_map()) {
2635
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2636
-        } else {
2637
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2638
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2639
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2640
-            //absolutely nothing in it for this ID
2641
-            if (WP_DEBUG) {
2642
-                throw new EE_Error(
2643
-                    sprintf(
2644
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2645
-                            'event_espresso'),
2646
-                        $this->ID(),
2647
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2648
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2649
-                    )
2650
-                );
2651
-            }
2652
-        }
2653
-    }
2654
-
2655
-
2656
-
2657
-    /**
2658
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2659
-     * (probably a bad assumption they have made, oh well)
2660
-     *
2661
-     * @return string
2662
-     */
2663
-    public function __toString()
2664
-    {
2665
-        try {
2666
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2667
-        } catch (Exception $e) {
2668
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2669
-            return '';
2670
-        }
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Clear related model objects if they're already in the DB, because otherwise when we
2677
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2678
-     * This means if we have made changes to those related model objects, and want to unserialize
2679
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2680
-     * Instead, those related model objects should be directly serialized and stored.
2681
-     * Eg, the following won't work:
2682
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2683
-     * $att = $reg->attendee();
2684
-     * $att->set( 'ATT_fname', 'Dirk' );
2685
-     * update_option( 'my_option', serialize( $reg ) );
2686
-     * //END REQUEST
2687
-     * //START NEXT REQUEST
2688
-     * $reg = get_option( 'my_option' );
2689
-     * $reg->attendee()->save();
2690
-     * And would need to be replace with:
2691
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2692
-     * $att = $reg->attendee();
2693
-     * $att->set( 'ATT_fname', 'Dirk' );
2694
-     * update_option( 'my_option', serialize( $reg ) );
2695
-     * //END REQUEST
2696
-     * //START NEXT REQUEST
2697
-     * $att = get_option( 'my_option' );
2698
-     * $att->save();
2699
-     *
2700
-     * @return array
2701
-     * @throws \EE_Error
2702
-     */
2703
-    public function __sleep()
2704
-    {
2705
-        $model = $this->get_model();
2706
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2707
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2708
-                $classname = 'EE_' . $model->get_this_model_name();
2709
-                if (
2710
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2711
-                    && $this->get_one_from_cache($relation_name)->ID()
2712
-                ) {
2713
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2714
-                }
2715
-            }
2716
-        }
2717
-        $this->_props_n_values_provided_in_constructor = array();
2718
-        $properties_to_serialize = get_object_vars($this);
2719
-        //don't serialize the model. It's big and that risks recursion
2720
-        unset($properties_to_serialize['_model']);
2721
-        return array_keys($properties_to_serialize);
2722
-    }
2723
-
2724
-
2725
-
2726
-    /**
2727
-     * restore _props_n_values_provided_in_constructor
2728
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2729
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2730
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2731
-     */
2732
-    public function __wakeup()
2733
-    {
2734
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2735
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+	/**
109
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
110
+	 */
111
+	protected $_has_changes = false;
112
+
113
+	/**
114
+	 * @var EEM_Base
115
+	 */
116
+	protected $_model;
117
+
118
+
119
+
120
+	/**
121
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
+	 * play nice
123
+	 *
124
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
127
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
+	 *                                                         corresponding db model or not.
129
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
+	 *                                                         be in when instantiating a EE_Base_Class object.
131
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
132
+	 *                                                         value is the date_format and second value is the time
133
+	 *                                                         format.
134
+	 * @throws EE_Error
135
+	 */
136
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
137
+	{
138
+		$className = get_class($this);
139
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
140
+		$model = $this->get_model();
141
+		$model_fields = $model->field_settings(false);
142
+		// ensure $fieldValues is an array
143
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
144
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
145
+		// verify client code has not passed any invalid field names
146
+		foreach ($fieldValues as $field_name => $field_value) {
147
+			if ( ! isset($model_fields[$field_name])) {
148
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
149
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
150
+			}
151
+		}
152
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
153
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
+		if ( ! empty($date_formats) && is_array($date_formats)) {
155
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
156
+		} else {
157
+			//set default formats for date and time
158
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
159
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
160
+		}
161
+		//if db model is instantiating
162
+		if ($bydb) {
163
+			//client code has indicated these field values are from the database
164
+			foreach ($model_fields as $fieldName => $field) {
165
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
166
+			}
167
+		} else {
168
+			//we're constructing a brand
169
+			//new instance of the model object. Generally, this means we'll need to do more field validation
170
+			foreach ($model_fields as $fieldName => $field) {
171
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
172
+			}
173
+		}
174
+		//remember what values were passed to this constructor
175
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
176
+		//remember in entity mapper
177
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
178
+			$model->add_to_entity_map($this);
179
+		}
180
+		//setup all the relations
181
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
182
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
183
+				$this->_model_relations[$relation_name] = null;
184
+			} else {
185
+				$this->_model_relations[$relation_name] = array();
186
+			}
187
+		}
188
+		/**
189
+		 * Action done at the end of each model object construction
190
+		 *
191
+		 * @param EE_Base_Class $this the model object just created
192
+		 */
193
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
200
+	 *
201
+	 * @return boolean
202
+	 */
203
+	public function allow_persist()
204
+	{
205
+		return $this->_allow_persist;
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
212
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
+	 * you got new information that somehow made you change your mind.
214
+	 *
215
+	 * @param boolean $allow_persist
216
+	 * @return boolean
217
+	 */
218
+	public function set_allow_persist($allow_persist)
219
+	{
220
+		return $this->_allow_persist = $allow_persist;
221
+	}
222
+
223
+
224
+
225
+	/**
226
+	 * Gets the field's original value when this object was constructed during this request.
227
+	 * This can be helpful when determining if a model object has changed or not
228
+	 *
229
+	 * @param string $field_name
230
+	 * @return mixed|null
231
+	 * @throws \EE_Error
232
+	 */
233
+	public function get_original($field_name)
234
+	{
235
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
236
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
237
+		) {
238
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
239
+		} else {
240
+			return null;
241
+		}
242
+	}
243
+
244
+
245
+
246
+	/**
247
+	 * @param EE_Base_Class $obj
248
+	 * @return string
249
+	 */
250
+	public function get_class($obj)
251
+	{
252
+		return get_class($obj);
253
+	}
254
+
255
+
256
+
257
+	/**
258
+	 * Overrides parent because parent expects old models.
259
+	 * This also doesn't do any validation, and won't work for serialized arrays
260
+	 *
261
+	 * @param    string $field_name
262
+	 * @param    mixed  $field_value
263
+	 * @param bool      $use_default
264
+	 * @throws \EE_Error
265
+	 */
266
+	public function set($field_name, $field_value, $use_default = false)
267
+	{
268
+		// if not using default and nothing has changed, and object has already been setup (has ID),
269
+		// then don't do anything
270
+		if (
271
+			! $use_default
272
+			&& $this->_fields[$field_name] === $field_value
273
+			&& $this->ID()
274
+		) {
275
+			return;
276
+		}
277
+		$model = $this->get_model();
278
+		$this->_has_changes = true;
279
+		$field_obj = $model->field_settings_for($field_name);
280
+		if ($field_obj instanceof EE_Model_Field_Base) {
281
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
282
+			if ($field_obj instanceof EE_Datetime_Field) {
283
+				$field_obj->set_timezone($this->_timezone);
284
+				$field_obj->set_date_format($this->_dt_frmt);
285
+				$field_obj->set_time_format($this->_tm_frmt);
286
+			}
287
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
288
+			//should the value be null?
289
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
290
+				$this->_fields[$field_name] = $field_obj->get_default_value();
291
+				/**
292
+				 * To save having to refactor all the models, if a default value is used for a
293
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
294
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
295
+				 * object.
296
+				 *
297
+				 * @since 4.6.10+
298
+				 */
299
+				if (
300
+					$field_obj instanceof EE_Datetime_Field
301
+					&& $this->_fields[$field_name] !== null
302
+					&& ! $this->_fields[$field_name] instanceof DateTime
303
+				) {
304
+					empty($this->_fields[$field_name])
305
+						? $this->set($field_name, time())
306
+						: $this->set($field_name, $this->_fields[$field_name]);
307
+				}
308
+			} else {
309
+				$this->_fields[$field_name] = $holder_of_value;
310
+			}
311
+			//if we're not in the constructor...
312
+			//now check if what we set was a primary key
313
+			if (
314
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
+				$this->_props_n_values_provided_in_constructor
316
+				&& $field_value
317
+				&& $field_name === $model->primary_key_name()
318
+			) {
319
+				//if so, we want all this object's fields to be filled either with
320
+				//what we've explicitly set on this model
321
+				//or what we have in the db
322
+				// echo "setting primary key!";
323
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
324
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
+				foreach ($fields_on_model as $field_obj) {
326
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
327
+						 && $field_obj->get_name() !== $field_name
328
+					) {
329
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
330
+					}
331
+				}
332
+				//oh this model object has an ID? well make sure its in the entity mapper
333
+				$model->add_to_entity_map($this);
334
+			}
335
+			//let's unset any cache for this field_name from the $_cached_properties property.
336
+			$this->_clear_cached_property($field_name);
337
+		} else {
338
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
339
+				"event_espresso"), $field_name));
340
+		}
341
+	}
342
+
343
+
344
+
345
+	/**
346
+	 * This sets the field value on the db column if it exists for the given $column_name or
347
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
348
+	 *
349
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
350
+	 * @param string $field_name  Must be the exact column name.
351
+	 * @param mixed  $field_value The value to set.
352
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
353
+	 * @throws \EE_Error
354
+	 */
355
+	public function set_field_or_extra_meta($field_name, $field_value)
356
+	{
357
+		if ($this->get_model()->has_field($field_name)) {
358
+			$this->set($field_name, $field_value);
359
+			return true;
360
+		} else {
361
+			//ensure this object is saved first so that extra meta can be properly related.
362
+			$this->save();
363
+			return $this->update_extra_meta($field_name, $field_value);
364
+		}
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * This retrieves the value of the db column set on this class or if that's not present
371
+	 * it will attempt to retrieve from extra_meta if found.
372
+	 * Example Usage:
373
+	 * Via EE_Message child class:
374
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
375
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
376
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
377
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
378
+	 * value for those extra fields dynamically via the EE_message object.
379
+	 *
380
+	 * @param  string $field_name expecting the fully qualified field name.
381
+	 * @return mixed|null  value for the field if found.  null if not found.
382
+	 * @throws \EE_Error
383
+	 */
384
+	public function get_field_or_extra_meta($field_name)
385
+	{
386
+		if ($this->get_model()->has_field($field_name)) {
387
+			$column_value = $this->get($field_name);
388
+		} else {
389
+			//This isn't a column in the main table, let's see if it is in the extra meta.
390
+			$column_value = $this->get_extra_meta($field_name, true, null);
391
+		}
392
+		return $column_value;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
399
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
400
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
401
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
402
+	 *
403
+	 * @access public
404
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
405
+	 * @return void
406
+	 * @throws \EE_Error
407
+	 */
408
+	public function set_timezone($timezone = '')
409
+	{
410
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
411
+		//make sure we clear all cached properties because they won't be relevant now
412
+		$this->_clear_cached_properties();
413
+		//make sure we update field settings and the date for all EE_Datetime_Fields
414
+		$model_fields = $this->get_model()->field_settings(false);
415
+		foreach ($model_fields as $field_name => $field_obj) {
416
+			if ($field_obj instanceof EE_Datetime_Field) {
417
+				$field_obj->set_timezone($this->_timezone);
418
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
419
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
420
+				}
421
+			}
422
+		}
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * This just returns whatever is set for the current timezone.
429
+	 *
430
+	 * @access public
431
+	 * @return string timezone string
432
+	 */
433
+	public function get_timezone()
434
+	{
435
+		return $this->_timezone;
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
442
+	 * internally instead of wp set date format options
443
+	 *
444
+	 * @since 4.6
445
+	 * @param string $format should be a format recognizable by PHP date() functions.
446
+	 */
447
+	public function set_date_format($format)
448
+	{
449
+		$this->_dt_frmt = $format;
450
+		//clear cached_properties because they won't be relevant now.
451
+		$this->_clear_cached_properties();
452
+	}
453
+
454
+
455
+
456
+	/**
457
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
458
+	 * class internally instead of wp set time format options.
459
+	 *
460
+	 * @since 4.6
461
+	 * @param string $format should be a format recognizable by PHP date() functions.
462
+	 */
463
+	public function set_time_format($format)
464
+	{
465
+		$this->_tm_frmt = $format;
466
+		//clear cached_properties because they won't be relevant now.
467
+		$this->_clear_cached_properties();
468
+	}
469
+
470
+
471
+
472
+	/**
473
+	 * This returns the current internal set format for the date and time formats.
474
+	 *
475
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
476
+	 *                             where the first value is the date format and the second value is the time format.
477
+	 * @return mixed string|array
478
+	 */
479
+	public function get_format($full = true)
480
+	{
481
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * cache
488
+	 * stores the passed model object on the current model object.
489
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
490
+	 *
491
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
492
+	 *                                       'Registration' associated with this model object
493
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
494
+	 *                                       that could be a payment or a registration)
495
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
496
+	 *                                       items which will be stored in an array on this object
497
+	 * @throws EE_Error
498
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
499
+	 *                  related thing, no array)
500
+	 */
501
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
502
+	{
503
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
504
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
505
+			return false;
506
+		}
507
+		// also get "how" the object is related, or throw an error
508
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
509
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
510
+				$relationName, get_class($this)));
511
+		}
512
+		// how many things are related ?
513
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
514
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
515
+			// so for these model objects just set it to be cached
516
+			$this->_model_relations[$relationName] = $object_to_cache;
517
+			$return = true;
518
+		} else {
519
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
520
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
521
+			if ( ! is_array($this->_model_relations[$relationName])) {
522
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
523
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
524
+					? array($this->_model_relations[$relationName]) : array();
525
+			}
526
+			// first check for a cache_id which is normally empty
527
+			if ( ! empty($cache_id)) {
528
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
529
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
530
+				$return = $cache_id;
531
+			} elseif ($object_to_cache->ID()) {
532
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
533
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
534
+				$return = $object_to_cache->ID();
535
+			} else {
536
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
537
+				$this->_model_relations[$relationName][] = $object_to_cache;
538
+				// move the internal pointer to the end of the array
539
+				end($this->_model_relations[$relationName]);
540
+				// and grab the key so that we can return it
541
+				$return = key($this->_model_relations[$relationName]);
542
+			}
543
+		}
544
+		return $return;
545
+	}
546
+
547
+
548
+
549
+	/**
550
+	 * For adding an item to the cached_properties property.
551
+	 *
552
+	 * @access protected
553
+	 * @param string      $fieldname the property item the corresponding value is for.
554
+	 * @param mixed       $value     The value we are caching.
555
+	 * @param string|null $cache_type
556
+	 * @return void
557
+	 * @throws \EE_Error
558
+	 */
559
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
560
+	{
561
+		//first make sure this property exists
562
+		$this->get_model()->field_settings_for($fieldname);
563
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
564
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
565
+	}
566
+
567
+
568
+
569
+	/**
570
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
571
+	 * This also SETS the cache if we return the actual property!
572
+	 *
573
+	 * @param string $fieldname        the name of the property we're trying to retrieve
574
+	 * @param bool   $pretty
575
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
576
+	 *                                 (in cases where the same property may be used for different outputs
577
+	 *                                 - i.e. datetime, money etc.)
578
+	 *                                 It can also accept certain pre-defined "schema" strings
579
+	 *                                 to define how to output the property.
580
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
581
+	 * @return mixed                   whatever the value for the property is we're retrieving
582
+	 * @throws \EE_Error
583
+	 */
584
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
585
+	{
586
+		//verify the field exists
587
+		$model = $this->get_model();
588
+		$model->field_settings_for($fieldname);
589
+		$cache_type = $pretty ? 'pretty' : 'standard';
590
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
591
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
592
+			return $this->_cached_properties[$fieldname][$cache_type];
593
+		}
594
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
595
+		$this->_set_cached_property($fieldname, $value, $cache_type);
596
+		return $value;
597
+	}
598
+
599
+
600
+
601
+	/**
602
+	 * If the cache didn't fetch the needed item, this fetches it.
603
+	 * @param string $fieldname
604
+	 * @param bool $pretty
605
+	 * @param string $extra_cache_ref
606
+	 * @return mixed
607
+	 */
608
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
609
+	{
610
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
611
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
612
+		if ($field_obj instanceof EE_Datetime_Field) {
613
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
614
+		}
615
+		if ( ! isset($this->_fields[$fieldname])) {
616
+			$this->_fields[$fieldname] = null;
617
+		}
618
+		$value = $pretty
619
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
620
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
621
+		return $value;
622
+	}
623
+
624
+
625
+
626
+	/**
627
+	 * set timezone, formats, and output for EE_Datetime_Field objects
628
+	 *
629
+	 * @param \EE_Datetime_Field $datetime_field
630
+	 * @param bool               $pretty
631
+	 * @param null $date_or_time
632
+	 * @return void
633
+	 * @throws \EE_Error
634
+	 */
635
+	protected function _prepare_datetime_field(
636
+		EE_Datetime_Field $datetime_field,
637
+		$pretty = false,
638
+		$date_or_time = null
639
+	) {
640
+		$datetime_field->set_timezone($this->_timezone);
641
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
642
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
643
+		//set the output returned
644
+		switch ($date_or_time) {
645
+			case 'D' :
646
+				$datetime_field->set_date_time_output('date');
647
+				break;
648
+			case 'T' :
649
+				$datetime_field->set_date_time_output('time');
650
+				break;
651
+			default :
652
+				$datetime_field->set_date_time_output();
653
+		}
654
+	}
655
+
656
+
657
+
658
+	/**
659
+	 * This just takes care of clearing out the cached_properties
660
+	 *
661
+	 * @return void
662
+	 */
663
+	protected function _clear_cached_properties()
664
+	{
665
+		$this->_cached_properties = array();
666
+	}
667
+
668
+
669
+
670
+	/**
671
+	 * This just clears out ONE property if it exists in the cache
672
+	 *
673
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
674
+	 * @return void
675
+	 */
676
+	protected function _clear_cached_property($property_name)
677
+	{
678
+		if (isset($this->_cached_properties[$property_name])) {
679
+			unset($this->_cached_properties[$property_name]);
680
+		}
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * Ensures that this related thing is a model object.
687
+	 *
688
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
689
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
690
+	 * @return EE_Base_Class
691
+	 * @throws \EE_Error
692
+	 */
693
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
694
+	{
695
+		$other_model_instance = self::_get_model_instance_with_name(
696
+			self::_get_model_classname($model_name),
697
+			$this->_timezone
698
+		);
699
+		return $other_model_instance->ensure_is_obj($object_or_id);
700
+	}
701
+
702
+
703
+
704
+	/**
705
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
706
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
707
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
708
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
709
+	 *
710
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
711
+	 *                                                     Eg 'Registration'
712
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
713
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
714
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
715
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
716
+	 *                                                     this is HasMany or HABTM.
717
+	 * @throws EE_Error
718
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
719
+	 *                       relation from all
720
+	 */
721
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
722
+	{
723
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
724
+		$index_in_cache = '';
725
+		if ( ! $relationship_to_model) {
726
+			throw new EE_Error(
727
+				sprintf(
728
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
729
+					$relationName,
730
+					get_class($this)
731
+				)
732
+			);
733
+		}
734
+		if ($clear_all) {
735
+			$obj_removed = true;
736
+			$this->_model_relations[$relationName] = null;
737
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
738
+			$obj_removed = $this->_model_relations[$relationName];
739
+			$this->_model_relations[$relationName] = null;
740
+		} else {
741
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
742
+				&& $object_to_remove_or_index_into_array->ID()
743
+			) {
744
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
745
+				if (is_array($this->_model_relations[$relationName])
746
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
747
+				) {
748
+					$index_found_at = null;
749
+					//find this object in the array even though it has a different key
750
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
751
+						if (
752
+							$obj instanceof EE_Base_Class
753
+							&& (
754
+								$obj == $object_to_remove_or_index_into_array
755
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
756
+							)
757
+						) {
758
+							$index_found_at = $index;
759
+							break;
760
+						}
761
+					}
762
+					if ($index_found_at) {
763
+						$index_in_cache = $index_found_at;
764
+					} else {
765
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
766
+						//if it wasn't in it to begin with. So we're done
767
+						return $object_to_remove_or_index_into_array;
768
+					}
769
+				}
770
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
771
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
772
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
773
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
774
+						$index_in_cache = $index;
775
+					}
776
+				}
777
+			} else {
778
+				$index_in_cache = $object_to_remove_or_index_into_array;
779
+			}
780
+			//supposedly we've found it. But it could just be that the client code
781
+			//provided a bad index/object
782
+			if (
783
+			isset(
784
+				$this->_model_relations[$relationName],
785
+				$this->_model_relations[$relationName][$index_in_cache]
786
+			)
787
+			) {
788
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
789
+				unset($this->_model_relations[$relationName][$index_in_cache]);
790
+			} else {
791
+				//that thing was never cached anyways.
792
+				$obj_removed = null;
793
+			}
794
+		}
795
+		return $obj_removed;
796
+	}
797
+
798
+
799
+
800
+	/**
801
+	 * update_cache_after_object_save
802
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
803
+	 * obtained after being saved to the db
804
+	 *
805
+	 * @param string         $relationName       - the type of object that is cached
806
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
807
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
808
+	 * @return boolean TRUE on success, FALSE on fail
809
+	 * @throws \EE_Error
810
+	 */
811
+	public function update_cache_after_object_save(
812
+		$relationName,
813
+		EE_Base_Class $newly_saved_object,
814
+		$current_cache_id = ''
815
+	) {
816
+		// verify that incoming object is of the correct type
817
+		$obj_class = 'EE_' . $relationName;
818
+		if ($newly_saved_object instanceof $obj_class) {
819
+			/* @type EE_Base_Class $newly_saved_object */
820
+			// now get the type of relation
821
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
822
+			// if this is a 1:1 relationship
823
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
824
+				// then just replace the cached object with the newly saved object
825
+				$this->_model_relations[$relationName] = $newly_saved_object;
826
+				return true;
827
+				// or if it's some kind of sordid feral polyamorous relationship...
828
+			} elseif (is_array($this->_model_relations[$relationName])
829
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
830
+			) {
831
+				// then remove the current cached item
832
+				unset($this->_model_relations[$relationName][$current_cache_id]);
833
+				// and cache the newly saved object using it's new ID
834
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
835
+				return true;
836
+			}
837
+		}
838
+		return false;
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
845
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
846
+	 *
847
+	 * @param string $relationName
848
+	 * @return EE_Base_Class
849
+	 */
850
+	public function get_one_from_cache($relationName)
851
+	{
852
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
853
+			: null;
854
+		if (is_array($cached_array_or_object)) {
855
+			return array_shift($cached_array_or_object);
856
+		} else {
857
+			return $cached_array_or_object;
858
+		}
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
865
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
866
+	 *
867
+	 * @param string $relationName
868
+	 * @throws \EE_Error
869
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
870
+	 */
871
+	public function get_all_from_cache($relationName)
872
+	{
873
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
874
+		// if the result is not an array, but exists, make it an array
875
+		$objects = is_array($objects) ? $objects : array($objects);
876
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
877
+		//basically, if this model object was stored in the session, and these cached model objects
878
+		//already have IDs, let's make sure they're in their model's entity mapper
879
+		//otherwise we will have duplicates next time we call
880
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
881
+		$model = EE_Registry::instance()->load_model($relationName);
882
+		foreach ($objects as $model_object) {
883
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
884
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
885
+				if ($model_object->ID()) {
886
+					$model->add_to_entity_map($model_object);
887
+				}
888
+			} else {
889
+				throw new EE_Error(
890
+					sprintf(
891
+						__(
892
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
893
+							'event_espresso'
894
+						),
895
+						$relationName,
896
+						gettype($model_object)
897
+					)
898
+				);
899
+			}
900
+		}
901
+		return $objects;
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
908
+	 * matching the given query conditions.
909
+	 *
910
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
911
+	 * @param int   $limit              How many objects to return.
912
+	 * @param array $query_params       Any additional conditions on the query.
913
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
914
+	 *                                  you can indicate just the columns you want returned
915
+	 * @return array|EE_Base_Class[]
916
+	 * @throws \EE_Error
917
+	 */
918
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
919
+	{
920
+		$model = $this->get_model();
921
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
922
+			? $model->get_primary_key_field()->get_name()
923
+			: $field_to_order_by;
924
+		$current_value = ! empty($field) ? $this->get($field) : null;
925
+		if (empty($field) || empty($current_value)) {
926
+			return array();
927
+		}
928
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
935
+	 * matching the given query conditions.
936
+	 *
937
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
938
+	 * @param int   $limit              How many objects to return.
939
+	 * @param array $query_params       Any additional conditions on the query.
940
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
941
+	 *                                  you can indicate just the columns you want returned
942
+	 * @return array|EE_Base_Class[]
943
+	 * @throws \EE_Error
944
+	 */
945
+	public function previous_x(
946
+		$field_to_order_by = null,
947
+		$limit = 1,
948
+		$query_params = array(),
949
+		$columns_to_select = null
950
+	) {
951
+		$model = $this->get_model();
952
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
953
+			? $model->get_primary_key_field()->get_name()
954
+			: $field_to_order_by;
955
+		$current_value = ! empty($field) ? $this->get($field) : null;
956
+		if (empty($field) || empty($current_value)) {
957
+			return array();
958
+		}
959
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
960
+	}
961
+
962
+
963
+
964
+	/**
965
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
966
+	 * matching the given query conditions.
967
+	 *
968
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
969
+	 * @param array $query_params       Any additional conditions on the query.
970
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
971
+	 *                                  you can indicate just the columns you want returned
972
+	 * @return array|EE_Base_Class
973
+	 * @throws \EE_Error
974
+	 */
975
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
976
+	{
977
+		$model = $this->get_model();
978
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
979
+			? $model->get_primary_key_field()->get_name()
980
+			: $field_to_order_by;
981
+		$current_value = ! empty($field) ? $this->get($field) : null;
982
+		if (empty($field) || empty($current_value)) {
983
+			return array();
984
+		}
985
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
992
+	 * matching the given query conditions.
993
+	 *
994
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
995
+	 * @param array $query_params       Any additional conditions on the query.
996
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
997
+	 *                                  you can indicate just the column you want returned
998
+	 * @return array|EE_Base_Class
999
+	 * @throws \EE_Error
1000
+	 */
1001
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1002
+	{
1003
+		$model = $this->get_model();
1004
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1005
+			? $model->get_primary_key_field()->get_name()
1006
+			: $field_to_order_by;
1007
+		$current_value = ! empty($field) ? $this->get($field) : null;
1008
+		if (empty($field) || empty($current_value)) {
1009
+			return array();
1010
+		}
1011
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1012
+	}
1013
+
1014
+
1015
+
1016
+	/**
1017
+	 * Overrides parent because parent expects old models.
1018
+	 * This also doesn't do any validation, and won't work for serialized arrays
1019
+	 *
1020
+	 * @param string $field_name
1021
+	 * @param mixed  $field_value_from_db
1022
+	 * @throws \EE_Error
1023
+	 */
1024
+	public function set_from_db($field_name, $field_value_from_db)
1025
+	{
1026
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1027
+		if ($field_obj instanceof EE_Model_Field_Base) {
1028
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1029
+			//eg, a CPT model object could have an entry in the posts table, but no
1030
+			//entry in the meta table. Meaning that all its columns in the meta table
1031
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1032
+			if ($field_value_from_db === null) {
1033
+				if ($field_obj->is_nullable()) {
1034
+					//if the field allows nulls, then let it be null
1035
+					$field_value = null;
1036
+				} else {
1037
+					$field_value = $field_obj->get_default_value();
1038
+				}
1039
+			} else {
1040
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1041
+			}
1042
+			$this->_fields[$field_name] = $field_value;
1043
+			$this->_clear_cached_property($field_name);
1044
+		}
1045
+	}
1046
+
1047
+
1048
+
1049
+	/**
1050
+	 * verifies that the specified field is of the correct type
1051
+	 *
1052
+	 * @param string $field_name
1053
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1054
+	 *                                (in cases where the same property may be used for different outputs
1055
+	 *                                - i.e. datetime, money etc.)
1056
+	 * @return mixed
1057
+	 * @throws \EE_Error
1058
+	 */
1059
+	public function get($field_name, $extra_cache_ref = null)
1060
+	{
1061
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1062
+	}
1063
+
1064
+
1065
+
1066
+	/**
1067
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1068
+	 *
1069
+	 * @param  string $field_name A valid fieldname
1070
+	 * @return mixed              Whatever the raw value stored on the property is.
1071
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1072
+	 */
1073
+	public function get_raw($field_name)
1074
+	{
1075
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1076
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1077
+			? $this->_fields[$field_name]->format('U')
1078
+			: $this->_fields[$field_name];
1079
+	}
1080
+
1081
+
1082
+
1083
+	/**
1084
+	 * This is used to return the internal DateTime object used for a field that is a
1085
+	 * EE_Datetime_Field.
1086
+	 *
1087
+	 * @param string $field_name               The field name retrieving the DateTime object.
1088
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1089
+	 * @throws \EE_Error
1090
+	 *                                         an error is set and false returned.  If the field IS an
1091
+	 *                                         EE_Datetime_Field and but the field value is null, then
1092
+	 *                                         just null is returned (because that indicates that likely
1093
+	 *                                         this field is nullable).
1094
+	 */
1095
+	public function get_DateTime_object($field_name)
1096
+	{
1097
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1098
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1099
+			EE_Error::add_error(
1100
+				sprintf(
1101
+					__(
1102
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1103
+						'event_espresso'
1104
+					),
1105
+					$field_name
1106
+				),
1107
+				__FILE__,
1108
+				__FUNCTION__,
1109
+				__LINE__
1110
+			);
1111
+			return false;
1112
+		}
1113
+		return $this->_fields[$field_name];
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * To be used in template to immediately echo out the value, and format it for output.
1120
+	 * Eg, should call stripslashes and whatnot before echoing
1121
+	 *
1122
+	 * @param string $field_name      the name of the field as it appears in the DB
1123
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1124
+	 *                                (in cases where the same property may be used for different outputs
1125
+	 *                                - i.e. datetime, money etc.)
1126
+	 * @return void
1127
+	 * @throws \EE_Error
1128
+	 */
1129
+	public function e($field_name, $extra_cache_ref = null)
1130
+	{
1131
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1132
+	}
1133
+
1134
+
1135
+
1136
+	/**
1137
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1138
+	 * can be easily used as the value of form input.
1139
+	 *
1140
+	 * @param string $field_name
1141
+	 * @return void
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function f($field_name)
1145
+	{
1146
+		$this->e($field_name, 'form_input');
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1153
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1154
+	 * to see what options are available.
1155
+	 * @param string $field_name
1156
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
+	 *                                (in cases where the same property may be used for different outputs
1158
+	 *                                - i.e. datetime, money etc.)
1159
+	 * @return mixed
1160
+	 * @throws \EE_Error
1161
+	 */
1162
+	public function get_pretty($field_name, $extra_cache_ref = null)
1163
+	{
1164
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1165
+	}
1166
+
1167
+
1168
+
1169
+	/**
1170
+	 * This simply returns the datetime for the given field name
1171
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1172
+	 * (and the equivalent e_date, e_time, e_datetime).
1173
+	 *
1174
+	 * @access   protected
1175
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1176
+	 * @param string   $dt_frmt      valid datetime format used for date
1177
+	 *                               (if '' then we just use the default on the field,
1178
+	 *                               if NULL we use the last-used format)
1179
+	 * @param string   $tm_frmt      Same as above except this is for time format
1180
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1181
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1182
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1183
+	 *                               if field is not a valid dtt field, or void if echoing
1184
+	 * @throws \EE_Error
1185
+	 */
1186
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1187
+	{
1188
+		// clear cached property
1189
+		$this->_clear_cached_property($field_name);
1190
+		//reset format properties because they are used in get()
1191
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1192
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1193
+		if ($echo) {
1194
+			$this->e($field_name, $date_or_time);
1195
+			return '';
1196
+		}
1197
+		return $this->get($field_name, $date_or_time);
1198
+	}
1199
+
1200
+
1201
+
1202
+	/**
1203
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1204
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1205
+	 * other echoes the pretty value for dtt)
1206
+	 *
1207
+	 * @param  string $field_name name of model object datetime field holding the value
1208
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1209
+	 * @return string            datetime value formatted
1210
+	 * @throws \EE_Error
1211
+	 */
1212
+	public function get_date($field_name, $format = '')
1213
+	{
1214
+		return $this->_get_datetime($field_name, $format, null, 'D');
1215
+	}
1216
+
1217
+
1218
+
1219
+	/**
1220
+	 * @param      $field_name
1221
+	 * @param string $format
1222
+	 * @throws \EE_Error
1223
+	 */
1224
+	public function e_date($field_name, $format = '')
1225
+	{
1226
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1233
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1234
+	 * other echoes the pretty value for dtt)
1235
+	 *
1236
+	 * @param  string $field_name name of model object datetime field holding the value
1237
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1238
+	 * @return string             datetime value formatted
1239
+	 * @throws \EE_Error
1240
+	 */
1241
+	public function get_time($field_name, $format = '')
1242
+	{
1243
+		return $this->_get_datetime($field_name, null, $format, 'T');
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 * @param      $field_name
1250
+	 * @param string $format
1251
+	 * @throws \EE_Error
1252
+	 */
1253
+	public function e_time($field_name, $format = '')
1254
+	{
1255
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1256
+	}
1257
+
1258
+
1259
+
1260
+	/**
1261
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1262
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1263
+	 * other echoes the pretty value for dtt)
1264
+	 *
1265
+	 * @param  string $field_name name of model object datetime field holding the value
1266
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1267
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1268
+	 * @return string             datetime value formatted
1269
+	 * @throws \EE_Error
1270
+	 */
1271
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1272
+	{
1273
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1274
+	}
1275
+
1276
+
1277
+
1278
+	/**
1279
+	 * @param string $field_name
1280
+	 * @param string $dt_frmt
1281
+	 * @param string $tm_frmt
1282
+	 * @throws \EE_Error
1283
+	 */
1284
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1285
+	{
1286
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1287
+	}
1288
+
1289
+
1290
+
1291
+	/**
1292
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1293
+	 *
1294
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1295
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1296
+	 *                           on the object will be used.
1297
+	 * @return string Date and time string in set locale or false if no field exists for the given
1298
+	 * @throws \EE_Error
1299
+	 *                           field name.
1300
+	 */
1301
+	public function get_i18n_datetime($field_name, $format = '')
1302
+	{
1303
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1304
+		return date_i18n(
1305
+			$format,
1306
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1307
+		);
1308
+	}
1309
+
1310
+
1311
+
1312
+	/**
1313
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1314
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1315
+	 * thrown.
1316
+	 *
1317
+	 * @param  string $field_name The field name being checked
1318
+	 * @throws EE_Error
1319
+	 * @return EE_Datetime_Field
1320
+	 */
1321
+	protected function _get_dtt_field_settings($field_name)
1322
+	{
1323
+		$field = $this->get_model()->field_settings_for($field_name);
1324
+		//check if field is dtt
1325
+		if ($field instanceof EE_Datetime_Field) {
1326
+			return $field;
1327
+		} else {
1328
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1329
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1330
+		}
1331
+	}
1332
+
1333
+
1334
+
1335
+
1336
+	/**
1337
+	 * NOTE ABOUT BELOW:
1338
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1339
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1340
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1341
+	 * method and make sure you send the entire datetime value for setting.
1342
+	 */
1343
+	/**
1344
+	 * sets the time on a datetime property
1345
+	 *
1346
+	 * @access protected
1347
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1348
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1349
+	 * @throws \EE_Error
1350
+	 */
1351
+	protected function _set_time_for($time, $fieldname)
1352
+	{
1353
+		$this->_set_date_time('T', $time, $fieldname);
1354
+	}
1355
+
1356
+
1357
+
1358
+	/**
1359
+	 * sets the date on a datetime property
1360
+	 *
1361
+	 * @access protected
1362
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1363
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1364
+	 * @throws \EE_Error
1365
+	 */
1366
+	protected function _set_date_for($date, $fieldname)
1367
+	{
1368
+		$this->_set_date_time('D', $date, $fieldname);
1369
+	}
1370
+
1371
+
1372
+
1373
+	/**
1374
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1375
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1376
+	 *
1377
+	 * @access protected
1378
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1379
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1380
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1381
+	 *                                        EE_Datetime_Field property)
1382
+	 * @throws \EE_Error
1383
+	 */
1384
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1385
+	{
1386
+		$field = $this->_get_dtt_field_settings($fieldname);
1387
+		$field->set_timezone($this->_timezone);
1388
+		$field->set_date_format($this->_dt_frmt);
1389
+		$field->set_time_format($this->_tm_frmt);
1390
+		switch ($what) {
1391
+			case 'T' :
1392
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1393
+					$datetime_value,
1394
+					$this->_fields[$fieldname]
1395
+				);
1396
+				break;
1397
+			case 'D' :
1398
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1399
+					$datetime_value,
1400
+					$this->_fields[$fieldname]
1401
+				);
1402
+				break;
1403
+			case 'B' :
1404
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1405
+				break;
1406
+		}
1407
+		$this->_clear_cached_property($fieldname);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1414
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1415
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1416
+	 * that could lead to some unexpected results!
1417
+	 *
1418
+	 * @access public
1419
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1420
+	 *                                         value being returned.
1421
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1422
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1423
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1424
+	 * @param string               $append     You can include something to append on the timestamp
1425
+	 * @throws EE_Error
1426
+	 * @return string timestamp
1427
+	 */
1428
+	public function display_in_my_timezone(
1429
+		$field_name,
1430
+		$callback = 'get_datetime',
1431
+		$args = null,
1432
+		$prepend = '',
1433
+		$append = ''
1434
+	) {
1435
+		$timezone = EEH_DTT_Helper::get_timezone();
1436
+		if ($timezone === $this->_timezone) {
1437
+			return '';
1438
+		}
1439
+		$original_timezone = $this->_timezone;
1440
+		$this->set_timezone($timezone);
1441
+		$fn = (array)$field_name;
1442
+		$args = array_merge($fn, (array)$args);
1443
+		if ( ! method_exists($this, $callback)) {
1444
+			throw new EE_Error(
1445
+				sprintf(
1446
+					__(
1447
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1448
+						'event_espresso'
1449
+					),
1450
+					$callback
1451
+				)
1452
+			);
1453
+		}
1454
+		$args = (array)$args;
1455
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1456
+		$this->set_timezone($original_timezone);
1457
+		return $return;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * Deletes this model object.
1464
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1465
+	 * override
1466
+	 * `EE_Base_Class::_delete` NOT this class.
1467
+	 *
1468
+	 * @return boolean | int
1469
+	 * @throws \EE_Error
1470
+	 */
1471
+	public function delete()
1472
+	{
1473
+		/**
1474
+		 * Called just before the `EE_Base_Class::_delete` method call.
1475
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1476
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1477
+		 * soft deletes (trash) the object and does not permanently delete it.
1478
+		 *
1479
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1480
+		 */
1481
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1482
+		$result = $this->_delete();
1483
+		/**
1484
+		 * Called just after the `EE_Base_Class::_delete` method call.
1485
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1486
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1487
+		 * soft deletes (trash) the object and does not permanently delete it.
1488
+		 *
1489
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1490
+		 * @param boolean       $result
1491
+		 */
1492
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1493
+		return $result;
1494
+	}
1495
+
1496
+
1497
+
1498
+	/**
1499
+	 * Calls the specific delete method for the instantiated class.
1500
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1501
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1502
+	 * `EE_Base_Class::delete`
1503
+	 *
1504
+	 * @return bool|int
1505
+	 * @throws \EE_Error
1506
+	 */
1507
+	protected function _delete()
1508
+	{
1509
+		return $this->delete_permanently();
1510
+	}
1511
+
1512
+
1513
+
1514
+	/**
1515
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1516
+	 * error)
1517
+	 *
1518
+	 * @return bool | int
1519
+	 * @throws \EE_Error
1520
+	 */
1521
+	public function delete_permanently()
1522
+	{
1523
+		/**
1524
+		 * Called just before HARD deleting a model object
1525
+		 *
1526
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1527
+		 */
1528
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1529
+		$model = $this->get_model();
1530
+		$result = $model->delete_permanently_by_ID($this->ID());
1531
+		$this->refresh_cache_of_related_objects();
1532
+		/**
1533
+		 * Called just after HARD deleting a model object
1534
+		 *
1535
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1536
+		 * @param boolean       $result
1537
+		 */
1538
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1539
+		return $result;
1540
+	}
1541
+
1542
+
1543
+
1544
+	/**
1545
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1546
+	 * related model objects
1547
+	 *
1548
+	 * @throws \EE_Error
1549
+	 */
1550
+	public function refresh_cache_of_related_objects()
1551
+	{
1552
+		$model = $this->get_model();
1553
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1554
+			if ( ! empty($this->_model_relations[$relation_name])) {
1555
+				$related_objects = $this->_model_relations[$relation_name];
1556
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1557
+					//this relation only stores a single model object, not an array
1558
+					//but let's make it consistent
1559
+					$related_objects = array($related_objects);
1560
+				}
1561
+				foreach ($related_objects as $related_object) {
1562
+					//only refresh their cache if they're in memory
1563
+					if ($related_object instanceof EE_Base_Class) {
1564
+						$related_object->clear_cache($model->get_this_model_name(), $this);
1565
+					}
1566
+				}
1567
+			}
1568
+		}
1569
+	}
1570
+
1571
+
1572
+
1573
+	/**
1574
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1575
+	 * object just before saving.
1576
+	 *
1577
+	 * @access public
1578
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1579
+	 *                                 if provided during the save() method (often client code will change the fields'
1580
+	 *                                 values before calling save)
1581
+	 * @throws \EE_Error
1582
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1583
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1584
+	 */
1585
+	public function save($set_cols_n_values = array())
1586
+	{
1587
+		$model = $this->get_model();
1588
+		/**
1589
+		 * Filters the fields we're about to save on the model object
1590
+		 *
1591
+		 * @param array         $set_cols_n_values
1592
+		 * @param EE_Base_Class $model_object
1593
+		 */
1594
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1595
+			$this);
1596
+		//set attributes as provided in $set_cols_n_values
1597
+		foreach ($set_cols_n_values as $column => $value) {
1598
+			$this->set($column, $value);
1599
+		}
1600
+		// no changes ? then don't do anything
1601
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1602
+			return 0;
1603
+		}
1604
+		/**
1605
+		 * Saving a model object.
1606
+		 * Before we perform a save, this action is fired.
1607
+		 *
1608
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1609
+		 */
1610
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1611
+		if ( ! $this->allow_persist()) {
1612
+			return 0;
1613
+		}
1614
+		//now get current attribute values
1615
+		$save_cols_n_values = $this->_fields;
1616
+		//if the object already has an ID, update it. Otherwise, insert it
1617
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1618
+		$old_assumption_concerning_value_preparation = $model
1619
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1620
+		$model->assume_values_already_prepared_by_model_object(true);
1621
+		//does this model have an autoincrement PK?
1622
+		if ($model->has_primary_key_field()) {
1623
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1624
+				//ok check if it's set, if so: update; if not, insert
1625
+				if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1626
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1627
+				} else {
1628
+					unset($save_cols_n_values[$model->primary_key_name()]);
1629
+					$results = $model->insert($save_cols_n_values);
1630
+					if ($results) {
1631
+						//if successful, set the primary key
1632
+						//but don't use the normal SET method, because it will check if
1633
+						//an item with the same ID exists in the mapper & db, then
1634
+						//will find it in the db (because we just added it) and THAT object
1635
+						//will get added to the mapper before we can add this one!
1636
+						//but if we just avoid using the SET method, all that headache can be avoided
1637
+						$pk_field_name = $model->primary_key_name();
1638
+						$this->_fields[$pk_field_name] = $results;
1639
+						$this->_clear_cached_property($pk_field_name);
1640
+						$model->add_to_entity_map($this);
1641
+						$this->_update_cached_related_model_objs_fks();
1642
+					}
1643
+				}
1644
+			} else {//PK is NOT auto-increment
1645
+				//so check if one like it already exists in the db
1646
+				if ($model->exists_by_ID($this->ID())) {
1647
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1648
+						throw new EE_Error(
1649
+							sprintf(
1650
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1651
+									'event_espresso'),
1652
+								get_class($this),
1653
+								get_class($model) . '::instance()->add_to_entity_map()',
1654
+								get_class($model) . '::instance()->get_one_by_ID()',
1655
+								'<br />'
1656
+							)
1657
+						);
1658
+					}
1659
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1660
+				} else {
1661
+					$results = $model->insert($save_cols_n_values);
1662
+					$this->_update_cached_related_model_objs_fks();
1663
+				}
1664
+			}
1665
+		} else {//there is NO primary key
1666
+			$already_in_db = false;
1667
+			foreach ($model->unique_indexes() as $index) {
1668
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1669
+				if ($model->exists(array($uniqueness_where_params))) {
1670
+					$already_in_db = true;
1671
+				}
1672
+			}
1673
+			if ($already_in_db) {
1674
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1675
+					$model->get_combined_primary_key_fields());
1676
+				$results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1677
+			} else {
1678
+				$results = $model->insert($save_cols_n_values);
1679
+			}
1680
+		}
1681
+		//restore the old assumption about values being prepared by the model object
1682
+		$model
1683
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1684
+		/**
1685
+		 * After saving the model object this action is called
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object which was just saved
1688
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1689
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1690
+		 */
1691
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1692
+		$this->_has_changes = false;
1693
+		return $results;
1694
+	}
1695
+
1696
+
1697
+
1698
+	/**
1699
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1700
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1701
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1702
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1703
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1704
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1705
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1706
+	 *
1707
+	 * @return void
1708
+	 * @throws \EE_Error
1709
+	 */
1710
+	protected function _update_cached_related_model_objs_fks()
1711
+	{
1712
+		$model = $this->get_model();
1713
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1714
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1715
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1716
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1717
+						$model->get_this_model_name()
1718
+					);
1719
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1720
+					if ($related_model_obj_in_cache->ID()) {
1721
+						$related_model_obj_in_cache->save();
1722
+					}
1723
+				}
1724
+			}
1725
+		}
1726
+	}
1727
+
1728
+
1729
+
1730
+	/**
1731
+	 * Saves this model object and its NEW cached relations to the database.
1732
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1733
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1734
+	 * because otherwise, there's a potential for infinite looping of saving
1735
+	 * Saves the cached related model objects, and ensures the relation between them
1736
+	 * and this object and properly setup
1737
+	 *
1738
+	 * @return int ID of new model object on save; 0 on failure+
1739
+	 * @throws \EE_Error
1740
+	 */
1741
+	public function save_new_cached_related_model_objs()
1742
+	{
1743
+		//make sure this has been saved
1744
+		if ( ! $this->ID()) {
1745
+			$id = $this->save();
1746
+		} else {
1747
+			$id = $this->ID();
1748
+		}
1749
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1750
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1751
+			if ($this->_model_relations[$relationName]) {
1752
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1753
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1754
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1755
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1756
+					//but ONLY if it DOES NOT exist in the DB
1757
+					/* @var $related_model_obj EE_Base_Class */
1758
+					$related_model_obj = $this->_model_relations[$relationName];
1759
+					//					if( ! $related_model_obj->ID()){
1760
+					$this->_add_relation_to($related_model_obj, $relationName);
1761
+					$related_model_obj->save_new_cached_related_model_objs();
1762
+					//					}
1763
+				} else {
1764
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1765
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1766
+						//but ONLY if it DOES NOT exist in the DB
1767
+						//						if( ! $related_model_obj->ID()){
1768
+						$this->_add_relation_to($related_model_obj, $relationName);
1769
+						$related_model_obj->save_new_cached_related_model_objs();
1770
+						//						}
1771
+					}
1772
+				}
1773
+			}
1774
+		}
1775
+		return $id;
1776
+	}
1777
+
1778
+
1779
+
1780
+	/**
1781
+	 * for getting a model while instantiated.
1782
+	 *
1783
+	 * @return \EEM_Base | \EEM_CPT_Base
1784
+	 */
1785
+	public function get_model()
1786
+	{
1787
+		if( ! $this->_model){
1788
+			$modelName = self::_get_model_classname(get_class($this));
1789
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1790
+		} else {
1791
+			$this->_model->set_timezone($this->_timezone);
1792
+		}
1793
+
1794
+		return $this->_model;
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * @param $props_n_values
1801
+	 * @param $classname
1802
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1803
+	 * @throws \EE_Error
1804
+	 */
1805
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1806
+	{
1807
+		//TODO: will not work for Term_Relationships because they have no PK!
1808
+		$primary_id_ref = self::_get_primary_key_name($classname);
1809
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1810
+			$id = $props_n_values[$primary_id_ref];
1811
+			return self::_get_model($classname)->get_from_entity_map($id);
1812
+		}
1813
+		return false;
1814
+	}
1815
+
1816
+
1817
+
1818
+	/**
1819
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1820
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1821
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1822
+	 * we return false.
1823
+	 *
1824
+	 * @param  array  $props_n_values   incoming array of properties and their values
1825
+	 * @param  string $classname        the classname of the child class
1826
+	 * @param null    $timezone
1827
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1828
+	 *                                  date_format and the second value is the time format
1829
+	 * @return mixed (EE_Base_Class|bool)
1830
+	 * @throws \EE_Error
1831
+	 */
1832
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1833
+	{
1834
+		$existing = null;
1835
+		$model = self::_get_model($classname, $timezone);
1836
+		if ($model->has_primary_key_field()) {
1837
+			$primary_id_ref = self::_get_primary_key_name($classname);
1838
+			if (array_key_exists($primary_id_ref, $props_n_values)
1839
+				&& ! empty($props_n_values[$primary_id_ref])
1840
+			) {
1841
+				$existing = $model->get_one_by_ID(
1842
+					$props_n_values[$primary_id_ref]
1843
+				);
1844
+			}
1845
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1846
+			//no primary key on this model, but there's still a matching item in the DB
1847
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1848
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1849
+			);
1850
+		}
1851
+		if ($existing) {
1852
+			//set date formats if present before setting values
1853
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1854
+				$existing->set_date_format($date_formats[0]);
1855
+				$existing->set_time_format($date_formats[1]);
1856
+			} else {
1857
+				//set default formats for date and time
1858
+				$existing->set_date_format(get_option('date_format'));
1859
+				$existing->set_time_format(get_option('time_format'));
1860
+			}
1861
+			foreach ($props_n_values as $property => $field_value) {
1862
+				$existing->set($property, $field_value);
1863
+			}
1864
+			return $existing;
1865
+		} else {
1866
+			return false;
1867
+		}
1868
+	}
1869
+
1870
+
1871
+
1872
+	/**
1873
+	 * Gets the EEM_*_Model for this class
1874
+	 *
1875
+	 * @access public now, as this is more convenient
1876
+	 * @param      $classname
1877
+	 * @param null $timezone
1878
+	 * @throws EE_Error
1879
+	 * @return EEM_Base
1880
+	 */
1881
+	protected static function _get_model($classname, $timezone = null)
1882
+	{
1883
+		//find model for this class
1884
+		if ( ! $classname) {
1885
+			throw new EE_Error(
1886
+				sprintf(
1887
+					__(
1888
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1889
+						"event_espresso"
1890
+					),
1891
+					$classname
1892
+				)
1893
+			);
1894
+		}
1895
+		$modelName = self::_get_model_classname($classname);
1896
+		return self::_get_model_instance_with_name($modelName, $timezone);
1897
+	}
1898
+
1899
+
1900
+
1901
+	/**
1902
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1903
+	 *
1904
+	 * @param string $model_classname
1905
+	 * @param null   $timezone
1906
+	 * @return EEM_Base
1907
+	 */
1908
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1909
+	{
1910
+		$model_classname = str_replace('EEM_', '', $model_classname);
1911
+		$model = EE_Registry::instance()->load_model($model_classname);
1912
+		$model->set_timezone($timezone);
1913
+		return $model;
1914
+	}
1915
+
1916
+
1917
+
1918
+	/**
1919
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1920
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1921
+	 *
1922
+	 * @param null $model_name
1923
+	 * @return string like EEM_Attendee
1924
+	 */
1925
+	private static function _get_model_classname($model_name = null)
1926
+	{
1927
+		if (strpos($model_name, "EE_") === 0) {
1928
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1929
+		} else {
1930
+			$model_classname = "EEM_" . $model_name;
1931
+		}
1932
+		return $model_classname;
1933
+	}
1934
+
1935
+
1936
+
1937
+	/**
1938
+	 * returns the name of the primary key attribute
1939
+	 *
1940
+	 * @param null $classname
1941
+	 * @throws EE_Error
1942
+	 * @return string
1943
+	 */
1944
+	protected static function _get_primary_key_name($classname = null)
1945
+	{
1946
+		if ( ! $classname) {
1947
+			throw new EE_Error(
1948
+				sprintf(
1949
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1950
+					$classname
1951
+				)
1952
+			);
1953
+		}
1954
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1955
+	}
1956
+
1957
+
1958
+
1959
+	/**
1960
+	 * Gets the value of the primary key.
1961
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1962
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1963
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1964
+	 *
1965
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1966
+	 * @throws \EE_Error
1967
+	 */
1968
+	public function ID()
1969
+	{
1970
+		$model = $this->get_model();
1971
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1972
+		if ($model->has_primary_key_field()) {
1973
+			return $this->_fields[$model->primary_key_name()];
1974
+		} else {
1975
+			return $model->get_index_primary_key_string($this->_fields);
1976
+		}
1977
+	}
1978
+
1979
+
1980
+
1981
+	/**
1982
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1983
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1984
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1985
+	 *
1986
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1987
+	 * @param string $relationName                     eg 'Events','Question',etc.
1988
+	 *                                                 an attendee to a group, you also want to specify which role they
1989
+	 *                                                 will have in that group. So you would use this parameter to
1990
+	 *                                                 specify array('role-column-name'=>'role-id')
1991
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1992
+	 *                                                 allow you to further constrict the relation to being added.
1993
+	 *                                                 However, keep in mind that the columns (keys) given must match a
1994
+	 *                                                 column on the JOIN table and currently only the HABTM models
1995
+	 *                                                 accept these additional conditions.  Also remember that if an
1996
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
1997
+	 *                                                 NEW row is created in the join table.
1998
+	 * @param null   $cache_id
1999
+	 * @throws EE_Error
2000
+	 * @return EE_Base_Class the object the relation was added to
2001
+	 */
2002
+	public function _add_relation_to(
2003
+		$otherObjectModelObjectOrID,
2004
+		$relationName,
2005
+		$extra_join_model_fields_n_values = array(),
2006
+		$cache_id = null
2007
+	) {
2008
+		$model = $this->get_model();
2009
+		//if this thing exists in the DB, save the relation to the DB
2010
+		if ($this->ID()) {
2011
+			$otherObject = $model
2012
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2013
+									$extra_join_model_fields_n_values);
2014
+			//clear cache so future get_many_related and get_first_related() return new results.
2015
+			$this->clear_cache($relationName, $otherObject, true);
2016
+			if ($otherObject instanceof EE_Base_Class) {
2017
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2018
+			}
2019
+		} else {
2020
+			//this thing doesn't exist in the DB,  so just cache it
2021
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2022
+				throw new EE_Error(sprintf(
2023
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2024
+						'event_espresso'),
2025
+					$otherObjectModelObjectOrID,
2026
+					get_class($this)
2027
+				));
2028
+			} else {
2029
+				$otherObject = $otherObjectModelObjectOrID;
2030
+			}
2031
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2032
+		}
2033
+		if ($otherObject instanceof EE_Base_Class) {
2034
+			//fix the reciprocal relation too
2035
+			if ($otherObject->ID()) {
2036
+				//its saved so assumed relations exist in the DB, so we can just
2037
+				//clear the cache so future queries use the updated info in the DB
2038
+				$otherObject->clear_cache($model->get_this_model_name(), null, true);
2039
+			} else {
2040
+				//it's not saved, so it caches relations like this
2041
+				$otherObject->cache($model->get_this_model_name(), $this);
2042
+			}
2043
+		}
2044
+		return $otherObject;
2045
+	}
2046
+
2047
+
2048
+
2049
+	/**
2050
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2051
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2052
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2053
+	 * from the cache
2054
+	 *
2055
+	 * @param mixed  $otherObjectModelObjectOrID
2056
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2057
+	 *                to the DB yet
2058
+	 * @param string $relationName
2059
+	 * @param array  $where_query
2060
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2061
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2062
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2063
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2064
+	 *                created in the join table.
2065
+	 * @return EE_Base_Class the relation was removed from
2066
+	 * @throws \EE_Error
2067
+	 */
2068
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2069
+	{
2070
+		if ($this->ID()) {
2071
+			//if this exists in the DB, save the relation change to the DB too
2072
+			$otherObject = $this->get_model()
2073
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2074
+									$where_query);
2075
+			$this->clear_cache($relationName, $otherObject);
2076
+		} else {
2077
+			//this doesn't exist in the DB, just remove it from the cache
2078
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2079
+		}
2080
+		if ($otherObject instanceof EE_Base_Class) {
2081
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2082
+		}
2083
+		return $otherObject;
2084
+	}
2085
+
2086
+
2087
+
2088
+	/**
2089
+	 * Removes ALL the related things for the $relationName.
2090
+	 *
2091
+	 * @param string $relationName
2092
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2093
+	 * @return EE_Base_Class
2094
+	 * @throws \EE_Error
2095
+	 */
2096
+	public function _remove_relations($relationName, $where_query_params = array())
2097
+	{
2098
+		if ($this->ID()) {
2099
+			//if this exists in the DB, save the relation change to the DB too
2100
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2101
+			$this->clear_cache($relationName, null, true);
2102
+		} else {
2103
+			//this doesn't exist in the DB, just remove it from the cache
2104
+			$otherObjects = $this->clear_cache($relationName, null, true);
2105
+		}
2106
+		if (is_array($otherObjects)) {
2107
+			foreach ($otherObjects as $otherObject) {
2108
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2109
+			}
2110
+		}
2111
+		return $otherObjects;
2112
+	}
2113
+
2114
+
2115
+
2116
+	/**
2117
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2118
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2119
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2120
+	 * because we want to get even deleted items etc.
2121
+	 *
2122
+	 * @param string $relationName key in the model's _model_relations array
2123
+	 * @param array  $query_params like EEM_Base::get_all
2124
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2125
+	 * @throws \EE_Error
2126
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2127
+	 *                             you want IDs
2128
+	 */
2129
+	public function get_many_related($relationName, $query_params = array())
2130
+	{
2131
+		if ($this->ID()) {
2132
+			//this exists in the DB, so get the related things from either the cache or the DB
2133
+			//if there are query parameters, forget about caching the related model objects.
2134
+			if ($query_params) {
2135
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2136
+			} else {
2137
+				//did we already cache the result of this query?
2138
+				$cached_results = $this->get_all_from_cache($relationName);
2139
+				if ( ! $cached_results) {
2140
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2141
+					//if no query parameters were passed, then we got all the related model objects
2142
+					//for that relation. We can cache them then.
2143
+					foreach ($related_model_objects as $related_model_object) {
2144
+						$this->cache($relationName, $related_model_object);
2145
+					}
2146
+				} else {
2147
+					$related_model_objects = $cached_results;
2148
+				}
2149
+			}
2150
+		} else {
2151
+			//this doesn't exist in the DB, so just get the related things from the cache
2152
+			$related_model_objects = $this->get_all_from_cache($relationName);
2153
+		}
2154
+		return $related_model_objects;
2155
+	}
2156
+
2157
+
2158
+
2159
+	/**
2160
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2161
+	 * unless otherwise specified in the $query_params
2162
+	 *
2163
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2164
+	 * @param array  $query_params   like EEM_Base::get_all's
2165
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2166
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2167
+	 *                               that by the setting $distinct to TRUE;
2168
+	 * @return int
2169
+	 */
2170
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2171
+	{
2172
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2173
+	}
2174
+
2175
+
2176
+
2177
+	/**
2178
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2179
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2180
+	 *
2181
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2182
+	 * @param array  $query_params  like EEM_Base::get_all's
2183
+	 * @param string $field_to_sum  name of field to count by.
2184
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2185
+	 *                              change it)
2186
+	 * @return int
2187
+	 */
2188
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2189
+	{
2190
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2191
+	}
2192
+
2193
+
2194
+
2195
+	/**
2196
+	 * Gets the first (ie, one) related model object of the specified type.
2197
+	 *
2198
+	 * @param string $relationName key in the model's _model_relations array
2199
+	 * @param array  $query_params like EEM_Base::get_all
2200
+	 * @return EE_Base_Class (not an array, a single object)
2201
+	 * @throws \EE_Error
2202
+	 */
2203
+	public function get_first_related($relationName, $query_params = array())
2204
+	{
2205
+		$model = $this->get_model();
2206
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2207
+			//if they've provided some query parameters, don't bother trying to cache the result
2208
+			//also make sure we're not caching the result of get_first_related
2209
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2210
+			if ($query_params
2211
+				|| ! $model->related_settings_for($relationName)
2212
+					 instanceof
2213
+					 EE_Belongs_To_Relation
2214
+			) {
2215
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2216
+			} else {
2217
+				//first, check if we've already cached the result of this query
2218
+				$cached_result = $this->get_one_from_cache($relationName);
2219
+				if ( ! $cached_result) {
2220
+					$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2221
+					$this->cache($relationName, $related_model_object);
2222
+				} else {
2223
+					$related_model_object = $cached_result;
2224
+				}
2225
+			}
2226
+		} else {
2227
+			$related_model_object = null;
2228
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2229
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2230
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2231
+			}
2232
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2233
+			if ( ! $related_model_object) {
2234
+				$related_model_object = $this->get_one_from_cache($relationName);
2235
+			}
2236
+		}
2237
+		return $related_model_object;
2238
+	}
2239
+
2240
+
2241
+
2242
+	/**
2243
+	 * Does a delete on all related objects of type $relationName and removes
2244
+	 * the current model object's relation to them. If they can't be deleted (because
2245
+	 * of blocking related model objects) does nothing. If the related model objects are
2246
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2247
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2248
+	 *
2249
+	 * @param string $relationName
2250
+	 * @param array  $query_params like EEM_Base::get_all's
2251
+	 * @return int how many deleted
2252
+	 * @throws \EE_Error
2253
+	 */
2254
+	public function delete_related($relationName, $query_params = array())
2255
+	{
2256
+		if ($this->ID()) {
2257
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2258
+		} else {
2259
+			$count = count($this->get_all_from_cache($relationName));
2260
+			$this->clear_cache($relationName, null, true);
2261
+		}
2262
+		return $count;
2263
+	}
2264
+
2265
+
2266
+
2267
+	/**
2268
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2269
+	 * the current model object's relation to them. If they can't be deleted (because
2270
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2271
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2272
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2273
+	 *
2274
+	 * @param string $relationName
2275
+	 * @param array  $query_params like EEM_Base::get_all's
2276
+	 * @return int how many deleted (including those soft deleted)
2277
+	 * @throws \EE_Error
2278
+	 */
2279
+	public function delete_related_permanently($relationName, $query_params = array())
2280
+	{
2281
+		if ($this->ID()) {
2282
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2283
+		} else {
2284
+			$count = count($this->get_all_from_cache($relationName));
2285
+		}
2286
+		$this->clear_cache($relationName, null, true);
2287
+		return $count;
2288
+	}
2289
+
2290
+
2291
+
2292
+	/**
2293
+	 * is_set
2294
+	 * Just a simple utility function children can use for checking if property exists
2295
+	 *
2296
+	 * @access  public
2297
+	 * @param  string $field_name property to check
2298
+	 * @return bool                              TRUE if existing,FALSE if not.
2299
+	 */
2300
+	public function is_set($field_name)
2301
+	{
2302
+		return isset($this->_fields[$field_name]);
2303
+	}
2304
+
2305
+
2306
+
2307
+	/**
2308
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2309
+	 * EE_Error exception if they don't
2310
+	 *
2311
+	 * @param  mixed (string|array) $properties properties to check
2312
+	 * @throws EE_Error
2313
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2314
+	 */
2315
+	protected function _property_exists($properties)
2316
+	{
2317
+		foreach ((array)$properties as $property_name) {
2318
+			//first make sure this property exists
2319
+			if ( ! $this->_fields[$property_name]) {
2320
+				throw new EE_Error(
2321
+					sprintf(
2322
+						__(
2323
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2324
+							'event_espresso'
2325
+						),
2326
+						$property_name
2327
+					)
2328
+				);
2329
+			}
2330
+		}
2331
+		return true;
2332
+	}
2333
+
2334
+
2335
+
2336
+	/**
2337
+	 * This simply returns an array of model fields for this object
2338
+	 *
2339
+	 * @return array
2340
+	 * @throws \EE_Error
2341
+	 */
2342
+	public function model_field_array()
2343
+	{
2344
+		$fields = $this->get_model()->field_settings(false);
2345
+		$properties = array();
2346
+		//remove prepended underscore
2347
+		foreach ($fields as $field_name => $settings) {
2348
+			$properties[$field_name] = $this->get($field_name);
2349
+		}
2350
+		return $properties;
2351
+	}
2352
+
2353
+
2354
+
2355
+	/**
2356
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2357
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2358
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2359
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2360
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2361
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2362
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2363
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2364
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2365
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2366
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2367
+	 *        return $previousReturnValue.$returnString;
2368
+	 * }
2369
+	 * require('EE_Answer.class.php');
2370
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2371
+	 * echo $answer->my_callback('monkeys',100);
2372
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2373
+	 *
2374
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2375
+	 * @param array  $args       array of original arguments passed to the function
2376
+	 * @throws EE_Error
2377
+	 * @return mixed whatever the plugin which calls add_filter decides
2378
+	 */
2379
+	public function __call($methodName, $args)
2380
+	{
2381
+		$className = get_class($this);
2382
+		$tagName = "FHEE__{$className}__{$methodName}";
2383
+		if ( ! has_filter($tagName)) {
2384
+			throw new EE_Error(
2385
+				sprintf(
2386
+					__(
2387
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2388
+						"event_espresso"
2389
+					),
2390
+					$methodName,
2391
+					$className,
2392
+					$tagName
2393
+				)
2394
+			);
2395
+		}
2396
+		return apply_filters($tagName, null, $this, $args);
2397
+	}
2398
+
2399
+
2400
+
2401
+	/**
2402
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2403
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2404
+	 *
2405
+	 * @param string $meta_key
2406
+	 * @param mixed  $meta_value
2407
+	 * @param mixed  $previous_value
2408
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2409
+	 * @throws \EE_Error
2410
+	 * NOTE: if the values haven't changed, returns 0
2411
+	 */
2412
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2413
+	{
2414
+		$query_params = array(
2415
+			array(
2416
+				'EXM_key'  => $meta_key,
2417
+				'OBJ_ID'   => $this->ID(),
2418
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2419
+			),
2420
+		);
2421
+		if ($previous_value !== null) {
2422
+			$query_params[0]['EXM_value'] = $meta_value;
2423
+		}
2424
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2425
+		if ( ! $existing_rows_like_that) {
2426
+			return $this->add_extra_meta($meta_key, $meta_value);
2427
+		}
2428
+		foreach ($existing_rows_like_that as $existing_row) {
2429
+			$existing_row->save(array('EXM_value' => $meta_value));
2430
+		}
2431
+		return count($existing_rows_like_that);
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2438
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2439
+	 * extra meta row was entered, false if not
2440
+	 *
2441
+	 * @param string  $meta_key
2442
+	 * @param mixed   $meta_value
2443
+	 * @param boolean $unique
2444
+	 * @return boolean
2445
+	 * @throws \EE_Error
2446
+	 */
2447
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2448
+	{
2449
+		if ($unique) {
2450
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2451
+				array(
2452
+					array(
2453
+						'EXM_key'  => $meta_key,
2454
+						'OBJ_ID'   => $this->ID(),
2455
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2456
+					),
2457
+				)
2458
+			);
2459
+			if ($existing_extra_meta) {
2460
+				return false;
2461
+			}
2462
+		}
2463
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2464
+			array(
2465
+				'EXM_key'   => $meta_key,
2466
+				'EXM_value' => $meta_value,
2467
+				'OBJ_ID'    => $this->ID(),
2468
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2469
+			)
2470
+		);
2471
+		$new_extra_meta->save();
2472
+		return true;
2473
+	}
2474
+
2475
+
2476
+
2477
+	/**
2478
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2479
+	 * is specified, only deletes extra meta records with that value.
2480
+	 *
2481
+	 * @param string $meta_key
2482
+	 * @param mixed  $meta_value
2483
+	 * @return int number of extra meta rows deleted
2484
+	 * @throws \EE_Error
2485
+	 */
2486
+	public function delete_extra_meta($meta_key, $meta_value = null)
2487
+	{
2488
+		$query_params = array(
2489
+			array(
2490
+				'EXM_key'  => $meta_key,
2491
+				'OBJ_ID'   => $this->ID(),
2492
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2493
+			),
2494
+		);
2495
+		if ($meta_value !== null) {
2496
+			$query_params[0]['EXM_value'] = $meta_value;
2497
+		}
2498
+		return EEM_Extra_Meta::instance()->delete($query_params);
2499
+	}
2500
+
2501
+
2502
+
2503
+	/**
2504
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2505
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2506
+	 * You can specify $default is case you haven't found the extra meta
2507
+	 *
2508
+	 * @param string  $meta_key
2509
+	 * @param boolean $single
2510
+	 * @param mixed   $default if we don't find anything, what should we return?
2511
+	 * @return mixed single value if $single; array if ! $single
2512
+	 * @throws \EE_Error
2513
+	 */
2514
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2515
+	{
2516
+		if ($single) {
2517
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2518
+			if ($result instanceof EE_Extra_Meta) {
2519
+				return $result->value();
2520
+			} else {
2521
+				return $default;
2522
+			}
2523
+		} else {
2524
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2525
+			if ($results) {
2526
+				$values = array();
2527
+				foreach ($results as $result) {
2528
+					if ($result instanceof EE_Extra_Meta) {
2529
+						$values[$result->ID()] = $result->value();
2530
+					}
2531
+				}
2532
+				return $values;
2533
+			} else {
2534
+				return $default;
2535
+			}
2536
+		}
2537
+	}
2538
+
2539
+
2540
+
2541
+	/**
2542
+	 * Returns a simple array of all the extra meta associated with this model object.
2543
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2544
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2545
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2546
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2547
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2548
+	 * finally the extra meta's value as each sub-value. (eg
2549
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2550
+	 *
2551
+	 * @param boolean $one_of_each_key
2552
+	 * @return array
2553
+	 * @throws \EE_Error
2554
+	 */
2555
+	public function all_extra_meta_array($one_of_each_key = true)
2556
+	{
2557
+		$return_array = array();
2558
+		if ($one_of_each_key) {
2559
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2560
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2561
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2562
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2563
+				}
2564
+			}
2565
+		} else {
2566
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2567
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2568
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2569
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2570
+						$return_array[$extra_meta_obj->key()] = array();
2571
+					}
2572
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2573
+				}
2574
+			}
2575
+		}
2576
+		return $return_array;
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2583
+	 *
2584
+	 * @return string
2585
+	 * @throws \EE_Error
2586
+	 */
2587
+	public function name()
2588
+	{
2589
+		//find a field that's not a text field
2590
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2591
+		if ($field_we_can_use) {
2592
+			return $this->get($field_we_can_use->get_name());
2593
+		} else {
2594
+			$first_few_properties = $this->model_field_array();
2595
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2596
+			$name_parts = array();
2597
+			foreach ($first_few_properties as $name => $value) {
2598
+				$name_parts[] = "$name:$value";
2599
+			}
2600
+			return implode(",", $name_parts);
2601
+		}
2602
+	}
2603
+
2604
+
2605
+
2606
+	/**
2607
+	 * in_entity_map
2608
+	 * Checks if this model object has been proven to already be in the entity map
2609
+	 *
2610
+	 * @return boolean
2611
+	 * @throws \EE_Error
2612
+	 */
2613
+	public function in_entity_map()
2614
+	{
2615
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2616
+			//well, if we looked, did we find it in the entity map?
2617
+			return true;
2618
+		} else {
2619
+			return false;
2620
+		}
2621
+	}
2622
+
2623
+
2624
+
2625
+	/**
2626
+	 * refresh_from_db
2627
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2628
+	 *
2629
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2630
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2631
+	 */
2632
+	public function refresh_from_db()
2633
+	{
2634
+		if ($this->ID() && $this->in_entity_map()) {
2635
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2636
+		} else {
2637
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2638
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2639
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2640
+			//absolutely nothing in it for this ID
2641
+			if (WP_DEBUG) {
2642
+				throw new EE_Error(
2643
+					sprintf(
2644
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2645
+							'event_espresso'),
2646
+						$this->ID(),
2647
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2648
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2649
+					)
2650
+				);
2651
+			}
2652
+		}
2653
+	}
2654
+
2655
+
2656
+
2657
+	/**
2658
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2659
+	 * (probably a bad assumption they have made, oh well)
2660
+	 *
2661
+	 * @return string
2662
+	 */
2663
+	public function __toString()
2664
+	{
2665
+		try {
2666
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2667
+		} catch (Exception $e) {
2668
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2669
+			return '';
2670
+		}
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2677
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2678
+	 * This means if we have made changes to those related model objects, and want to unserialize
2679
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2680
+	 * Instead, those related model objects should be directly serialized and stored.
2681
+	 * Eg, the following won't work:
2682
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2683
+	 * $att = $reg->attendee();
2684
+	 * $att->set( 'ATT_fname', 'Dirk' );
2685
+	 * update_option( 'my_option', serialize( $reg ) );
2686
+	 * //END REQUEST
2687
+	 * //START NEXT REQUEST
2688
+	 * $reg = get_option( 'my_option' );
2689
+	 * $reg->attendee()->save();
2690
+	 * And would need to be replace with:
2691
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2692
+	 * $att = $reg->attendee();
2693
+	 * $att->set( 'ATT_fname', 'Dirk' );
2694
+	 * update_option( 'my_option', serialize( $reg ) );
2695
+	 * //END REQUEST
2696
+	 * //START NEXT REQUEST
2697
+	 * $att = get_option( 'my_option' );
2698
+	 * $att->save();
2699
+	 *
2700
+	 * @return array
2701
+	 * @throws \EE_Error
2702
+	 */
2703
+	public function __sleep()
2704
+	{
2705
+		$model = $this->get_model();
2706
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2707
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2708
+				$classname = 'EE_' . $model->get_this_model_name();
2709
+				if (
2710
+					$this->get_one_from_cache($relation_name) instanceof $classname
2711
+					&& $this->get_one_from_cache($relation_name)->ID()
2712
+				) {
2713
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2714
+				}
2715
+			}
2716
+		}
2717
+		$this->_props_n_values_provided_in_constructor = array();
2718
+		$properties_to_serialize = get_object_vars($this);
2719
+		//don't serialize the model. It's big and that risks recursion
2720
+		unset($properties_to_serialize['_model']);
2721
+		return array_keys($properties_to_serialize);
2722
+	}
2723
+
2724
+
2725
+
2726
+	/**
2727
+	 * restore _props_n_values_provided_in_constructor
2728
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2729
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2730
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2731
+	 */
2732
+	public function __wakeup()
2733
+	{
2734
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2735
+	}
2736 2736
 
2737 2737
 
2738 2738
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -17 removed lines patch added patch discarded remove patch
@@ -732,7 +732,7 @@  discard block
 block discarded – undo
732 732
 
733 733
 
734 734
     /**
735
-     * @param $model_field_factory
735
+     * @param null|ModelFieldFactory $model_field_factory
736 736
      * @return ModelFieldFactory
737 737
      * @throws InvalidArgumentException
738 738
      * @throws InvalidDataTypeException
@@ -992,7 +992,7 @@  discard block
 block discarded – undo
992 992
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
993 993
      * foreign key to the WP_User table)
994 994
      *
995
-     * @return string|boolean string on success, boolean false when there is no
995
+     * @return string|false string on success, boolean false when there is no
996 996
      * foreign key to the WP_User table
997 997
      */
998 998
     public function wp_user_field_name()
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
      *
1098 1098
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1099 1099
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1100
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1101 1101
      *                                  fields on the model, and the models we joined to in the query. However, you can
1102 1102
      *                                  override this and set the select to "*", or a specific column name, like
1103 1103
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1511,7 +1511,7 @@  discard block
 block discarded – undo
1511 1511
      * @param string $field_name The name of the field the formats are being retrieved for.
1512 1512
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513 1513
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1514
-     * @return array formats in an array with the date format first, and the time format last.
1514
+     * @return string[] formats in an array with the date format first, and the time format last.
1515 1515
      */
1516 1516
     public function get_formats_for($field_name, $pretty = false)
1517 1517
     {
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
      *                                 be returned.
1547 1547
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1548 1548
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1549
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1549
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1550 1550
      *                                 exception is triggered.
1551 1551
      */
1552 1552
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1586,7 +1586,7 @@  discard block
 block discarded – undo
1586 1586
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1587 1587
      *                                format is
1588 1588
      *                                'U', this is ignored.
1589
-     * @return DateTime
1589
+     * @return string
1590 1590
      * @throws EE_Error
1591 1591
      */
1592 1592
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1883,7 +1883,7 @@  discard block
 block discarded – undo
1883 1883
      * Wrapper for EEM_Base::delete_permanently()
1884 1884
      *
1885 1885
      * @param mixed $id
1886
-     * @return boolean whether the row got deleted or not
1886
+     * @return integer whether the row got deleted or not
1887 1887
      * @throws EE_Error
1888 1888
      */
1889 1889
     public function delete_permanently_by_ID($id)
@@ -1903,7 +1903,7 @@  discard block
 block discarded – undo
1903 1903
      * Wrapper for EEM_Base::delete()
1904 1904
      *
1905 1905
      * @param mixed $id
1906
-     * @return boolean whether the row got deleted or not
1906
+     * @return integer whether the row got deleted or not
1907 1907
      * @throws EE_Error
1908 1908
      */
1909 1909
     public function delete_by_ID($id)
@@ -2360,7 +2360,7 @@  discard block
 block discarded – undo
2360 2360
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2361 2361
      * EEM_Base::$_db_verification_level
2362 2362
      *
2363
-     * @param $wpdb_method
2363
+     * @param string $wpdb_method
2364 2364
      * @param $arguments_to_provide
2365 2365
      * @return string
2366 2366
      */
@@ -2484,6 +2484,7 @@  discard block
 block discarded – undo
2484 2484
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2485 2485
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2486 2486
      *                             because these will be inserted in any new rows created as well.
2487
+     * @param EE_Base_Class $id_or_obj
2487 2488
      */
2488 2489
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2489 2490
     {
@@ -2494,7 +2495,7 @@  discard block
 block discarded – undo
2494 2495
 
2495 2496
 
2496 2497
     /**
2497
-     * @param mixed           $id_or_obj
2498
+     * @param EE_Base_Class           $id_or_obj
2498 2499
      * @param string          $relationName
2499 2500
      * @param array           $where_query_params
2500 2501
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2535,7 +2536,7 @@  discard block
 block discarded – undo
2535 2536
      * However, if the model objects can't be deleted because of blocking related model objects, then
2536 2537
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2537 2538
      *
2538
-     * @param EE_Base_Class|int|string $id_or_obj
2539
+     * @param EE_Base_Class $id_or_obj
2539 2540
      * @param string                   $model_name
2540 2541
      * @param array                    $query_params
2541 2542
      * @return int how many deleted
@@ -2556,7 +2557,7 @@  discard block
 block discarded – undo
2556 2557
      * the model objects can't be hard deleted because of blocking related model objects,
2557 2558
      * just does a soft-delete on them instead.
2558 2559
      *
2559
-     * @param EE_Base_Class|int|string $id_or_obj
2560
+     * @param EE_Base_Class $id_or_obj
2560 2561
      * @param string                   $model_name
2561 2562
      * @param array                    $query_params
2562 2563
      * @return int how many deleted
@@ -2613,6 +2614,7 @@  discard block
 block discarded – undo
2613 2614
      * @param string $model_name   like 'Event', or 'Registration'
2614 2615
      * @param array  $query_params like EEM_Base::get_all's
2615 2616
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2617
+     * @param EE_Base_Class $id_or_obj
2616 2618
      * @return float
2617 2619
      * @throws EE_Error
2618 2620
      */
@@ -3082,7 +3084,7 @@  discard block
 block discarded – undo
3082 3084
      * Finds all the fields that correspond to the given table
3083 3085
      *
3084 3086
      * @param string $table_alias , array key in EEM_Base::_tables
3085
-     * @return EE_Model_Field_Base[]
3087
+     * @return EE_Model_Field_Base
3086 3088
      */
3087 3089
     public function _get_fields_for_table($table_alias)
3088 3090
     {
@@ -3573,7 +3575,7 @@  discard block
 block discarded – undo
3573 3575
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3574 3576
      * We should use default where conditions on related models when they requested to use default where conditions
3575 3577
      * on all models, or specifically just on other related models
3576
-     * @param      $default_where_conditions_value
3578
+     * @param      string $default_where_conditions_value
3577 3579
      * @param bool $for_this_model false means this is for OTHER related models
3578 3580
      * @return bool
3579 3581
      */
@@ -3611,7 +3613,7 @@  discard block
 block discarded – undo
3611 3613
      * where conditions.
3612 3614
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3613 3615
      * on this model or others
3614
-     * @param      $default_where_conditions_value
3616
+     * @param      string $default_where_conditions_value
3615 3617
      * @param bool $for_this_model false means this is for OTHER related models
3616 3618
      * @return bool
3617 3619
      */
@@ -4694,7 +4696,7 @@  discard block
 block discarded – undo
4694 4696
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4695 4697
      * Eg, on EE_Answer that would be ANS_ID field object
4696 4698
      *
4697
-     * @param $field_obj
4699
+     * @param EE_Model_Field_Base $field_obj
4698 4700
      * @return boolean
4699 4701
      */
4700 4702
     public function is_primary_key_field($field_obj)
@@ -5412,7 +5414,7 @@  discard block
 block discarded – undo
5412 5414
     /**
5413 5415
      * Read comments for assume_values_already_prepared_by_model_object()
5414 5416
      *
5415
-     * @return int
5417
+     * @return boolean
5416 5418
      */
5417 5419
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5418 5420
     {
Please login to merge, or discard this patch.
Indentation   +5970 added lines, -5970 removed lines patch added patch discarded remove patch
@@ -32,5982 +32,5982 @@
 block discarded – undo
32 32
 abstract class EEM_Base extends EE_Base implements ResettableInterface
33 33
 {
34 34
 
35
-    //admin posty
36
-    //basic -> grants access to mine -> if they don't have it, select none
37
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
-    //*_published -> grants access to published -> if they dont have it, select non-published
40
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
42
-    //frontend posty
43
-    //by default has access to published
44
-    //basic -> grants access to mine that aren't published, and all published
45
-    //*_others ->grants access to others that aren't private, all mine
46
-    //*_private -> grants full access
47
-    //frontend non-posty
48
-    //like admin posty
49
-    //category-y
50
-    //assign -> grants access to join-table
51
-    //(delete, edit)
52
-    //payment-method-y
53
-    //for each registered payment method,
54
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
-    /**
56
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
-     * They almost always WILL NOT, but it's not necessarily a requirement.
59
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
-     *
61
-     * @var boolean
62
-     */
63
-    private $_values_already_prepared_by_model_object = 0;
64
-
65
-    /**
66
-     * when $_values_already_prepared_by_model_object equals this, we assume
67
-     * the data is just like form input that needs to have the model fields'
68
-     * prepare_for_set and prepare_for_use_in_db called on it
69
-     */
70
-    const not_prepared_by_model_object = 0;
71
-
72
-    /**
73
-     * when $_values_already_prepared_by_model_object equals this, we
74
-     * assume this value is coming from a model object and doesn't need to have
75
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
76
-     */
77
-    const prepared_by_model_object = 1;
78
-
79
-    /**
80
-     * when $_values_already_prepared_by_model_object equals this, we assume
81
-     * the values are already to be used in the database (ie no processing is done
82
-     * on them by the model's fields)
83
-     */
84
-    const prepared_for_use_in_db = 2;
85
-
86
-
87
-    protected $singular_item = 'Item';
88
-
89
-    protected $plural_item   = 'Items';
90
-
91
-    /**
92
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
-     */
94
-    protected $_tables;
95
-
96
-    /**
97
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
-     *
101
-     * @var \EE_Model_Field_Base[] $_fields
102
-     */
103
-    protected $_fields;
104
-
105
-    /**
106
-     * array of different kinds of relations
107
-     *
108
-     * @var \EE_Model_Relation_Base[] $_model_relations
109
-     */
110
-    protected $_model_relations;
111
-
112
-    /**
113
-     * @var \EE_Index[] $_indexes
114
-     */
115
-    protected $_indexes = array();
116
-
117
-    /**
118
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
119
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
-     * by setting the same columns as used in these queries in the query yourself.
121
-     *
122
-     * @var EE_Default_Where_Conditions
123
-     */
124
-    protected $_default_where_conditions_strategy;
125
-
126
-    /**
127
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
-     * This is particularly useful when you want something between 'none' and 'default'
129
-     *
130
-     * @var EE_Default_Where_Conditions
131
-     */
132
-    protected $_minimum_where_conditions_strategy;
133
-
134
-    /**
135
-     * String describing how to find the "owner" of this model's objects.
136
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
-     * But when there isn't, this indicates which related model, or transiently-related model,
138
-     * has the foreign key to the wp_users table.
139
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
-     * related to events, and events have a foreign key to wp_users.
141
-     * On EEM_Transaction, this would be 'Transaction.Event'
142
-     *
143
-     * @var string
144
-     */
145
-    protected $_model_chain_to_wp_user = '';
146
-
147
-    /**
148
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
-     * don't need it (particularly CPT models)
150
-     *
151
-     * @var bool
152
-     */
153
-    protected $_ignore_where_strategy = false;
154
-
155
-    /**
156
-     * String used in caps relating to this model. Eg, if the caps relating to this
157
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
-     *
159
-     * @var string. If null it hasn't been initialized yet. If false then we
160
-     * have indicated capabilities don't apply to this
161
-     */
162
-    protected $_caps_slug = null;
163
-
164
-    /**
165
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
-     * and next-level keys are capability names, and each's value is a
167
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
-     * they specify which context to use (ie, frontend, backend, edit or delete)
169
-     * and then each capability in the corresponding sub-array that they're missing
170
-     * adds the where conditions onto the query.
171
-     *
172
-     * @var array
173
-     */
174
-    protected $_cap_restrictions = array(
175
-        self::caps_read       => array(),
176
-        self::caps_read_admin => array(),
177
-        self::caps_edit       => array(),
178
-        self::caps_delete     => array(),
179
-    );
180
-
181
-    /**
182
-     * Array defining which cap restriction generators to use to create default
183
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
184
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
-     * automatically set this to false (not just null).
187
-     *
188
-     * @var EE_Restriction_Generator_Base[]
189
-     */
190
-    protected $_cap_restriction_generators = array();
191
-
192
-    /**
193
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
-     */
195
-    const caps_read       = 'read';
196
-
197
-    const caps_read_admin = 'read_admin';
198
-
199
-    const caps_edit       = 'edit';
200
-
201
-    const caps_delete     = 'delete';
202
-
203
-    /**
204
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
-     * maps to 'read' because when looking for relevant permissions we're going to use
207
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
208
-     *
209
-     * @var array
210
-     */
211
-    protected $_cap_contexts_to_cap_action_map = array(
212
-        self::caps_read       => 'read',
213
-        self::caps_read_admin => 'read',
214
-        self::caps_edit       => 'edit',
215
-        self::caps_delete     => 'delete',
216
-    );
217
-
218
-    /**
219
-     * Timezone
220
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
-     * EE_Datetime_Field data type will have access to it.
224
-     *
225
-     * @var string
226
-     */
227
-    protected $_timezone;
228
-
229
-
230
-    /**
231
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
-     * multisite.
233
-     *
234
-     * @var int
235
-     */
236
-    protected static $_model_query_blog_id;
237
-
238
-    /**
239
-     * A copy of _fields, except the array keys are the model names pointed to by
240
-     * the field
241
-     *
242
-     * @var EE_Model_Field_Base[]
243
-     */
244
-    private $_cache_foreign_key_to_fields = array();
245
-
246
-    /**
247
-     * Cached list of all the fields on the model, indexed by their name
248
-     *
249
-     * @var EE_Model_Field_Base[]
250
-     */
251
-    private $_cached_fields = null;
252
-
253
-    /**
254
-     * Cached list of all the fields on the model, except those that are
255
-     * marked as only pertinent to the database
256
-     *
257
-     * @var EE_Model_Field_Base[]
258
-     */
259
-    private $_cached_fields_non_db_only = null;
260
-
261
-    /**
262
-     * A cached reference to the primary key for quick lookup
263
-     *
264
-     * @var EE_Model_Field_Base
265
-     */
266
-    private $_primary_key_field = null;
267
-
268
-    /**
269
-     * Flag indicating whether this model has a primary key or not
270
-     *
271
-     * @var boolean
272
-     */
273
-    protected $_has_primary_key_field = null;
274
-
275
-    /**
276
-     * Whether or not this model is based off a table in WP core only (CPTs should set
277
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
-     *
279
-     * @var boolean
280
-     */
281
-    protected $_wp_core_model = false;
282
-
283
-    /**
284
-     *    List of valid operators that can be used for querying.
285
-     * The keys are all operators we'll accept, the values are the real SQL
286
-     * operators used
287
-     *
288
-     * @var array
289
-     */
290
-    protected $_valid_operators = array(
291
-        '='           => '=',
292
-        '<='          => '<=',
293
-        '<'           => '<',
294
-        '>='          => '>=',
295
-        '>'           => '>',
296
-        '!='          => '!=',
297
-        'LIKE'        => 'LIKE',
298
-        'like'        => 'LIKE',
299
-        'NOT_LIKE'    => 'NOT LIKE',
300
-        'not_like'    => 'NOT LIKE',
301
-        'NOT LIKE'    => 'NOT LIKE',
302
-        'not like'    => 'NOT LIKE',
303
-        'IN'          => 'IN',
304
-        'in'          => 'IN',
305
-        'NOT_IN'      => 'NOT IN',
306
-        'not_in'      => 'NOT IN',
307
-        'NOT IN'      => 'NOT IN',
308
-        'not in'      => 'NOT IN',
309
-        'between'     => 'BETWEEN',
310
-        'BETWEEN'     => 'BETWEEN',
311
-        'IS_NOT_NULL' => 'IS NOT NULL',
312
-        'is_not_null' => 'IS NOT NULL',
313
-        'IS NOT NULL' => 'IS NOT NULL',
314
-        'is not null' => 'IS NOT NULL',
315
-        'IS_NULL'     => 'IS NULL',
316
-        'is_null'     => 'IS NULL',
317
-        'IS NULL'     => 'IS NULL',
318
-        'is null'     => 'IS NULL',
319
-        'REGEXP'      => 'REGEXP',
320
-        'regexp'      => 'REGEXP',
321
-        'NOT_REGEXP'  => 'NOT REGEXP',
322
-        'not_regexp'  => 'NOT REGEXP',
323
-        'NOT REGEXP'  => 'NOT REGEXP',
324
-        'not regexp'  => 'NOT REGEXP',
325
-    );
326
-
327
-    /**
328
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
-     *
330
-     * @var array
331
-     */
332
-    protected $_in_style_operators = array('IN', 'NOT IN');
333
-
334
-    /**
335
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
-     * '12-31-2012'"
337
-     *
338
-     * @var array
339
-     */
340
-    protected $_between_style_operators = array('BETWEEN');
341
-
342
-    /**
343
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
-     * on a join table.
345
-     *
346
-     * @var array
347
-     */
348
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
-
350
-    /**
351
-     * Allowed values for $query_params['order'] for ordering in queries
352
-     *
353
-     * @var array
354
-     */
355
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
-
357
-    /**
358
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
360
-     *
361
-     * @var array
362
-     */
363
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
-
365
-    /**
366
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
368
-     *
369
-     * @var array
370
-     */
371
-    private $_allowed_query_params = array(
372
-        0,
373
-        'limit',
374
-        'order_by',
375
-        'group_by',
376
-        'having',
377
-        'force_join',
378
-        'order',
379
-        'on_join_limit',
380
-        'default_where_conditions',
381
-        'caps',
382
-    );
383
-
384
-    /**
385
-     * All the data types that can be used in $wpdb->prepare statements.
386
-     *
387
-     * @var array
388
-     */
389
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
-
391
-    /**
392
-     *    EE_Registry Object
393
-     *
394
-     * @var    object
395
-     * @access    protected
396
-     */
397
-    protected $EE = null;
398
-
399
-
400
-    /**
401
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
-     *
403
-     * @var int
404
-     */
405
-    protected $_show_next_x_db_queries = 0;
406
-
407
-    /**
408
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
-     *
411
-     * @var array
412
-     */
413
-    protected $_custom_selections = array();
414
-
415
-    /**
416
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
-     * caches every model object we've fetched from the DB on this request
418
-     *
419
-     * @var array
420
-     */
421
-    protected $_entity_map;
422
-
423
-    /**
424
-     * constant used to show EEM_Base has not yet verified the db on this http request
425
-     */
426
-    const db_verified_none = 0;
427
-
428
-    /**
429
-     * constant used to show EEM_Base has verified the EE core db on this http request,
430
-     * but not the addons' dbs
431
-     */
432
-    const db_verified_core = 1;
433
-
434
-    /**
435
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
-     * the EE core db too)
437
-     */
438
-    const db_verified_addons = 2;
439
-
440
-    /**
441
-     * indicates whether an EEM_Base child has already re-verified the DB
442
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
443
-     * looking like EEM_Base::db_verified_*
444
-     *
445
-     * @var int - 0 = none, 1 = core, 2 = addons
446
-     */
447
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
448
-
449
-    /**
450
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
-     *        registrations for non-trashed tickets for non-trashed datetimes)
453
-     */
454
-    const default_where_conditions_all = 'all';
455
-
456
-    /**
457
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
-     *        models which share tables with other models, this can return data for the wrong model.
462
-     */
463
-    const default_where_conditions_this_only = 'this_model_only';
464
-
465
-    /**
466
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
-     */
470
-    const default_where_conditions_others_only = 'other_models_only';
471
-
472
-    /**
473
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
476
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
-     *        (regardless of whether those events and venues are trashed)
478
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
-     *        events.
480
-     */
481
-    const default_where_conditions_minimum_all = 'minimum';
482
-
483
-    /**
484
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
-     *        not)
488
-     */
489
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
-     *        it's possible it will return table entries for other models. You should use
495
-     *        EEM_Base::default_where_conditions_minimum_all instead.
496
-     */
497
-    const default_where_conditions_none = 'none';
498
-
499
-
500
-
501
-    /**
502
-     * About all child constructors:
503
-     * they should define the _tables, _fields and _model_relations arrays.
504
-     * Should ALWAYS be called after child constructor.
505
-     * In order to make the child constructors to be as simple as possible, this parent constructor
506
-     * finalizes constructing all the object's attributes.
507
-     * Generally, rather than requiring a child to code
508
-     * $this->_tables = array(
509
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
-     *        ...);
511
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
-     * each EE_Table has a function to set the table's alias after the constructor, using
513
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
-     * do something similar.
515
-     *
516
-     * @param null $timezone
517
-     * @throws EE_Error
518
-     */
519
-    protected function __construct($timezone = null)
520
-    {
521
-        // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
524
-                sprintf(
525
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
526
-                        'event_espresso'),
527
-                    get_class($this)
528
-                )
529
-            );
530
-        }
531
-        /**
532
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
-         */
534
-        if (empty(EEM_Base::$_model_query_blog_id)) {
535
-            EEM_Base::set_model_query_blog_id();
536
-        }
537
-        /**
538
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
-         * just use EE_Register_Model_Extension
540
-         *
541
-         * @var EE_Table_Base[] $_tables
542
-         */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
-        foreach ($this->_tables as $table_alias => $table_obj) {
545
-            /** @var $table_obj EE_Table_Base */
546
-            $table_obj->_construct_finalize_with_alias($table_alias);
547
-            if ($table_obj instanceof EE_Secondary_Table) {
548
-                /** @var $table_obj EE_Secondary_Table */
549
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
-            }
551
-        }
552
-        /**
553
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
-         * EE_Register_Model_Extension
555
-         *
556
-         * @param EE_Model_Field_Base[] $_fields
557
-         */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
-        $this->_invalidate_field_caches();
560
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
562
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                //primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            //make extra meta related to everything, but don't block deleting things just
575
-            //because they have related extra meta info. For now just orphan those extra meta
576
-            //in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        //and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
-            $this->_model_relations);
591
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
592
-            /** @var $relation_obj EE_Model_Relation_Base */
593
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
-        }
595
-        foreach ($this->_indexes as $index_name => $index_obj) {
596
-            /** @var $index_obj EE_Index */
597
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
-        }
599
-        $this->set_timezone($timezone);
600
-        //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
602
-            //nothing was set during child constructor, so set default
603
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
-        }
605
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
607
-            //nothing was set during child constructor, so set default
608
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
-        }
610
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
612
-        //to indicate to NOT set it, set it to the logical default
613
-        if ($this->_caps_slug === null) {
614
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
-        }
616
-        //initialize the standard cap restriction generators if none were specified by the child constructor
617
-        if ($this->_cap_restriction_generators !== false) {
618
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
621
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
-                        new EE_Restriction_Generator_Protected(),
623
-                        $cap_context,
624
-                        $this
625
-                    );
626
-                }
627
-            }
628
-        }
629
-        //if there are cap restriction generators, use them to make the default cap restrictions
630
-        if ($this->_cap_restriction_generators !== false) {
631
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
633
-                    continue;
634
-                }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
-                    throw new EE_Error(
637
-                        sprintf(
638
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
639
-                                'event_espresso'),
640
-                            $context,
641
-                            $this->get_this_model_name()
642
-                        )
643
-                    );
644
-                }
645
-                $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
647
-                    $generator_object->_construct_finalize($this, $action);
648
-                }
649
-            }
650
-        }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
652
-    }
653
-
654
-
655
-
656
-    /**
657
-     * Generates the cap restrictions for the given context, or if they were
658
-     * already generated just gets what's cached
659
-     *
660
-     * @param string $context one of EEM_Base::valid_cap_contexts()
661
-     * @return EE_Default_Where_Conditions[]
662
-     */
663
-    protected function _generate_cap_restrictions($context)
664
-    {
665
-        if (isset($this->_cap_restriction_generators[$context])
666
-            && $this->_cap_restriction_generators[$context]
667
-               instanceof
668
-               EE_Restriction_Generator_Base
669
-        ) {
670
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
-        } else {
672
-            return array();
673
-        }
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     * Used to set the $_model_query_blog_id static property.
680
-     *
681
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
-     *                      value for get_current_blog_id() will be used.
683
-     */
684
-    public static function set_model_query_blog_id($blog_id = 0)
685
-    {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
-    }
688
-
689
-
690
-
691
-    /**
692
-     * Returns whatever is set as the internal $model_query_blog_id.
693
-     *
694
-     * @return int
695
-     */
696
-    public static function get_model_query_blog_id()
697
-    {
698
-        return EEM_Base::$_model_query_blog_id;
699
-    }
700
-
701
-
702
-
703
-    /**
704
-     * This function is a singleton method used to instantiate the Espresso_model object
705
-     *
706
-     * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
707
-     *                                    (and any incoming timezone data that gets saved).
708
-     *                                    Note this just sends the timezone info to the date time model field objects.
709
-     *                                    Default is NULL
710
-     *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
-     * @param ModelFieldFactory $model_field_factory
712
-     * @return static (as in the concrete child class)
713
-     * @throws InvalidArgumentException
714
-     * @throws InvalidInterfaceException
715
-     * @throws InvalidDataTypeException
716
-     * @throws EE_Error
717
-     */
718
-    public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719
-    {
720
-        // check if instance of Espresso_model already exists
721
-        if (! static::$_instance instanceof static) {
722
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
723
-            // instantiate Espresso_model
724
-            static::$_instance = new static($timezone, $model_field_factory);
725
-        }
726
-        //we might have a timezone set, let set_timezone decide what to do with it
727
-        static::$_instance->set_timezone($timezone);
728
-        // Espresso_model object
729
-        return static::$_instance;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * @param $model_field_factory
736
-     * @return ModelFieldFactory
737
-     * @throws InvalidArgumentException
738
-     * @throws InvalidDataTypeException
739
-     * @throws InvalidInterfaceException
740
-     */
741
-    private static function getModelFieldFactory($model_field_factory)
742
-    {
743
-        return $model_field_factory instanceof ModelFieldFactory
744
-            ? $model_field_factory
745
-            : LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory');
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * resets the model and returns it
752
-     *
753
-     * @param null | string          $timezone
754
-     * @param ModelFieldFactory|null $model_field_factory
755
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
756
-     * @throws ReflectionException
757
-     * all its properties reset; if it wasn't instantiated, returns null)
758
-     * @throws EE_Error
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
764
-    {
765
-        if (static::$_instance instanceof EEM_Base) {
766
-            //let's try to NOT swap out the current instance for a new one
767
-            //because if someone has a reference to it, we can't remove their reference
768
-            //so it's best to keep using the same reference, but change the original object
769
-            //reset all its properties to their original values as defined in the class
770
-            $r = new ReflectionClass(get_class(static::$_instance));
771
-            $static_properties = $r->getStaticProperties();
772
-            foreach ($r->getDefaultProperties() as $property => $value) {
773
-                //don't set instance to null like it was originally,
774
-                //but it's static anyways, and we're ignoring static properties (for now at least)
775
-                if (! isset($static_properties[$property])) {
776
-                    static::$_instance->{$property} = $value;
777
-                }
778
-            }
779
-            //and then directly call its constructor again, like we would if we were creating a new one
780
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
781
-            static::$_instance->__construct($timezone, $model_field_factory);
782
-            return self::instance();
783
-        }
784
-        return null;
785
-    }
786
-
787
-
788
-
789
-    /**
790
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
791
-     *
792
-     * @param  boolean $translated return localized strings or JUST the array.
793
-     * @return array
794
-     * @throws EE_Error
795
-     */
796
-    public function status_array($translated = false)
797
-    {
798
-        if (! array_key_exists('Status', $this->_model_relations)) {
799
-            return array();
800
-        }
801
-        $model_name = $this->get_this_model_name();
802
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
803
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
804
-        $status_array = array();
805
-        foreach ($stati as $status) {
806
-            $status_array[$status->ID()] = $status->get('STS_code');
807
-        }
808
-        return $translated
809
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
810
-            : $status_array;
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
817
-     *
818
-     * @param array $query_params             {
819
-     * @var array $0 (where) array {
820
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
821
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
822
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
823
-     *                                        conditions based on related models (and even
824
-     *                                        models-related-to-related-models) prepend the model's name onto the field
825
-     *                                        name. Eg,
826
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
827
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
828
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
829
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
830
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
831
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
832
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
833
-     *                                        to Venues (even when each of those models actually consisted of two
834
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
835
-     *                                        just having
836
-     *                                        "Venue.VNU_ID", you could have
837
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
838
-     *                                        events are related to Registrations, which are related to Attendees). You
839
-     *                                        can take it even further with
840
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
841
-     *                                        (from the default of '='), change the value to an numerically-indexed
842
-     *                                        array, where the first item in the list is the operator. eg: array(
843
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
844
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
845
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
846
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
847
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
848
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
849
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
850
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
851
-     *                                        the value is a field, simply provide a third array item (true) to the
852
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
853
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
854
-     *                                        Note: you can also use related model field names like you would any other
855
-     *                                        field name. eg:
856
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
857
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
858
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
859
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
860
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
861
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
862
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
863
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
864
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
865
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
866
-     *                                        "stick" until you specify an AND. eg
867
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
868
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
869
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
870
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
871
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
872
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
873
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
874
-     *                                        too, eg:
875
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
876
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
877
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
878
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
879
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
880
-     *                                        the OFFSET, the 2nd is the LIMIT
881
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
882
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
883
-     *                                        following format array('on_join_limit'
884
-     *                                        => array( 'table_alias', array(1,2) ) ).
885
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
886
-     *                                        values are either 'ASC' or 'DESC'.
887
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
888
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
889
-     *                                        DESC..." respectively. Like the
890
-     *                                        'where' conditions, these fields can be on related models. Eg
891
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
892
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
893
-     *                                        Attendee, Price, Datetime, etc.)
894
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
895
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
896
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
897
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
898
-     *                                        order by the primary key. Eg,
899
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
900
-     *                                        //(will join with the Datetime model's table(s) and order by its field
901
-     *                                        DTT_EVT_start) or
902
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
903
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
904
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
905
-     *                                        'group_by'=>'VNU_ID', or
906
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
907
-     *                                        if no
908
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
909
-     *                                        model's primary key (or combined primary keys). This avoids some
910
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
911
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
912
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
913
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
914
-     *                                        results)
915
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
916
-     *                                        array where values are models to be joined in the query.Eg
917
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
918
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
919
-     *                                        probably only want to do this in hopes of increasing efficiency, as
920
-     *                                        related models which belongs to the current model
921
-     *                                        (ie, the current model has a foreign key to them, like how Registration
922
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
923
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
924
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
925
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
926
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
927
-     *                                        default where conditions set it to 'other_models_only'. If you only want
928
-     *                                        this model's default where conditions added to the query, use
929
-     *                                        'this_model_only'. If you want to use all default where conditions
930
-     *                                        (default), set to 'all'.
931
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
932
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
933
-     *                                        everything? Or should we only show the current user items they should be
934
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
935
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
936
-     *                                        }
937
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
938
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
939
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
940
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
941
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
942
-     *                                        array( array(
943
-     *                                        'OR'=>array(
944
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
945
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
946
-     *                                        )
947
-     *                                        ),
948
-     *                                        'limit'=>10,
949
-     *                                        'group_by'=>'TXN_ID'
950
-     *                                        ));
951
-     *                                        get all the answers to the question titled "shirt size" for event with id
952
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
953
-     *                                        'Question.QST_display_text'=>'shirt size',
954
-     *                                        'Registration.Event.EVT_ID'=>12
955
-     *                                        ),
956
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
957
-     *                                        ));
958
-     * @throws EE_Error
959
-     */
960
-    public function get_all($query_params = array())
961
-    {
962
-        if (isset($query_params['limit'])
963
-            && ! isset($query_params['group_by'])
964
-        ) {
965
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
966
-        }
967
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
968
-    }
969
-
970
-
971
-
972
-    /**
973
-     * Modifies the query parameters so we only get back model objects
974
-     * that "belong" to the current user
975
-     *
976
-     * @param array $query_params @see EEM_Base::get_all()
977
-     * @return array like EEM_Base::get_all
978
-     */
979
-    public function alter_query_params_to_only_include_mine($query_params = array())
980
-    {
981
-        $wp_user_field_name = $this->wp_user_field_name();
982
-        if ($wp_user_field_name) {
983
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
984
-        }
985
-        return $query_params;
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Returns the name of the field's name that points to the WP_User table
992
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
993
-     * foreign key to the WP_User table)
994
-     *
995
-     * @return string|boolean string on success, boolean false when there is no
996
-     * foreign key to the WP_User table
997
-     */
998
-    public function wp_user_field_name()
999
-    {
1000
-        try {
1001
-            if (! empty($this->_model_chain_to_wp_user)) {
1002
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003
-                $last_model_name = end($models_to_follow_to_wp_users);
1004
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1006
-            } else {
1007
-                $model_with_fk_to_wp_users = $this;
1008
-                $model_chain_to_wp_user = '';
1009
-            }
1010
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1012
-        } catch (EE_Error $e) {
1013
-            return false;
1014
-        }
1015
-    }
1016
-
1017
-
1018
-
1019
-    /**
1020
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1021
-     * (or transiently-related model) has a foreign key to the wp_users table;
1022
-     * useful for finding if model objects of this type are 'owned' by the current user.
1023
-     * This is an empty string when the foreign key is on this model and when it isn't,
1024
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1025
-     * (or transiently-related model)
1026
-     *
1027
-     * @return string
1028
-     */
1029
-    public function model_chain_to_wp_user()
1030
-    {
1031
-        return $this->_model_chain_to_wp_user;
1032
-    }
1033
-
1034
-
1035
-
1036
-    /**
1037
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1038
-     * like how registrations don't have a foreign key to wp_users, but the
1039
-     * events they are for are), or is unrelated to wp users.
1040
-     * generally available
1041
-     *
1042
-     * @return boolean
1043
-     */
1044
-    public function is_owned()
1045
-    {
1046
-        if ($this->model_chain_to_wp_user()) {
1047
-            return true;
1048
-        }
1049
-        try {
1050
-            $this->get_foreign_key_to('WP_User');
1051
-            return true;
1052
-        } catch (EE_Error $e) {
1053
-            return false;
1054
-        }
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1061
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1062
-     * the model)
1063
-     *
1064
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1065
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1066
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1067
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1068
-     *                                  override this and set the select to "*", or a specific column name, like
1069
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1070
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1071
-     *                                  the aliases used to refer to this selection, and values are to be
1072
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1073
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1074
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1075
-     * @throws EE_Error
1076
-     */
1077
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1078
-    {
1079
-        // remember the custom selections, if any, and type cast as array
1080
-        // (unless $columns_to_select is an object, then just set as an empty array)
1081
-        // Note: (array) 'some string' === array( 'some string' )
1082
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1083
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1084
-        $select_expressions = $columns_to_select !== null
1085
-            ? $this->_construct_select_from_input($columns_to_select)
1086
-            : $this->_construct_default_select_sql($model_query_info);
1087
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1088
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089
-    }
1090
-
1091
-
1092
-
1093
-    /**
1094
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1095
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1096
-     * take care of joins, field preparation etc.
1097
-     *
1098
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1099
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1100
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1101
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1102
-     *                                  override this and set the select to "*", or a specific column name, like
1103
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1104
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1105
-     *                                  the aliases used to refer to this selection, and values are to be
1106
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1107
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1108
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1112
-    {
1113
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * For creating a custom select statement
1120
-     *
1121
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1122
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1123
-     *                                 SQL, and 1=>is the datatype
1124
-     * @throws EE_Error
1125
-     * @return string
1126
-     */
1127
-    private function _construct_select_from_input($columns_to_select)
1128
-    {
1129
-        if (is_array($columns_to_select)) {
1130
-            $select_sql_array = array();
1131
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133
-                    throw new EE_Error(
1134
-                        sprintf(
1135
-                            __(
1136
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1137
-                                "event_espresso"
1138
-                            ),
1139
-                            $selection_and_datatype,
1140
-                            $alias
1141
-                        )
1142
-                    );
1143
-                }
1144
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145
-                    throw new EE_Error(
1146
-                        sprintf(
1147
-                            __(
1148
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1149
-                                "event_espresso"
1150
-                            ),
1151
-                            $selection_and_datatype[1],
1152
-                            $selection_and_datatype[0],
1153
-                            $alias,
1154
-                            implode(",", $this->_valid_wpdb_data_types)
1155
-                        )
1156
-                    );
1157
-                }
1158
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1159
-            }
1160
-            $columns_to_select_string = implode(", ", $select_sql_array);
1161
-        } else {
1162
-            $columns_to_select_string = $columns_to_select;
1163
-        }
1164
-        return $columns_to_select_string;
1165
-    }
1166
-
1167
-
1168
-
1169
-    /**
1170
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1171
-     *
1172
-     * @return string
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function primary_key_name()
1176
-    {
1177
-        return $this->get_primary_key_field()->get_name();
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1184
-     * If there is no primary key on this model, $id is treated as primary key string
1185
-     *
1186
-     * @param mixed $id int or string, depending on the type of the model's primary key
1187
-     * @return EE_Base_Class
1188
-     */
1189
-    public function get_one_by_ID($id)
1190
-    {
1191
-        if ($this->get_from_entity_map($id)) {
1192
-            return $this->get_from_entity_map($id);
1193
-        }
1194
-        return $this->get_one(
1195
-            $this->alter_query_params_to_restrict_by_ID(
1196
-                $id,
1197
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1198
-            )
1199
-        );
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Alters query parameters to only get items with this ID are returned.
1206
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1207
-     * or could just be a simple primary key ID
1208
-     *
1209
-     * @param int   $id
1210
-     * @param array $query_params
1211
-     * @return array of normal query params, @see EEM_Base::get_all
1212
-     * @throws EE_Error
1213
-     */
1214
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215
-    {
1216
-        if (! isset($query_params[0])) {
1217
-            $query_params[0] = array();
1218
-        }
1219
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1220
-        if ($conditions_from_id === null) {
1221
-            $query_params[0][$this->primary_key_name()] = $id;
1222
-        } else {
1223
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1224
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1225
-        }
1226
-        return $query_params;
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1233
-     * array. If no item is found, null is returned.
1234
-     *
1235
-     * @param array $query_params like EEM_Base's $query_params variable.
1236
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1237
-     * @throws EE_Error
1238
-     */
1239
-    public function get_one($query_params = array())
1240
-    {
1241
-        if (! is_array($query_params)) {
1242
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1243
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
-                    gettype($query_params)), '4.6.0');
1245
-            $query_params = array();
1246
-        }
1247
-        $query_params['limit'] = 1;
1248
-        $items = $this->get_all($query_params);
1249
-        if (empty($items)) {
1250
-            return null;
1251
-        }
1252
-        return array_shift($items);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Returns the next x number of items in sequence from the given value as
1259
-     * found in the database matching the given query conditions.
1260
-     *
1261
-     * @param mixed $current_field_value    Value used for the reference point.
1262
-     * @param null  $field_to_order_by      What field is used for the
1263
-     *                                      reference point.
1264
-     * @param int   $limit                  How many to return.
1265
-     * @param array $query_params           Extra conditions on the query.
1266
-     * @param null  $columns_to_select      If left null, then an array of
1267
-     *                                      EE_Base_Class objects is returned,
1268
-     *                                      otherwise you can indicate just the
1269
-     *                                      columns you want returned.
1270
-     * @return EE_Base_Class[]|array
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function next_x(
1274
-        $current_field_value,
1275
-        $field_to_order_by = null,
1276
-        $limit = 1,
1277
-        $query_params = array(),
1278
-        $columns_to_select = null
1279
-    ) {
1280
-        return $this->_get_consecutive(
1281
-            $current_field_value,
1282
-            '>',
1283
-            $field_to_order_by,
1284
-            $limit,
1285
-            $query_params,
1286
-            $columns_to_select
1287
-        );
1288
-    }
1289
-
1290
-
1291
-
1292
-    /**
1293
-     * Returns the previous x number of items in sequence from the given value
1294
-     * as found in the database matching the given query conditions.
1295
-     *
1296
-     * @param mixed $current_field_value    Value used for the reference point.
1297
-     * @param null  $field_to_order_by      What field is used for the
1298
-     *                                      reference point.
1299
-     * @param int   $limit                  How many to return.
1300
-     * @param array $query_params           Extra conditions on the query.
1301
-     * @param null  $columns_to_select      If left null, then an array of
1302
-     *                                      EE_Base_Class objects is returned,
1303
-     *                                      otherwise you can indicate just the
1304
-     *                                      columns you want returned.
1305
-     * @return EE_Base_Class[]|array
1306
-     * @throws EE_Error
1307
-     */
1308
-    public function previous_x(
1309
-        $current_field_value,
1310
-        $field_to_order_by = null,
1311
-        $limit = 1,
1312
-        $query_params = array(),
1313
-        $columns_to_select = null
1314
-    ) {
1315
-        return $this->_get_consecutive(
1316
-            $current_field_value,
1317
-            '<',
1318
-            $field_to_order_by,
1319
-            $limit,
1320
-            $query_params,
1321
-            $columns_to_select
1322
-        );
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * Returns the next item in sequence from the given value as found in the
1329
-     * database matching the given query conditions.
1330
-     *
1331
-     * @param mixed $current_field_value    Value used for the reference point.
1332
-     * @param null  $field_to_order_by      What field is used for the
1333
-     *                                      reference point.
1334
-     * @param array $query_params           Extra conditions on the query.
1335
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
-     *                                      object is returned, otherwise you
1337
-     *                                      can indicate just the columns you
1338
-     *                                      want and a single array indexed by
1339
-     *                                      the columns will be returned.
1340
-     * @return EE_Base_Class|null|array()
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function next(
1344
-        $current_field_value,
1345
-        $field_to_order_by = null,
1346
-        $query_params = array(),
1347
-        $columns_to_select = null
1348
-    ) {
1349
-        $results = $this->_get_consecutive(
1350
-            $current_field_value,
1351
-            '>',
1352
-            $field_to_order_by,
1353
-            1,
1354
-            $query_params,
1355
-            $columns_to_select
1356
-        );
1357
-        return empty($results) ? null : reset($results);
1358
-    }
1359
-
1360
-
1361
-
1362
-    /**
1363
-     * Returns the previous item in sequence from the given value as found in
1364
-     * the database matching the given query conditions.
1365
-     *
1366
-     * @param mixed $current_field_value    Value used for the reference point.
1367
-     * @param null  $field_to_order_by      What field is used for the
1368
-     *                                      reference point.
1369
-     * @param array $query_params           Extra conditions on the query.
1370
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1371
-     *                                      object is returned, otherwise you
1372
-     *                                      can indicate just the columns you
1373
-     *                                      want and a single array indexed by
1374
-     *                                      the columns will be returned.
1375
-     * @return EE_Base_Class|null|array()
1376
-     * @throws EE_Error
1377
-     */
1378
-    public function previous(
1379
-        $current_field_value,
1380
-        $field_to_order_by = null,
1381
-        $query_params = array(),
1382
-        $columns_to_select = null
1383
-    ) {
1384
-        $results = $this->_get_consecutive(
1385
-            $current_field_value,
1386
-            '<',
1387
-            $field_to_order_by,
1388
-            1,
1389
-            $query_params,
1390
-            $columns_to_select
1391
-        );
1392
-        return empty($results) ? null : reset($results);
1393
-    }
1394
-
1395
-
1396
-
1397
-    /**
1398
-     * Returns the a consecutive number of items in sequence from the given
1399
-     * value as found in the database matching the given query conditions.
1400
-     *
1401
-     * @param mixed  $current_field_value   Value used for the reference point.
1402
-     * @param string $operand               What operand is used for the sequence.
1403
-     * @param string $field_to_order_by     What field is used for the reference point.
1404
-     * @param int    $limit                 How many to return.
1405
-     * @param array  $query_params          Extra conditions on the query.
1406
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
-     *                                      otherwise you can indicate just the columns you want returned.
1408
-     * @return EE_Base_Class[]|array
1409
-     * @throws EE_Error
1410
-     */
1411
-    protected function _get_consecutive(
1412
-        $current_field_value,
1413
-        $operand = '>',
1414
-        $field_to_order_by = null,
1415
-        $limit = 1,
1416
-        $query_params = array(),
1417
-        $columns_to_select = null
1418
-    ) {
1419
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1420
-        if (empty($field_to_order_by)) {
1421
-            if ($this->has_primary_key_field()) {
1422
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1423
-            } else {
1424
-                if (WP_DEBUG) {
1425
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
-                        'event_espresso'));
1427
-                }
1428
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
-                return array();
1430
-            }
1431
-        }
1432
-        if (! is_array($query_params)) {
1433
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435
-                    gettype($query_params)), '4.6.0');
1436
-            $query_params = array();
1437
-        }
1438
-        //let's add the where query param for consecutive look up.
1439
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440
-        $query_params['limit'] = $limit;
1441
-        //set direction
1442
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1443
-        $query_params['order_by'] = $operand === '>'
1444
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1445
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1446
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1447
-        if (empty($columns_to_select)) {
1448
-            return $this->get_all($query_params);
1449
-        }
1450
-        //getting just the fields
1451
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1452
-    }
1453
-
1454
-
1455
-
1456
-    /**
1457
-     * This sets the _timezone property after model object has been instantiated.
1458
-     *
1459
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
-     */
1461
-    public function set_timezone($timezone)
1462
-    {
1463
-        if ($timezone !== null) {
1464
-            $this->_timezone = $timezone;
1465
-        }
1466
-        //note we need to loop through relations and set the timezone on those objects as well.
1467
-        foreach ($this->_model_relations as $relation) {
1468
-            $relation->set_timezone($timezone);
1469
-        }
1470
-        //and finally we do the same for any datetime fields
1471
-        foreach ($this->_fields as $field) {
1472
-            if ($field instanceof EE_Datetime_Field) {
1473
-                $field->set_timezone($timezone);
1474
-            }
1475
-        }
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * This just returns whatever is set for the current timezone.
1482
-     *
1483
-     * @access public
1484
-     * @return string
1485
-     */
1486
-    public function get_timezone()
1487
-    {
1488
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1489
-        if (empty($this->_timezone)) {
1490
-            foreach ($this->_fields as $field) {
1491
-                if ($field instanceof EE_Datetime_Field) {
1492
-                    $this->set_timezone($field->get_timezone());
1493
-                    break;
1494
-                }
1495
-            }
1496
-        }
1497
-        //if timezone STILL empty then return the default timezone for the site.
1498
-        if (empty($this->_timezone)) {
1499
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1500
-        }
1501
-        return $this->_timezone;
1502
-    }
1503
-
1504
-
1505
-
1506
-    /**
1507
-     * This returns the date formats set for the given field name and also ensures that
1508
-     * $this->_timezone property is set correctly.
1509
-     *
1510
-     * @since 4.6.x
1511
-     * @param string $field_name The name of the field the formats are being retrieved for.
1512
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1514
-     * @return array formats in an array with the date format first, and the time format last.
1515
-     */
1516
-    public function get_formats_for($field_name, $pretty = false)
1517
-    {
1518
-        $field_settings = $this->field_settings_for($field_name);
1519
-        //if not a valid EE_Datetime_Field then throw error
1520
-        if (! $field_settings instanceof EE_Datetime_Field) {
1521
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1522
-                'event_espresso'), $field_name));
1523
-        }
1524
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1525
-        //the field.
1526
-        $this->_timezone = $field_settings->get_timezone();
1527
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * This returns the current time in a format setup for a query on this model.
1534
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1535
-     * it will return:
1536
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1537
-     *  NOW
1538
-     *  - or a unix timestamp (equivalent to time())
1539
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1540
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1541
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1542
-     * @since 4.6.x
1543
-     * @param string $field_name       The field the current time is needed for.
1544
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1545
-     *                                 formatted string matching the set format for the field in the set timezone will
1546
-     *                                 be returned.
1547
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1548
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1549
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1550
-     *                                 exception is triggered.
1551
-     */
1552
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1553
-    {
1554
-        $formats = $this->get_formats_for($field_name);
1555
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1556
-        if ($timestamp) {
1557
-            return $DateTime->format('U');
1558
-        }
1559
-        //not returning timestamp, so return formatted string in timezone.
1560
-        switch ($what) {
1561
-            case 'time' :
1562
-                return $DateTime->format($formats[1]);
1563
-                break;
1564
-            case 'date' :
1565
-                return $DateTime->format($formats[0]);
1566
-                break;
1567
-            default :
1568
-                return $DateTime->format(implode(' ', $formats));
1569
-                break;
1570
-        }
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1577
-     * for the model are.  Returns a DateTime object.
1578
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1579
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1580
-     * ignored.
1581
-     *
1582
-     * @param string $field_name      The field being setup.
1583
-     * @param string $timestring      The date time string being used.
1584
-     * @param string $incoming_format The format for the time string.
1585
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1586
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1587
-     *                                format is
1588
-     *                                'U', this is ignored.
1589
-     * @return DateTime
1590
-     * @throws EE_Error
1591
-     */
1592
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1593
-    {
1594
-        //just using this to ensure the timezone is set correctly internally
1595
-        $this->get_formats_for($field_name);
1596
-        //load EEH_DTT_Helper
1597
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1600
-    }
1601
-
1602
-
1603
-
1604
-    /**
1605
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1606
-     *
1607
-     * @return EE_Table_Base[]
1608
-     */
1609
-    public function get_tables()
1610
-    {
1611
-        return $this->_tables;
1612
-    }
1613
-
1614
-
1615
-
1616
-    /**
1617
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1618
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1619
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1620
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1621
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1622
-     * model object with EVT_ID = 1
1623
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1624
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1625
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1626
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1627
-     * are not specified)
1628
-     *
1629
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1630
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1631
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1632
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1633
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1634
-     *                                         ID=34, we'd use this method as follows:
1635
-     *                                         EEM_Transaction::instance()->update(
1636
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1637
-     *                                         array(array('TXN_ID'=>34)));
1638
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1639
-     *                                         in client code into what's expected to be stored on each field. Eg,
1640
-     *                                         consider updating Question's QST_admin_label field is of type
1641
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1642
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1643
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1644
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1645
-     *                                         TRUE, it is assumed that you've already called
1646
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1647
-     *                                         malicious javascript. However, if
1648
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1649
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1650
-     *                                         and every other field, before insertion. We provide this parameter
1651
-     *                                         because model objects perform their prepare_for_set function on all
1652
-     *                                         their values, and so don't need to be called again (and in many cases,
1653
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1654
-     *                                         prepare_for_set method...)
1655
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1656
-     *                                         in this model's entity map according to $fields_n_values that match
1657
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1658
-     *                                         by setting this to FALSE, but be aware that model objects being used
1659
-     *                                         could get out-of-sync with the database
1660
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1661
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1662
-     *                                         bad)
1663
-     * @throws EE_Error
1664
-     */
1665
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666
-    {
1667
-        if (! is_array($query_params)) {
1668
-            EE_Error::doing_it_wrong('EEM_Base::update',
1669
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670
-                    gettype($query_params)), '4.6.0');
1671
-            $query_params = array();
1672
-        }
1673
-        /**
1674
-         * Action called before a model update call has been made.
1675
-         *
1676
-         * @param EEM_Base $model
1677
-         * @param array    $fields_n_values the updated fields and their new values
1678
-         * @param array    $query_params    @see EEM_Base::get_all()
1679
-         */
1680
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1681
-        /**
1682
-         * Filters the fields about to be updated given the query parameters. You can provide the
1683
-         * $query_params to $this->get_all() to find exactly which records will be updated
1684
-         *
1685
-         * @param array    $fields_n_values fields and their new values
1686
-         * @param EEM_Base $model           the model being queried
1687
-         * @param array    $query_params    see EEM_Base::get_all()
1688
-         */
1689
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690
-            $query_params);
1691
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1692
-        //to do that, for each table, verify that it's PK isn't null.
1693
-        $tables = $this->get_tables();
1694
-        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1695
-        //NOTE: we should make this code more efficient by NOT querying twice
1696
-        //before the real update, but that needs to first go through ALPHA testing
1697
-        //as it's dangerous. says Mike August 8 2014
1698
-        //we want to make sure the default_where strategy is ignored
1699
-        $this->_ignore_where_strategy = true;
1700
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701
-        foreach ($wpdb_select_results as $wpdb_result) {
1702
-            // type cast stdClass as array
1703
-            $wpdb_result = (array)$wpdb_result;
1704
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705
-            if ($this->has_primary_key_field()) {
1706
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1707
-            } else {
1708
-                //if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1709
-                $main_table_pk_value = null;
1710
-            }
1711
-            //if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1712
-            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1713
-            if (count($tables) > 1) {
1714
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1715
-                //in that table, and so we'll want to insert one
1716
-                foreach ($tables as $table_obj) {
1717
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718
-                    //if there is no private key for this table on the results, it means there's no entry
1719
-                    //in this table, right? so insert a row in the current table, using any fields available
1720
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1721
-                           && $wpdb_result[$this_table_pk_column])
1722
-                    ) {
1723
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724
-                            $main_table_pk_value);
1725
-                        //if we died here, report the error
1726
-                        if (! $success) {
1727
-                            return false;
1728
-                        }
1729
-                    }
1730
-                }
1731
-            }
1732
-            //				//and now check that if we have cached any models by that ID on the model, that
1733
-            //				//they also get updated properly
1734
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1735
-            //				if( $model_object ){
1736
-            //					foreach( $fields_n_values as $field => $value ){
1737
-            //						$model_object->set($field, $value);
1738
-            //let's make sure default_where strategy is followed now
1739
-            $this->_ignore_where_strategy = false;
1740
-        }
1741
-        //if we want to keep model objects in sync, AND
1742
-        //if this wasn't called from a model object (to update itself)
1743
-        //then we want to make sure we keep all the existing
1744
-        //model objects in sync with the db
1745
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1746
-            if ($this->has_primary_key_field()) {
1747
-                $model_objs_affected_ids = $this->get_col($query_params);
1748
-            } else {
1749
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1750
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1751
-                $model_objs_affected_ids = array();
1752
-                foreach ($models_affected_key_columns as $row) {
1753
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1754
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755
-                }
1756
-            }
1757
-            if (! $model_objs_affected_ids) {
1758
-                //wait wait wait- if nothing was affected let's stop here
1759
-                return 0;
1760
-            }
1761
-            foreach ($model_objs_affected_ids as $id) {
1762
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1763
-                if ($model_obj_in_entity_map) {
1764
-                    foreach ($fields_n_values as $field => $new_value) {
1765
-                        $model_obj_in_entity_map->set($field, $new_value);
1766
-                    }
1767
-                }
1768
-            }
1769
-            //if there is a primary key on this model, we can now do a slight optimization
1770
-            if ($this->has_primary_key_field()) {
1771
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1772
-                $query_params = array(
1773
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1774
-                    'limit'                    => count($model_objs_affected_ids),
1775
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1776
-                );
1777
-            }
1778
-        }
1779
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1780
-        $SQL = "UPDATE "
1781
-               . $model_query_info->get_full_join_sql()
1782
-               . " SET "
1783
-               . $this->_construct_update_sql($fields_n_values)
1784
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786
-        /**
1787
-         * Action called after a model update call has been made.
1788
-         *
1789
-         * @param EEM_Base $model
1790
-         * @param array    $fields_n_values the updated fields and their new values
1791
-         * @param array    $query_params    @see EEM_Base::get_all()
1792
-         * @param int      $rows_affected
1793
-         */
1794
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
-        return $rows_affected;//how many supposedly got updated
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1802
-     * are teh values of the field specified (or by default the primary key field)
1803
-     * that matched the query params. Note that you should pass the name of the
1804
-     * model FIELD, not the database table's column name.
1805
-     *
1806
-     * @param array  $query_params @see EEM_Base::get_all()
1807
-     * @param string $field_to_select
1808
-     * @return array just like $wpdb->get_col()
1809
-     * @throws EE_Error
1810
-     */
1811
-    public function get_col($query_params = array(), $field_to_select = null)
1812
-    {
1813
-        if ($field_to_select) {
1814
-            $field = $this->field_settings_for($field_to_select);
1815
-        } elseif ($this->has_primary_key_field()) {
1816
-            $field = $this->get_primary_key_field();
1817
-        } else {
1818
-            //no primary key, just grab the first column
1819
-            $field = reset($this->field_settings());
1820
-        }
1821
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1822
-        $select_expressions = $field->get_qualified_column();
1823
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1824
-        return $this->_do_wpdb_query('get_col', array($SQL));
1825
-    }
1826
-
1827
-
1828
-
1829
-    /**
1830
-     * Returns a single column value for a single row from the database
1831
-     *
1832
-     * @param array  $query_params    @see EEM_Base::get_all()
1833
-     * @param string $field_to_select @see EEM_Base::get_col()
1834
-     * @return string
1835
-     * @throws EE_Error
1836
-     */
1837
-    public function get_var($query_params = array(), $field_to_select = null)
1838
-    {
1839
-        $query_params['limit'] = 1;
1840
-        $col = $this->get_col($query_params, $field_to_select);
1841
-        if (! empty($col)) {
1842
-            return reset($col);
1843
-        }
1844
-        return null;
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1851
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1852
-     * injection, but currently no further filtering is done
1853
-     *
1854
-     * @global      $wpdb
1855
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1856
-     *                               be updated to in the DB
1857
-     * @return string of SQL
1858
-     * @throws EE_Error
1859
-     */
1860
-    public function _construct_update_sql($fields_n_values)
1861
-    {
1862
-        /** @type WPDB $wpdb */
1863
-        global $wpdb;
1864
-        $cols_n_values = array();
1865
-        foreach ($fields_n_values as $field_name => $value) {
1866
-            $field_obj = $this->field_settings_for($field_name);
1867
-            //if the value is NULL, we want to assign the value to that.
1868
-            //wpdb->prepare doesn't really handle that properly
1869
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870
-            $value_sql = $prepared_value === null ? 'NULL'
1871
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1873
-        }
1874
-        return implode(",", $cols_n_values);
1875
-    }
1876
-
1877
-
1878
-
1879
-    /**
1880
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1881
-     * Performs a HARD delete, meaning the database row should always be removed,
1882
-     * not just have a flag field on it switched
1883
-     * Wrapper for EEM_Base::delete_permanently()
1884
-     *
1885
-     * @param mixed $id
1886
-     * @return boolean whether the row got deleted or not
1887
-     * @throws EE_Error
1888
-     */
1889
-    public function delete_permanently_by_ID($id)
1890
-    {
1891
-        return $this->delete_permanently(
1892
-            array(
1893
-                array($this->get_primary_key_field()->get_name() => $id),
1894
-                'limit' => 1,
1895
-            )
1896
-        );
1897
-    }
1898
-
1899
-
1900
-
1901
-    /**
1902
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1903
-     * Wrapper for EEM_Base::delete()
1904
-     *
1905
-     * @param mixed $id
1906
-     * @return boolean whether the row got deleted or not
1907
-     * @throws EE_Error
1908
-     */
1909
-    public function delete_by_ID($id)
1910
-    {
1911
-        return $this->delete(
1912
-            array(
1913
-                array($this->get_primary_key_field()->get_name() => $id),
1914
-                'limit' => 1,
1915
-            )
1916
-        );
1917
-    }
1918
-
1919
-
1920
-
1921
-    /**
1922
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1923
-     * meaning if the model has a field that indicates its been "trashed" or
1924
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1925
-     *
1926
-     * @see EEM_Base::delete_permanently
1927
-     * @param array   $query_params
1928
-     * @param boolean $allow_blocking
1929
-     * @return int how many rows got deleted
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete($query_params, $allow_blocking = true)
1933
-    {
1934
-        return $this->delete_permanently($query_params, $allow_blocking);
1935
-    }
1936
-
1937
-
1938
-
1939
-    /**
1940
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1941
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1942
-     * as archived, not actually deleted
1943
-     *
1944
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1945
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1946
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1947
-     *                                deletes regardless of other objects which may depend on it. Its generally
1948
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1949
-     *                                DB
1950
-     * @return int how many rows got deleted
1951
-     * @throws EE_Error
1952
-     */
1953
-    public function delete_permanently($query_params, $allow_blocking = true)
1954
-    {
1955
-        /**
1956
-         * Action called just before performing a real deletion query. You can use the
1957
-         * model and its $query_params to find exactly which items will be deleted
1958
-         *
1959
-         * @param EEM_Base $model
1960
-         * @param array    $query_params   @see EEM_Base::get_all()
1961
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1962
-         *                                 to block (prevent) this deletion
1963
-         */
1964
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1965
-        //some MySQL databases may be running safe mode, which may restrict
1966
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1967
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1968
-        //to delete them
1969
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1970
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1971
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1972
-            $columns_and_ids_for_deleting
1973
-        );
1974
-        /**
1975
-         * Allows client code to act on the items being deleted before the query is actually executed.
1976
-         *
1977
-         * @param EEM_Base $this  The model instance being acted on.
1978
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1979
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1980
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1981
-         *                                                  derived from the incoming query parameters.
1982
-         *                                                  @see details on the structure of this array in the phpdocs
1983
-         *                                                  for the `_get_ids_for_delete_method`
1984
-         *
1985
-         */
1986
-        do_action('AHEE__EEM_Base__delete__before_query',
1987
-            $this,
1988
-            $query_params,
1989
-            $allow_blocking,
1990
-            $columns_and_ids_for_deleting
1991
-        );
1992
-        if ($deletion_where_query_part) {
1993
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1994
-            $table_aliases = array_keys($this->_tables);
1995
-            $SQL = "DELETE "
1996
-                   . implode(", ", $table_aliases)
1997
-                   . " FROM "
1998
-                   . $model_query_info->get_full_join_sql()
1999
-                   . " WHERE "
2000
-                   . $deletion_where_query_part;
2001
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2002
-        } else {
2003
-            $rows_deleted = 0;
2004
-        }
2005
-
2006
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2007
-        //there was no error with the delete query.
2008
-        if ($this->has_primary_key_field()
2009
-            && $rows_deleted !== false
2010
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2011
-        ) {
2012
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2013
-            foreach ($ids_for_removal as $id) {
2014
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2015
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2016
-                }
2017
-            }
2018
-
2019
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2020
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2021
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2022
-            // (although it is possible).
2023
-            //Note this can be skipped by using the provided filter and returning false.
2024
-            if (apply_filters(
2025
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2026
-                ! $this instanceof EEM_Extra_Meta,
2027
-                $this
2028
-            )) {
2029
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2030
-                    0 => array(
2031
-                        'EXM_type' => $this->get_this_model_name(),
2032
-                        'OBJ_ID'   => array(
2033
-                            'IN',
2034
-                            $ids_for_removal
2035
-                        )
2036
-                    )
2037
-                ));
2038
-            }
2039
-        }
2040
-
2041
-        /**
2042
-         * Action called just after performing a real deletion query. Although at this point the
2043
-         * items should have been deleted
2044
-         *
2045
-         * @param EEM_Base $model
2046
-         * @param array    $query_params @see EEM_Base::get_all()
2047
-         * @param int      $rows_deleted
2048
-         */
2049
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
-        return $rows_deleted;//how many supposedly got deleted
2051
-    }
2052
-
2053
-
2054
-
2055
-    /**
2056
-     * Checks all the relations that throw error messages when there are blocking related objects
2057
-     * for related model objects. If there are any related model objects on those relations,
2058
-     * adds an EE_Error, and return true
2059
-     *
2060
-     * @param EE_Base_Class|int $this_model_obj_or_id
2061
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2062
-     *                                                 should be ignored when determining whether there are related
2063
-     *                                                 model objects which block this model object's deletion. Useful
2064
-     *                                                 if you know A is related to B and are considering deleting A,
2065
-     *                                                 but want to see if A has any other objects blocking its deletion
2066
-     *                                                 before removing the relation between A and B
2067
-     * @return boolean
2068
-     * @throws EE_Error
2069
-     */
2070
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2071
-    {
2072
-        //first, if $ignore_this_model_obj was supplied, get its model
2073
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2074
-            $ignored_model = $ignore_this_model_obj->get_model();
2075
-        } else {
2076
-            $ignored_model = null;
2077
-        }
2078
-        //now check all the relations of $this_model_obj_or_id and see if there
2079
-        //are any related model objects blocking it?
2080
-        $is_blocked = false;
2081
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2082
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2083
-                //if $ignore_this_model_obj was supplied, then for the query
2084
-                //on that model needs to be told to ignore $ignore_this_model_obj
2085
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2086
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2087
-                        array(
2088
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2089
-                                '!=',
2090
-                                $ignore_this_model_obj->ID(),
2091
-                            ),
2092
-                        ),
2093
-                    ));
2094
-                } else {
2095
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2096
-                }
2097
-                if ($related_model_objects) {
2098
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2099
-                    $is_blocked = true;
2100
-                }
2101
-            }
2102
-        }
2103
-        return $is_blocked;
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2109
-     * @param array $row_results_for_deleting
2110
-     * @param bool  $allow_blocking
2111
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2112
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2113
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2114
-     *                 deleted. Example:
2115
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2116
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2117
-     *                 where each element is a group of columns and values that get deleted. Example:
2118
-     *                      array(
2119
-     *                          0 => array(
2120
-     *                              'Term_Relationship.object_id' => 1
2121
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2122
-     *                          ),
2123
-     *                          1 => array(
2124
-     *                              'Term_Relationship.object_id' => 1
2125
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2126
-     *                          )
2127
-     *                      )
2128
-     * @throws EE_Error
2129
-     */
2130
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2131
-    {
2132
-        $ids_to_delete_indexed_by_column = array();
2133
-        if ($this->has_primary_key_field()) {
2134
-            $primary_table = $this->_get_main_table();
2135
-            $other_tables = $this->_get_other_tables();
2136
-            $ids_to_delete_indexed_by_column = $query = array();
2137
-            foreach ($row_results_for_deleting as $item_to_delete) {
2138
-                //before we mark this item for deletion,
2139
-                //make sure there's no related entities blocking its deletion (if we're checking)
2140
-                if (
2141
-                    $allow_blocking
2142
-                    && $this->delete_is_blocked_by_related_models(
2143
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2144
-                    )
2145
-                ) {
2146
-                    continue;
2147
-                }
2148
-                //primary table deletes
2149
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2150
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2151
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2152
-                }
2153
-            }
2154
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2155
-            $fields = $this->get_combined_primary_key_fields();
2156
-            foreach ($row_results_for_deleting as $item_to_delete) {
2157
-                $ids_to_delete_indexed_by_column_for_row = array();
2158
-                foreach ($fields as $cpk_field) {
2159
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2160
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2161
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2162
-                    }
2163
-                }
2164
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2165
-            }
2166
-        } else {
2167
-            //so there's no primary key and no combined key...
2168
-            //sorry, can't help you
2169
-            throw new EE_Error(
2170
-                sprintf(
2171
-                    __(
2172
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2173
-                        "event_espresso"
2174
-                    ), get_class($this)
2175
-                )
2176
-            );
2177
-        }    
2178
-        return $ids_to_delete_indexed_by_column;
2179
-    }
2180
-
2181
-
2182
-    /**
2183
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2184
-     * the corresponding query_part for the query performing the delete.
2185
-     *
2186
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2187
-     * @return string
2188
-     * @throws EE_Error
2189
-     */
2190
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2191
-        $query_part = '';
2192
-        if (empty($ids_to_delete_indexed_by_column)) {
2193
-            return $query_part;
2194
-        } elseif ($this->has_primary_key_field()) {
2195
-            $query = array();
2196
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2197
-                //make sure we have unique $ids
2198
-                $ids = array_unique($ids);
2199
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2200
-            }
2201
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2202
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2203
-            $ways_to_identify_a_row = array();
2204
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2205
-                $values_for_each_combined_primary_key_for_a_row = array();
2206
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2207
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2208
-                }
2209
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2210
-            }
2211
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2212
-        }
2213
-        return $query_part;
2214
-    }
35
+	//admin posty
36
+	//basic -> grants access to mine -> if they don't have it, select none
37
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
+	//*_published -> grants access to published -> if they dont have it, select non-published
40
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
42
+	//frontend posty
43
+	//by default has access to published
44
+	//basic -> grants access to mine that aren't published, and all published
45
+	//*_others ->grants access to others that aren't private, all mine
46
+	//*_private -> grants full access
47
+	//frontend non-posty
48
+	//like admin posty
49
+	//category-y
50
+	//assign -> grants access to join-table
51
+	//(delete, edit)
52
+	//payment-method-y
53
+	//for each registered payment method,
54
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
+	/**
56
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
59
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
+	 *
61
+	 * @var boolean
62
+	 */
63
+	private $_values_already_prepared_by_model_object = 0;
64
+
65
+	/**
66
+	 * when $_values_already_prepared_by_model_object equals this, we assume
67
+	 * the data is just like form input that needs to have the model fields'
68
+	 * prepare_for_set and prepare_for_use_in_db called on it
69
+	 */
70
+	const not_prepared_by_model_object = 0;
71
+
72
+	/**
73
+	 * when $_values_already_prepared_by_model_object equals this, we
74
+	 * assume this value is coming from a model object and doesn't need to have
75
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
76
+	 */
77
+	const prepared_by_model_object = 1;
78
+
79
+	/**
80
+	 * when $_values_already_prepared_by_model_object equals this, we assume
81
+	 * the values are already to be used in the database (ie no processing is done
82
+	 * on them by the model's fields)
83
+	 */
84
+	const prepared_for_use_in_db = 2;
85
+
86
+
87
+	protected $singular_item = 'Item';
88
+
89
+	protected $plural_item   = 'Items';
90
+
91
+	/**
92
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
+	 */
94
+	protected $_tables;
95
+
96
+	/**
97
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
+	 *
101
+	 * @var \EE_Model_Field_Base[] $_fields
102
+	 */
103
+	protected $_fields;
104
+
105
+	/**
106
+	 * array of different kinds of relations
107
+	 *
108
+	 * @var \EE_Model_Relation_Base[] $_model_relations
109
+	 */
110
+	protected $_model_relations;
111
+
112
+	/**
113
+	 * @var \EE_Index[] $_indexes
114
+	 */
115
+	protected $_indexes = array();
116
+
117
+	/**
118
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
119
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
+	 * by setting the same columns as used in these queries in the query yourself.
121
+	 *
122
+	 * @var EE_Default_Where_Conditions
123
+	 */
124
+	protected $_default_where_conditions_strategy;
125
+
126
+	/**
127
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
+	 * This is particularly useful when you want something between 'none' and 'default'
129
+	 *
130
+	 * @var EE_Default_Where_Conditions
131
+	 */
132
+	protected $_minimum_where_conditions_strategy;
133
+
134
+	/**
135
+	 * String describing how to find the "owner" of this model's objects.
136
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
+	 * But when there isn't, this indicates which related model, or transiently-related model,
138
+	 * has the foreign key to the wp_users table.
139
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
+	 * related to events, and events have a foreign key to wp_users.
141
+	 * On EEM_Transaction, this would be 'Transaction.Event'
142
+	 *
143
+	 * @var string
144
+	 */
145
+	protected $_model_chain_to_wp_user = '';
146
+
147
+	/**
148
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
+	 * don't need it (particularly CPT models)
150
+	 *
151
+	 * @var bool
152
+	 */
153
+	protected $_ignore_where_strategy = false;
154
+
155
+	/**
156
+	 * String used in caps relating to this model. Eg, if the caps relating to this
157
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
+	 *
159
+	 * @var string. If null it hasn't been initialized yet. If false then we
160
+	 * have indicated capabilities don't apply to this
161
+	 */
162
+	protected $_caps_slug = null;
163
+
164
+	/**
165
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
+	 * and next-level keys are capability names, and each's value is a
167
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
169
+	 * and then each capability in the corresponding sub-array that they're missing
170
+	 * adds the where conditions onto the query.
171
+	 *
172
+	 * @var array
173
+	 */
174
+	protected $_cap_restrictions = array(
175
+		self::caps_read       => array(),
176
+		self::caps_read_admin => array(),
177
+		self::caps_edit       => array(),
178
+		self::caps_delete     => array(),
179
+	);
180
+
181
+	/**
182
+	 * Array defining which cap restriction generators to use to create default
183
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
184
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
+	 * automatically set this to false (not just null).
187
+	 *
188
+	 * @var EE_Restriction_Generator_Base[]
189
+	 */
190
+	protected $_cap_restriction_generators = array();
191
+
192
+	/**
193
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
+	 */
195
+	const caps_read       = 'read';
196
+
197
+	const caps_read_admin = 'read_admin';
198
+
199
+	const caps_edit       = 'edit';
200
+
201
+	const caps_delete     = 'delete';
202
+
203
+	/**
204
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
+	 * maps to 'read' because when looking for relevant permissions we're going to use
207
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
208
+	 *
209
+	 * @var array
210
+	 */
211
+	protected $_cap_contexts_to_cap_action_map = array(
212
+		self::caps_read       => 'read',
213
+		self::caps_read_admin => 'read',
214
+		self::caps_edit       => 'edit',
215
+		self::caps_delete     => 'delete',
216
+	);
217
+
218
+	/**
219
+	 * Timezone
220
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
+	 * EE_Datetime_Field data type will have access to it.
224
+	 *
225
+	 * @var string
226
+	 */
227
+	protected $_timezone;
228
+
229
+
230
+	/**
231
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
+	 * multisite.
233
+	 *
234
+	 * @var int
235
+	 */
236
+	protected static $_model_query_blog_id;
237
+
238
+	/**
239
+	 * A copy of _fields, except the array keys are the model names pointed to by
240
+	 * the field
241
+	 *
242
+	 * @var EE_Model_Field_Base[]
243
+	 */
244
+	private $_cache_foreign_key_to_fields = array();
245
+
246
+	/**
247
+	 * Cached list of all the fields on the model, indexed by their name
248
+	 *
249
+	 * @var EE_Model_Field_Base[]
250
+	 */
251
+	private $_cached_fields = null;
252
+
253
+	/**
254
+	 * Cached list of all the fields on the model, except those that are
255
+	 * marked as only pertinent to the database
256
+	 *
257
+	 * @var EE_Model_Field_Base[]
258
+	 */
259
+	private $_cached_fields_non_db_only = null;
260
+
261
+	/**
262
+	 * A cached reference to the primary key for quick lookup
263
+	 *
264
+	 * @var EE_Model_Field_Base
265
+	 */
266
+	private $_primary_key_field = null;
267
+
268
+	/**
269
+	 * Flag indicating whether this model has a primary key or not
270
+	 *
271
+	 * @var boolean
272
+	 */
273
+	protected $_has_primary_key_field = null;
274
+
275
+	/**
276
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
277
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
+	 *
279
+	 * @var boolean
280
+	 */
281
+	protected $_wp_core_model = false;
282
+
283
+	/**
284
+	 *    List of valid operators that can be used for querying.
285
+	 * The keys are all operators we'll accept, the values are the real SQL
286
+	 * operators used
287
+	 *
288
+	 * @var array
289
+	 */
290
+	protected $_valid_operators = array(
291
+		'='           => '=',
292
+		'<='          => '<=',
293
+		'<'           => '<',
294
+		'>='          => '>=',
295
+		'>'           => '>',
296
+		'!='          => '!=',
297
+		'LIKE'        => 'LIKE',
298
+		'like'        => 'LIKE',
299
+		'NOT_LIKE'    => 'NOT LIKE',
300
+		'not_like'    => 'NOT LIKE',
301
+		'NOT LIKE'    => 'NOT LIKE',
302
+		'not like'    => 'NOT LIKE',
303
+		'IN'          => 'IN',
304
+		'in'          => 'IN',
305
+		'NOT_IN'      => 'NOT IN',
306
+		'not_in'      => 'NOT IN',
307
+		'NOT IN'      => 'NOT IN',
308
+		'not in'      => 'NOT IN',
309
+		'between'     => 'BETWEEN',
310
+		'BETWEEN'     => 'BETWEEN',
311
+		'IS_NOT_NULL' => 'IS NOT NULL',
312
+		'is_not_null' => 'IS NOT NULL',
313
+		'IS NOT NULL' => 'IS NOT NULL',
314
+		'is not null' => 'IS NOT NULL',
315
+		'IS_NULL'     => 'IS NULL',
316
+		'is_null'     => 'IS NULL',
317
+		'IS NULL'     => 'IS NULL',
318
+		'is null'     => 'IS NULL',
319
+		'REGEXP'      => 'REGEXP',
320
+		'regexp'      => 'REGEXP',
321
+		'NOT_REGEXP'  => 'NOT REGEXP',
322
+		'not_regexp'  => 'NOT REGEXP',
323
+		'NOT REGEXP'  => 'NOT REGEXP',
324
+		'not regexp'  => 'NOT REGEXP',
325
+	);
326
+
327
+	/**
328
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
+	 *
330
+	 * @var array
331
+	 */
332
+	protected $_in_style_operators = array('IN', 'NOT IN');
333
+
334
+	/**
335
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
+	 * '12-31-2012'"
337
+	 *
338
+	 * @var array
339
+	 */
340
+	protected $_between_style_operators = array('BETWEEN');
341
+
342
+	/**
343
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
+	 * on a join table.
345
+	 *
346
+	 * @var array
347
+	 */
348
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
+
350
+	/**
351
+	 * Allowed values for $query_params['order'] for ordering in queries
352
+	 *
353
+	 * @var array
354
+	 */
355
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
+
357
+	/**
358
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
360
+	 *
361
+	 * @var array
362
+	 */
363
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
+
365
+	/**
366
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
368
+	 *
369
+	 * @var array
370
+	 */
371
+	private $_allowed_query_params = array(
372
+		0,
373
+		'limit',
374
+		'order_by',
375
+		'group_by',
376
+		'having',
377
+		'force_join',
378
+		'order',
379
+		'on_join_limit',
380
+		'default_where_conditions',
381
+		'caps',
382
+	);
383
+
384
+	/**
385
+	 * All the data types that can be used in $wpdb->prepare statements.
386
+	 *
387
+	 * @var array
388
+	 */
389
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
+
391
+	/**
392
+	 *    EE_Registry Object
393
+	 *
394
+	 * @var    object
395
+	 * @access    protected
396
+	 */
397
+	protected $EE = null;
398
+
399
+
400
+	/**
401
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
+	 *
403
+	 * @var int
404
+	 */
405
+	protected $_show_next_x_db_queries = 0;
406
+
407
+	/**
408
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
+	 *
411
+	 * @var array
412
+	 */
413
+	protected $_custom_selections = array();
414
+
415
+	/**
416
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
+	 * caches every model object we've fetched from the DB on this request
418
+	 *
419
+	 * @var array
420
+	 */
421
+	protected $_entity_map;
422
+
423
+	/**
424
+	 * constant used to show EEM_Base has not yet verified the db on this http request
425
+	 */
426
+	const db_verified_none = 0;
427
+
428
+	/**
429
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
430
+	 * but not the addons' dbs
431
+	 */
432
+	const db_verified_core = 1;
433
+
434
+	/**
435
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
+	 * the EE core db too)
437
+	 */
438
+	const db_verified_addons = 2;
439
+
440
+	/**
441
+	 * indicates whether an EEM_Base child has already re-verified the DB
442
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
443
+	 * looking like EEM_Base::db_verified_*
444
+	 *
445
+	 * @var int - 0 = none, 1 = core, 2 = addons
446
+	 */
447
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
448
+
449
+	/**
450
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
453
+	 */
454
+	const default_where_conditions_all = 'all';
455
+
456
+	/**
457
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
+	 *        models which share tables with other models, this can return data for the wrong model.
462
+	 */
463
+	const default_where_conditions_this_only = 'this_model_only';
464
+
465
+	/**
466
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
+	 */
470
+	const default_where_conditions_others_only = 'other_models_only';
471
+
472
+	/**
473
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
476
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
+	 *        (regardless of whether those events and venues are trashed)
478
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
+	 *        events.
480
+	 */
481
+	const default_where_conditions_minimum_all = 'minimum';
482
+
483
+	/**
484
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
+	 *        not)
488
+	 */
489
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
+	 *        it's possible it will return table entries for other models. You should use
495
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
496
+	 */
497
+	const default_where_conditions_none = 'none';
498
+
499
+
500
+
501
+	/**
502
+	 * About all child constructors:
503
+	 * they should define the _tables, _fields and _model_relations arrays.
504
+	 * Should ALWAYS be called after child constructor.
505
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
506
+	 * finalizes constructing all the object's attributes.
507
+	 * Generally, rather than requiring a child to code
508
+	 * $this->_tables = array(
509
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
+	 *        ...);
511
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
+	 * each EE_Table has a function to set the table's alias after the constructor, using
513
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
+	 * do something similar.
515
+	 *
516
+	 * @param null $timezone
517
+	 * @throws EE_Error
518
+	 */
519
+	protected function __construct($timezone = null)
520
+	{
521
+		// check that the model has not been loaded too soon
522
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+			throw new EE_Error (
524
+				sprintf(
525
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
526
+						'event_espresso'),
527
+					get_class($this)
528
+				)
529
+			);
530
+		}
531
+		/**
532
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
+		 */
534
+		if (empty(EEM_Base::$_model_query_blog_id)) {
535
+			EEM_Base::set_model_query_blog_id();
536
+		}
537
+		/**
538
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
+		 * just use EE_Register_Model_Extension
540
+		 *
541
+		 * @var EE_Table_Base[] $_tables
542
+		 */
543
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
+		foreach ($this->_tables as $table_alias => $table_obj) {
545
+			/** @var $table_obj EE_Table_Base */
546
+			$table_obj->_construct_finalize_with_alias($table_alias);
547
+			if ($table_obj instanceof EE_Secondary_Table) {
548
+				/** @var $table_obj EE_Secondary_Table */
549
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
+			}
551
+		}
552
+		/**
553
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
+		 * EE_Register_Model_Extension
555
+		 *
556
+		 * @param EE_Model_Field_Base[] $_fields
557
+		 */
558
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
+		$this->_invalidate_field_caches();
560
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
561
+			if (! array_key_exists($table_alias, $this->_tables)) {
562
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				//primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			//make extra meta related to everything, but don't block deleting things just
575
+			//because they have related extra meta info. For now just orphan those extra meta
576
+			//in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		//and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
+			$this->_model_relations);
591
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
592
+			/** @var $relation_obj EE_Model_Relation_Base */
593
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
+		}
595
+		foreach ($this->_indexes as $index_name => $index_obj) {
596
+			/** @var $index_obj EE_Index */
597
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
+		}
599
+		$this->set_timezone($timezone);
600
+		//finalize default where condition strategy, or set default
601
+		if (! $this->_default_where_conditions_strategy) {
602
+			//nothing was set during child constructor, so set default
603
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
+		}
605
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
606
+		if (! $this->_minimum_where_conditions_strategy) {
607
+			//nothing was set during child constructor, so set default
608
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
+		}
610
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
612
+		//to indicate to NOT set it, set it to the logical default
613
+		if ($this->_caps_slug === null) {
614
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
+		}
616
+		//initialize the standard cap restriction generators if none were specified by the child constructor
617
+		if ($this->_cap_restriction_generators !== false) {
618
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
621
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
+						new EE_Restriction_Generator_Protected(),
623
+						$cap_context,
624
+						$this
625
+					);
626
+				}
627
+			}
628
+		}
629
+		//if there are cap restriction generators, use them to make the default cap restrictions
630
+		if ($this->_cap_restriction_generators !== false) {
631
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
+				if (! $generator_object) {
633
+					continue;
634
+				}
635
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
+					throw new EE_Error(
637
+						sprintf(
638
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
639
+								'event_espresso'),
640
+							$context,
641
+							$this->get_this_model_name()
642
+						)
643
+					);
644
+				}
645
+				$action = $this->cap_action_for_context($context);
646
+				if (! $generator_object->construction_finalized()) {
647
+					$generator_object->_construct_finalize($this, $action);
648
+				}
649
+			}
650
+		}
651
+		do_action('AHEE__' . get_class($this) . '__construct__end');
652
+	}
653
+
654
+
655
+
656
+	/**
657
+	 * Generates the cap restrictions for the given context, or if they were
658
+	 * already generated just gets what's cached
659
+	 *
660
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
661
+	 * @return EE_Default_Where_Conditions[]
662
+	 */
663
+	protected function _generate_cap_restrictions($context)
664
+	{
665
+		if (isset($this->_cap_restriction_generators[$context])
666
+			&& $this->_cap_restriction_generators[$context]
667
+			   instanceof
668
+			   EE_Restriction_Generator_Base
669
+		) {
670
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
+		} else {
672
+			return array();
673
+		}
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 * Used to set the $_model_query_blog_id static property.
680
+	 *
681
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
+	 *                      value for get_current_blog_id() will be used.
683
+	 */
684
+	public static function set_model_query_blog_id($blog_id = 0)
685
+	{
686
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
+	}
688
+
689
+
690
+
691
+	/**
692
+	 * Returns whatever is set as the internal $model_query_blog_id.
693
+	 *
694
+	 * @return int
695
+	 */
696
+	public static function get_model_query_blog_id()
697
+	{
698
+		return EEM_Base::$_model_query_blog_id;
699
+	}
700
+
701
+
702
+
703
+	/**
704
+	 * This function is a singleton method used to instantiate the Espresso_model object
705
+	 *
706
+	 * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
707
+	 *                                    (and any incoming timezone data that gets saved).
708
+	 *                                    Note this just sends the timezone info to the date time model field objects.
709
+	 *                                    Default is NULL
710
+	 *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
+	 * @param ModelFieldFactory $model_field_factory
712
+	 * @return static (as in the concrete child class)
713
+	 * @throws InvalidArgumentException
714
+	 * @throws InvalidInterfaceException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws EE_Error
717
+	 */
718
+	public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719
+	{
720
+		// check if instance of Espresso_model already exists
721
+		if (! static::$_instance instanceof static) {
722
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
723
+			// instantiate Espresso_model
724
+			static::$_instance = new static($timezone, $model_field_factory);
725
+		}
726
+		//we might have a timezone set, let set_timezone decide what to do with it
727
+		static::$_instance->set_timezone($timezone);
728
+		// Espresso_model object
729
+		return static::$_instance;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * @param $model_field_factory
736
+	 * @return ModelFieldFactory
737
+	 * @throws InvalidArgumentException
738
+	 * @throws InvalidDataTypeException
739
+	 * @throws InvalidInterfaceException
740
+	 */
741
+	private static function getModelFieldFactory($model_field_factory)
742
+	{
743
+		return $model_field_factory instanceof ModelFieldFactory
744
+			? $model_field_factory
745
+			: LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory');
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * resets the model and returns it
752
+	 *
753
+	 * @param null | string          $timezone
754
+	 * @param ModelFieldFactory|null $model_field_factory
755
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
756
+	 * @throws ReflectionException
757
+	 * all its properties reset; if it wasn't instantiated, returns null)
758
+	 * @throws EE_Error
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
764
+	{
765
+		if (static::$_instance instanceof EEM_Base) {
766
+			//let's try to NOT swap out the current instance for a new one
767
+			//because if someone has a reference to it, we can't remove their reference
768
+			//so it's best to keep using the same reference, but change the original object
769
+			//reset all its properties to their original values as defined in the class
770
+			$r = new ReflectionClass(get_class(static::$_instance));
771
+			$static_properties = $r->getStaticProperties();
772
+			foreach ($r->getDefaultProperties() as $property => $value) {
773
+				//don't set instance to null like it was originally,
774
+				//but it's static anyways, and we're ignoring static properties (for now at least)
775
+				if (! isset($static_properties[$property])) {
776
+					static::$_instance->{$property} = $value;
777
+				}
778
+			}
779
+			//and then directly call its constructor again, like we would if we were creating a new one
780
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
781
+			static::$_instance->__construct($timezone, $model_field_factory);
782
+			return self::instance();
783
+		}
784
+		return null;
785
+	}
786
+
787
+
788
+
789
+	/**
790
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
791
+	 *
792
+	 * @param  boolean $translated return localized strings or JUST the array.
793
+	 * @return array
794
+	 * @throws EE_Error
795
+	 */
796
+	public function status_array($translated = false)
797
+	{
798
+		if (! array_key_exists('Status', $this->_model_relations)) {
799
+			return array();
800
+		}
801
+		$model_name = $this->get_this_model_name();
802
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
803
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
804
+		$status_array = array();
805
+		foreach ($stati as $status) {
806
+			$status_array[$status->ID()] = $status->get('STS_code');
807
+		}
808
+		return $translated
809
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
810
+			: $status_array;
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
817
+	 *
818
+	 * @param array $query_params             {
819
+	 * @var array $0 (where) array {
820
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
821
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
822
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
823
+	 *                                        conditions based on related models (and even
824
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
825
+	 *                                        name. Eg,
826
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
827
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
828
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
829
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
830
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
831
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
832
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
833
+	 *                                        to Venues (even when each of those models actually consisted of two
834
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
835
+	 *                                        just having
836
+	 *                                        "Venue.VNU_ID", you could have
837
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
838
+	 *                                        events are related to Registrations, which are related to Attendees). You
839
+	 *                                        can take it even further with
840
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
841
+	 *                                        (from the default of '='), change the value to an numerically-indexed
842
+	 *                                        array, where the first item in the list is the operator. eg: array(
843
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
844
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
845
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
846
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
847
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
848
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
849
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
850
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
851
+	 *                                        the value is a field, simply provide a third array item (true) to the
852
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
853
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
854
+	 *                                        Note: you can also use related model field names like you would any other
855
+	 *                                        field name. eg:
856
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
857
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
858
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
859
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
860
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
861
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
862
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
863
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
864
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
865
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
866
+	 *                                        "stick" until you specify an AND. eg
867
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
868
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
869
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
870
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
871
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
872
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
873
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
874
+	 *                                        too, eg:
875
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
876
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
877
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
878
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
879
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
880
+	 *                                        the OFFSET, the 2nd is the LIMIT
881
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
882
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
883
+	 *                                        following format array('on_join_limit'
884
+	 *                                        => array( 'table_alias', array(1,2) ) ).
885
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
886
+	 *                                        values are either 'ASC' or 'DESC'.
887
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
888
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
889
+	 *                                        DESC..." respectively. Like the
890
+	 *                                        'where' conditions, these fields can be on related models. Eg
891
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
892
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
893
+	 *                                        Attendee, Price, Datetime, etc.)
894
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
895
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
896
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
897
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
898
+	 *                                        order by the primary key. Eg,
899
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
900
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
901
+	 *                                        DTT_EVT_start) or
902
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
903
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
904
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
905
+	 *                                        'group_by'=>'VNU_ID', or
906
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
907
+	 *                                        if no
908
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
909
+	 *                                        model's primary key (or combined primary keys). This avoids some
910
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
911
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
912
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
913
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
914
+	 *                                        results)
915
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
916
+	 *                                        array where values are models to be joined in the query.Eg
917
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
918
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
919
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
920
+	 *                                        related models which belongs to the current model
921
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
922
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
923
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
924
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
925
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
926
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
927
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
928
+	 *                                        this model's default where conditions added to the query, use
929
+	 *                                        'this_model_only'. If you want to use all default where conditions
930
+	 *                                        (default), set to 'all'.
931
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
932
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
933
+	 *                                        everything? Or should we only show the current user items they should be
934
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
935
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
936
+	 *                                        }
937
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
938
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
939
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
940
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
941
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
942
+	 *                                        array( array(
943
+	 *                                        'OR'=>array(
944
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
945
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
946
+	 *                                        )
947
+	 *                                        ),
948
+	 *                                        'limit'=>10,
949
+	 *                                        'group_by'=>'TXN_ID'
950
+	 *                                        ));
951
+	 *                                        get all the answers to the question titled "shirt size" for event with id
952
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
953
+	 *                                        'Question.QST_display_text'=>'shirt size',
954
+	 *                                        'Registration.Event.EVT_ID'=>12
955
+	 *                                        ),
956
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
957
+	 *                                        ));
958
+	 * @throws EE_Error
959
+	 */
960
+	public function get_all($query_params = array())
961
+	{
962
+		if (isset($query_params['limit'])
963
+			&& ! isset($query_params['group_by'])
964
+		) {
965
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
966
+		}
967
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
968
+	}
969
+
970
+
971
+
972
+	/**
973
+	 * Modifies the query parameters so we only get back model objects
974
+	 * that "belong" to the current user
975
+	 *
976
+	 * @param array $query_params @see EEM_Base::get_all()
977
+	 * @return array like EEM_Base::get_all
978
+	 */
979
+	public function alter_query_params_to_only_include_mine($query_params = array())
980
+	{
981
+		$wp_user_field_name = $this->wp_user_field_name();
982
+		if ($wp_user_field_name) {
983
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
984
+		}
985
+		return $query_params;
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * Returns the name of the field's name that points to the WP_User table
992
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
993
+	 * foreign key to the WP_User table)
994
+	 *
995
+	 * @return string|boolean string on success, boolean false when there is no
996
+	 * foreign key to the WP_User table
997
+	 */
998
+	public function wp_user_field_name()
999
+	{
1000
+		try {
1001
+			if (! empty($this->_model_chain_to_wp_user)) {
1002
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003
+				$last_model_name = end($models_to_follow_to_wp_users);
1004
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1006
+			} else {
1007
+				$model_with_fk_to_wp_users = $this;
1008
+				$model_chain_to_wp_user = '';
1009
+			}
1010
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
1012
+		} catch (EE_Error $e) {
1013
+			return false;
1014
+		}
1015
+	}
1016
+
1017
+
1018
+
1019
+	/**
1020
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1021
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1022
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1023
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1024
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1025
+	 * (or transiently-related model)
1026
+	 *
1027
+	 * @return string
1028
+	 */
1029
+	public function model_chain_to_wp_user()
1030
+	{
1031
+		return $this->_model_chain_to_wp_user;
1032
+	}
1033
+
1034
+
1035
+
1036
+	/**
1037
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1038
+	 * like how registrations don't have a foreign key to wp_users, but the
1039
+	 * events they are for are), or is unrelated to wp users.
1040
+	 * generally available
1041
+	 *
1042
+	 * @return boolean
1043
+	 */
1044
+	public function is_owned()
1045
+	{
1046
+		if ($this->model_chain_to_wp_user()) {
1047
+			return true;
1048
+		}
1049
+		try {
1050
+			$this->get_foreign_key_to('WP_User');
1051
+			return true;
1052
+		} catch (EE_Error $e) {
1053
+			return false;
1054
+		}
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1061
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1062
+	 * the model)
1063
+	 *
1064
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1065
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1066
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1067
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1068
+	 *                                  override this and set the select to "*", or a specific column name, like
1069
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1070
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1071
+	 *                                  the aliases used to refer to this selection, and values are to be
1072
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1073
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1074
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1075
+	 * @throws EE_Error
1076
+	 */
1077
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1078
+	{
1079
+		// remember the custom selections, if any, and type cast as array
1080
+		// (unless $columns_to_select is an object, then just set as an empty array)
1081
+		// Note: (array) 'some string' === array( 'some string' )
1082
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1083
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1084
+		$select_expressions = $columns_to_select !== null
1085
+			? $this->_construct_select_from_input($columns_to_select)
1086
+			: $this->_construct_default_select_sql($model_query_info);
1087
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1088
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089
+	}
1090
+
1091
+
1092
+
1093
+	/**
1094
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1095
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1096
+	 * take care of joins, field preparation etc.
1097
+	 *
1098
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1099
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1100
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1101
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1102
+	 *                                  override this and set the select to "*", or a specific column name, like
1103
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1104
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1105
+	 *                                  the aliases used to refer to this selection, and values are to be
1106
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1107
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1108
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1112
+	{
1113
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * For creating a custom select statement
1120
+	 *
1121
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1122
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1123
+	 *                                 SQL, and 1=>is the datatype
1124
+	 * @throws EE_Error
1125
+	 * @return string
1126
+	 */
1127
+	private function _construct_select_from_input($columns_to_select)
1128
+	{
1129
+		if (is_array($columns_to_select)) {
1130
+			$select_sql_array = array();
1131
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133
+					throw new EE_Error(
1134
+						sprintf(
1135
+							__(
1136
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1137
+								"event_espresso"
1138
+							),
1139
+							$selection_and_datatype,
1140
+							$alias
1141
+						)
1142
+					);
1143
+				}
1144
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145
+					throw new EE_Error(
1146
+						sprintf(
1147
+							__(
1148
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1149
+								"event_espresso"
1150
+							),
1151
+							$selection_and_datatype[1],
1152
+							$selection_and_datatype[0],
1153
+							$alias,
1154
+							implode(",", $this->_valid_wpdb_data_types)
1155
+						)
1156
+					);
1157
+				}
1158
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1159
+			}
1160
+			$columns_to_select_string = implode(", ", $select_sql_array);
1161
+		} else {
1162
+			$columns_to_select_string = $columns_to_select;
1163
+		}
1164
+		return $columns_to_select_string;
1165
+	}
1166
+
1167
+
1168
+
1169
+	/**
1170
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1171
+	 *
1172
+	 * @return string
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function primary_key_name()
1176
+	{
1177
+		return $this->get_primary_key_field()->get_name();
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1184
+	 * If there is no primary key on this model, $id is treated as primary key string
1185
+	 *
1186
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1187
+	 * @return EE_Base_Class
1188
+	 */
1189
+	public function get_one_by_ID($id)
1190
+	{
1191
+		if ($this->get_from_entity_map($id)) {
1192
+			return $this->get_from_entity_map($id);
1193
+		}
1194
+		return $this->get_one(
1195
+			$this->alter_query_params_to_restrict_by_ID(
1196
+				$id,
1197
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1198
+			)
1199
+		);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Alters query parameters to only get items with this ID are returned.
1206
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1207
+	 * or could just be a simple primary key ID
1208
+	 *
1209
+	 * @param int   $id
1210
+	 * @param array $query_params
1211
+	 * @return array of normal query params, @see EEM_Base::get_all
1212
+	 * @throws EE_Error
1213
+	 */
1214
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215
+	{
1216
+		if (! isset($query_params[0])) {
1217
+			$query_params[0] = array();
1218
+		}
1219
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1220
+		if ($conditions_from_id === null) {
1221
+			$query_params[0][$this->primary_key_name()] = $id;
1222
+		} else {
1223
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1224
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1225
+		}
1226
+		return $query_params;
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1233
+	 * array. If no item is found, null is returned.
1234
+	 *
1235
+	 * @param array $query_params like EEM_Base's $query_params variable.
1236
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1237
+	 * @throws EE_Error
1238
+	 */
1239
+	public function get_one($query_params = array())
1240
+	{
1241
+		if (! is_array($query_params)) {
1242
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1243
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
+					gettype($query_params)), '4.6.0');
1245
+			$query_params = array();
1246
+		}
1247
+		$query_params['limit'] = 1;
1248
+		$items = $this->get_all($query_params);
1249
+		if (empty($items)) {
1250
+			return null;
1251
+		}
1252
+		return array_shift($items);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Returns the next x number of items in sequence from the given value as
1259
+	 * found in the database matching the given query conditions.
1260
+	 *
1261
+	 * @param mixed $current_field_value    Value used for the reference point.
1262
+	 * @param null  $field_to_order_by      What field is used for the
1263
+	 *                                      reference point.
1264
+	 * @param int   $limit                  How many to return.
1265
+	 * @param array $query_params           Extra conditions on the query.
1266
+	 * @param null  $columns_to_select      If left null, then an array of
1267
+	 *                                      EE_Base_Class objects is returned,
1268
+	 *                                      otherwise you can indicate just the
1269
+	 *                                      columns you want returned.
1270
+	 * @return EE_Base_Class[]|array
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function next_x(
1274
+		$current_field_value,
1275
+		$field_to_order_by = null,
1276
+		$limit = 1,
1277
+		$query_params = array(),
1278
+		$columns_to_select = null
1279
+	) {
1280
+		return $this->_get_consecutive(
1281
+			$current_field_value,
1282
+			'>',
1283
+			$field_to_order_by,
1284
+			$limit,
1285
+			$query_params,
1286
+			$columns_to_select
1287
+		);
1288
+	}
1289
+
1290
+
1291
+
1292
+	/**
1293
+	 * Returns the previous x number of items in sequence from the given value
1294
+	 * as found in the database matching the given query conditions.
1295
+	 *
1296
+	 * @param mixed $current_field_value    Value used for the reference point.
1297
+	 * @param null  $field_to_order_by      What field is used for the
1298
+	 *                                      reference point.
1299
+	 * @param int   $limit                  How many to return.
1300
+	 * @param array $query_params           Extra conditions on the query.
1301
+	 * @param null  $columns_to_select      If left null, then an array of
1302
+	 *                                      EE_Base_Class objects is returned,
1303
+	 *                                      otherwise you can indicate just the
1304
+	 *                                      columns you want returned.
1305
+	 * @return EE_Base_Class[]|array
1306
+	 * @throws EE_Error
1307
+	 */
1308
+	public function previous_x(
1309
+		$current_field_value,
1310
+		$field_to_order_by = null,
1311
+		$limit = 1,
1312
+		$query_params = array(),
1313
+		$columns_to_select = null
1314
+	) {
1315
+		return $this->_get_consecutive(
1316
+			$current_field_value,
1317
+			'<',
1318
+			$field_to_order_by,
1319
+			$limit,
1320
+			$query_params,
1321
+			$columns_to_select
1322
+		);
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * Returns the next item in sequence from the given value as found in the
1329
+	 * database matching the given query conditions.
1330
+	 *
1331
+	 * @param mixed $current_field_value    Value used for the reference point.
1332
+	 * @param null  $field_to_order_by      What field is used for the
1333
+	 *                                      reference point.
1334
+	 * @param array $query_params           Extra conditions on the query.
1335
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
+	 *                                      object is returned, otherwise you
1337
+	 *                                      can indicate just the columns you
1338
+	 *                                      want and a single array indexed by
1339
+	 *                                      the columns will be returned.
1340
+	 * @return EE_Base_Class|null|array()
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function next(
1344
+		$current_field_value,
1345
+		$field_to_order_by = null,
1346
+		$query_params = array(),
1347
+		$columns_to_select = null
1348
+	) {
1349
+		$results = $this->_get_consecutive(
1350
+			$current_field_value,
1351
+			'>',
1352
+			$field_to_order_by,
1353
+			1,
1354
+			$query_params,
1355
+			$columns_to_select
1356
+		);
1357
+		return empty($results) ? null : reset($results);
1358
+	}
1359
+
1360
+
1361
+
1362
+	/**
1363
+	 * Returns the previous item in sequence from the given value as found in
1364
+	 * the database matching the given query conditions.
1365
+	 *
1366
+	 * @param mixed $current_field_value    Value used for the reference point.
1367
+	 * @param null  $field_to_order_by      What field is used for the
1368
+	 *                                      reference point.
1369
+	 * @param array $query_params           Extra conditions on the query.
1370
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1371
+	 *                                      object is returned, otherwise you
1372
+	 *                                      can indicate just the columns you
1373
+	 *                                      want and a single array indexed by
1374
+	 *                                      the columns will be returned.
1375
+	 * @return EE_Base_Class|null|array()
1376
+	 * @throws EE_Error
1377
+	 */
1378
+	public function previous(
1379
+		$current_field_value,
1380
+		$field_to_order_by = null,
1381
+		$query_params = array(),
1382
+		$columns_to_select = null
1383
+	) {
1384
+		$results = $this->_get_consecutive(
1385
+			$current_field_value,
1386
+			'<',
1387
+			$field_to_order_by,
1388
+			1,
1389
+			$query_params,
1390
+			$columns_to_select
1391
+		);
1392
+		return empty($results) ? null : reset($results);
1393
+	}
1394
+
1395
+
1396
+
1397
+	/**
1398
+	 * Returns the a consecutive number of items in sequence from the given
1399
+	 * value as found in the database matching the given query conditions.
1400
+	 *
1401
+	 * @param mixed  $current_field_value   Value used for the reference point.
1402
+	 * @param string $operand               What operand is used for the sequence.
1403
+	 * @param string $field_to_order_by     What field is used for the reference point.
1404
+	 * @param int    $limit                 How many to return.
1405
+	 * @param array  $query_params          Extra conditions on the query.
1406
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
+	 *                                      otherwise you can indicate just the columns you want returned.
1408
+	 * @return EE_Base_Class[]|array
1409
+	 * @throws EE_Error
1410
+	 */
1411
+	protected function _get_consecutive(
1412
+		$current_field_value,
1413
+		$operand = '>',
1414
+		$field_to_order_by = null,
1415
+		$limit = 1,
1416
+		$query_params = array(),
1417
+		$columns_to_select = null
1418
+	) {
1419
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1420
+		if (empty($field_to_order_by)) {
1421
+			if ($this->has_primary_key_field()) {
1422
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1423
+			} else {
1424
+				if (WP_DEBUG) {
1425
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1426
+						'event_espresso'));
1427
+				}
1428
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
+				return array();
1430
+			}
1431
+		}
1432
+		if (! is_array($query_params)) {
1433
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435
+					gettype($query_params)), '4.6.0');
1436
+			$query_params = array();
1437
+		}
1438
+		//let's add the where query param for consecutive look up.
1439
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440
+		$query_params['limit'] = $limit;
1441
+		//set direction
1442
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1443
+		$query_params['order_by'] = $operand === '>'
1444
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1445
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1446
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1447
+		if (empty($columns_to_select)) {
1448
+			return $this->get_all($query_params);
1449
+		}
1450
+		//getting just the fields
1451
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1452
+	}
1453
+
1454
+
1455
+
1456
+	/**
1457
+	 * This sets the _timezone property after model object has been instantiated.
1458
+	 *
1459
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
+	 */
1461
+	public function set_timezone($timezone)
1462
+	{
1463
+		if ($timezone !== null) {
1464
+			$this->_timezone = $timezone;
1465
+		}
1466
+		//note we need to loop through relations and set the timezone on those objects as well.
1467
+		foreach ($this->_model_relations as $relation) {
1468
+			$relation->set_timezone($timezone);
1469
+		}
1470
+		//and finally we do the same for any datetime fields
1471
+		foreach ($this->_fields as $field) {
1472
+			if ($field instanceof EE_Datetime_Field) {
1473
+				$field->set_timezone($timezone);
1474
+			}
1475
+		}
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * This just returns whatever is set for the current timezone.
1482
+	 *
1483
+	 * @access public
1484
+	 * @return string
1485
+	 */
1486
+	public function get_timezone()
1487
+	{
1488
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1489
+		if (empty($this->_timezone)) {
1490
+			foreach ($this->_fields as $field) {
1491
+				if ($field instanceof EE_Datetime_Field) {
1492
+					$this->set_timezone($field->get_timezone());
1493
+					break;
1494
+				}
1495
+			}
1496
+		}
1497
+		//if timezone STILL empty then return the default timezone for the site.
1498
+		if (empty($this->_timezone)) {
1499
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1500
+		}
1501
+		return $this->_timezone;
1502
+	}
1503
+
1504
+
1505
+
1506
+	/**
1507
+	 * This returns the date formats set for the given field name and also ensures that
1508
+	 * $this->_timezone property is set correctly.
1509
+	 *
1510
+	 * @since 4.6.x
1511
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1512
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1514
+	 * @return array formats in an array with the date format first, and the time format last.
1515
+	 */
1516
+	public function get_formats_for($field_name, $pretty = false)
1517
+	{
1518
+		$field_settings = $this->field_settings_for($field_name);
1519
+		//if not a valid EE_Datetime_Field then throw error
1520
+		if (! $field_settings instanceof EE_Datetime_Field) {
1521
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1522
+				'event_espresso'), $field_name));
1523
+		}
1524
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1525
+		//the field.
1526
+		$this->_timezone = $field_settings->get_timezone();
1527
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * This returns the current time in a format setup for a query on this model.
1534
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1535
+	 * it will return:
1536
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1537
+	 *  NOW
1538
+	 *  - or a unix timestamp (equivalent to time())
1539
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1540
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1541
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1542
+	 * @since 4.6.x
1543
+	 * @param string $field_name       The field the current time is needed for.
1544
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1545
+	 *                                 formatted string matching the set format for the field in the set timezone will
1546
+	 *                                 be returned.
1547
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1548
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1549
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1550
+	 *                                 exception is triggered.
1551
+	 */
1552
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1553
+	{
1554
+		$formats = $this->get_formats_for($field_name);
1555
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1556
+		if ($timestamp) {
1557
+			return $DateTime->format('U');
1558
+		}
1559
+		//not returning timestamp, so return formatted string in timezone.
1560
+		switch ($what) {
1561
+			case 'time' :
1562
+				return $DateTime->format($formats[1]);
1563
+				break;
1564
+			case 'date' :
1565
+				return $DateTime->format($formats[0]);
1566
+				break;
1567
+			default :
1568
+				return $DateTime->format(implode(' ', $formats));
1569
+				break;
1570
+		}
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1577
+	 * for the model are.  Returns a DateTime object.
1578
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1579
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1580
+	 * ignored.
1581
+	 *
1582
+	 * @param string $field_name      The field being setup.
1583
+	 * @param string $timestring      The date time string being used.
1584
+	 * @param string $incoming_format The format for the time string.
1585
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1586
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1587
+	 *                                format is
1588
+	 *                                'U', this is ignored.
1589
+	 * @return DateTime
1590
+	 * @throws EE_Error
1591
+	 */
1592
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1593
+	{
1594
+		//just using this to ensure the timezone is set correctly internally
1595
+		$this->get_formats_for($field_name);
1596
+		//load EEH_DTT_Helper
1597
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1600
+	}
1601
+
1602
+
1603
+
1604
+	/**
1605
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1606
+	 *
1607
+	 * @return EE_Table_Base[]
1608
+	 */
1609
+	public function get_tables()
1610
+	{
1611
+		return $this->_tables;
1612
+	}
1613
+
1614
+
1615
+
1616
+	/**
1617
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1618
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1619
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1620
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1621
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1622
+	 * model object with EVT_ID = 1
1623
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1624
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1625
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1626
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1627
+	 * are not specified)
1628
+	 *
1629
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1630
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1631
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1632
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1633
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1634
+	 *                                         ID=34, we'd use this method as follows:
1635
+	 *                                         EEM_Transaction::instance()->update(
1636
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1637
+	 *                                         array(array('TXN_ID'=>34)));
1638
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1639
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1640
+	 *                                         consider updating Question's QST_admin_label field is of type
1641
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1642
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1643
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1644
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1645
+	 *                                         TRUE, it is assumed that you've already called
1646
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1647
+	 *                                         malicious javascript. However, if
1648
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1649
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1650
+	 *                                         and every other field, before insertion. We provide this parameter
1651
+	 *                                         because model objects perform their prepare_for_set function on all
1652
+	 *                                         their values, and so don't need to be called again (and in many cases,
1653
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1654
+	 *                                         prepare_for_set method...)
1655
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1656
+	 *                                         in this model's entity map according to $fields_n_values that match
1657
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1658
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1659
+	 *                                         could get out-of-sync with the database
1660
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1661
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1662
+	 *                                         bad)
1663
+	 * @throws EE_Error
1664
+	 */
1665
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666
+	{
1667
+		if (! is_array($query_params)) {
1668
+			EE_Error::doing_it_wrong('EEM_Base::update',
1669
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670
+					gettype($query_params)), '4.6.0');
1671
+			$query_params = array();
1672
+		}
1673
+		/**
1674
+		 * Action called before a model update call has been made.
1675
+		 *
1676
+		 * @param EEM_Base $model
1677
+		 * @param array    $fields_n_values the updated fields and their new values
1678
+		 * @param array    $query_params    @see EEM_Base::get_all()
1679
+		 */
1680
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1681
+		/**
1682
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1683
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1684
+		 *
1685
+		 * @param array    $fields_n_values fields and their new values
1686
+		 * @param EEM_Base $model           the model being queried
1687
+		 * @param array    $query_params    see EEM_Base::get_all()
1688
+		 */
1689
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690
+			$query_params);
1691
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1692
+		//to do that, for each table, verify that it's PK isn't null.
1693
+		$tables = $this->get_tables();
1694
+		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1695
+		//NOTE: we should make this code more efficient by NOT querying twice
1696
+		//before the real update, but that needs to first go through ALPHA testing
1697
+		//as it's dangerous. says Mike August 8 2014
1698
+		//we want to make sure the default_where strategy is ignored
1699
+		$this->_ignore_where_strategy = true;
1700
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701
+		foreach ($wpdb_select_results as $wpdb_result) {
1702
+			// type cast stdClass as array
1703
+			$wpdb_result = (array)$wpdb_result;
1704
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705
+			if ($this->has_primary_key_field()) {
1706
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1707
+			} else {
1708
+				//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1709
+				$main_table_pk_value = null;
1710
+			}
1711
+			//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1712
+			//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1713
+			if (count($tables) > 1) {
1714
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1715
+				//in that table, and so we'll want to insert one
1716
+				foreach ($tables as $table_obj) {
1717
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718
+					//if there is no private key for this table on the results, it means there's no entry
1719
+					//in this table, right? so insert a row in the current table, using any fields available
1720
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1721
+						   && $wpdb_result[$this_table_pk_column])
1722
+					) {
1723
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724
+							$main_table_pk_value);
1725
+						//if we died here, report the error
1726
+						if (! $success) {
1727
+							return false;
1728
+						}
1729
+					}
1730
+				}
1731
+			}
1732
+			//				//and now check that if we have cached any models by that ID on the model, that
1733
+			//				//they also get updated properly
1734
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1735
+			//				if( $model_object ){
1736
+			//					foreach( $fields_n_values as $field => $value ){
1737
+			//						$model_object->set($field, $value);
1738
+			//let's make sure default_where strategy is followed now
1739
+			$this->_ignore_where_strategy = false;
1740
+		}
1741
+		//if we want to keep model objects in sync, AND
1742
+		//if this wasn't called from a model object (to update itself)
1743
+		//then we want to make sure we keep all the existing
1744
+		//model objects in sync with the db
1745
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1746
+			if ($this->has_primary_key_field()) {
1747
+				$model_objs_affected_ids = $this->get_col($query_params);
1748
+			} else {
1749
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1750
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1751
+				$model_objs_affected_ids = array();
1752
+				foreach ($models_affected_key_columns as $row) {
1753
+					$combined_index_key = $this->get_index_primary_key_string($row);
1754
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755
+				}
1756
+			}
1757
+			if (! $model_objs_affected_ids) {
1758
+				//wait wait wait- if nothing was affected let's stop here
1759
+				return 0;
1760
+			}
1761
+			foreach ($model_objs_affected_ids as $id) {
1762
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1763
+				if ($model_obj_in_entity_map) {
1764
+					foreach ($fields_n_values as $field => $new_value) {
1765
+						$model_obj_in_entity_map->set($field, $new_value);
1766
+					}
1767
+				}
1768
+			}
1769
+			//if there is a primary key on this model, we can now do a slight optimization
1770
+			if ($this->has_primary_key_field()) {
1771
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1772
+				$query_params = array(
1773
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1774
+					'limit'                    => count($model_objs_affected_ids),
1775
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1776
+				);
1777
+			}
1778
+		}
1779
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1780
+		$SQL = "UPDATE "
1781
+			   . $model_query_info->get_full_join_sql()
1782
+			   . " SET "
1783
+			   . $this->_construct_update_sql($fields_n_values)
1784
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786
+		/**
1787
+		 * Action called after a model update call has been made.
1788
+		 *
1789
+		 * @param EEM_Base $model
1790
+		 * @param array    $fields_n_values the updated fields and their new values
1791
+		 * @param array    $query_params    @see EEM_Base::get_all()
1792
+		 * @param int      $rows_affected
1793
+		 */
1794
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
+		return $rows_affected;//how many supposedly got updated
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1802
+	 * are teh values of the field specified (or by default the primary key field)
1803
+	 * that matched the query params. Note that you should pass the name of the
1804
+	 * model FIELD, not the database table's column name.
1805
+	 *
1806
+	 * @param array  $query_params @see EEM_Base::get_all()
1807
+	 * @param string $field_to_select
1808
+	 * @return array just like $wpdb->get_col()
1809
+	 * @throws EE_Error
1810
+	 */
1811
+	public function get_col($query_params = array(), $field_to_select = null)
1812
+	{
1813
+		if ($field_to_select) {
1814
+			$field = $this->field_settings_for($field_to_select);
1815
+		} elseif ($this->has_primary_key_field()) {
1816
+			$field = $this->get_primary_key_field();
1817
+		} else {
1818
+			//no primary key, just grab the first column
1819
+			$field = reset($this->field_settings());
1820
+		}
1821
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1822
+		$select_expressions = $field->get_qualified_column();
1823
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1824
+		return $this->_do_wpdb_query('get_col', array($SQL));
1825
+	}
1826
+
1827
+
1828
+
1829
+	/**
1830
+	 * Returns a single column value for a single row from the database
1831
+	 *
1832
+	 * @param array  $query_params    @see EEM_Base::get_all()
1833
+	 * @param string $field_to_select @see EEM_Base::get_col()
1834
+	 * @return string
1835
+	 * @throws EE_Error
1836
+	 */
1837
+	public function get_var($query_params = array(), $field_to_select = null)
1838
+	{
1839
+		$query_params['limit'] = 1;
1840
+		$col = $this->get_col($query_params, $field_to_select);
1841
+		if (! empty($col)) {
1842
+			return reset($col);
1843
+		}
1844
+		return null;
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1851
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1852
+	 * injection, but currently no further filtering is done
1853
+	 *
1854
+	 * @global      $wpdb
1855
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1856
+	 *                               be updated to in the DB
1857
+	 * @return string of SQL
1858
+	 * @throws EE_Error
1859
+	 */
1860
+	public function _construct_update_sql($fields_n_values)
1861
+	{
1862
+		/** @type WPDB $wpdb */
1863
+		global $wpdb;
1864
+		$cols_n_values = array();
1865
+		foreach ($fields_n_values as $field_name => $value) {
1866
+			$field_obj = $this->field_settings_for($field_name);
1867
+			//if the value is NULL, we want to assign the value to that.
1868
+			//wpdb->prepare doesn't really handle that properly
1869
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870
+			$value_sql = $prepared_value === null ? 'NULL'
1871
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1873
+		}
1874
+		return implode(",", $cols_n_values);
1875
+	}
1876
+
1877
+
1878
+
1879
+	/**
1880
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1881
+	 * Performs a HARD delete, meaning the database row should always be removed,
1882
+	 * not just have a flag field on it switched
1883
+	 * Wrapper for EEM_Base::delete_permanently()
1884
+	 *
1885
+	 * @param mixed $id
1886
+	 * @return boolean whether the row got deleted or not
1887
+	 * @throws EE_Error
1888
+	 */
1889
+	public function delete_permanently_by_ID($id)
1890
+	{
1891
+		return $this->delete_permanently(
1892
+			array(
1893
+				array($this->get_primary_key_field()->get_name() => $id),
1894
+				'limit' => 1,
1895
+			)
1896
+		);
1897
+	}
1898
+
1899
+
1900
+
1901
+	/**
1902
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1903
+	 * Wrapper for EEM_Base::delete()
1904
+	 *
1905
+	 * @param mixed $id
1906
+	 * @return boolean whether the row got deleted or not
1907
+	 * @throws EE_Error
1908
+	 */
1909
+	public function delete_by_ID($id)
1910
+	{
1911
+		return $this->delete(
1912
+			array(
1913
+				array($this->get_primary_key_field()->get_name() => $id),
1914
+				'limit' => 1,
1915
+			)
1916
+		);
1917
+	}
1918
+
1919
+
1920
+
1921
+	/**
1922
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1923
+	 * meaning if the model has a field that indicates its been "trashed" or
1924
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1925
+	 *
1926
+	 * @see EEM_Base::delete_permanently
1927
+	 * @param array   $query_params
1928
+	 * @param boolean $allow_blocking
1929
+	 * @return int how many rows got deleted
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete($query_params, $allow_blocking = true)
1933
+	{
1934
+		return $this->delete_permanently($query_params, $allow_blocking);
1935
+	}
1936
+
1937
+
1938
+
1939
+	/**
1940
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1941
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1942
+	 * as archived, not actually deleted
1943
+	 *
1944
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1945
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1946
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1947
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1948
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1949
+	 *                                DB
1950
+	 * @return int how many rows got deleted
1951
+	 * @throws EE_Error
1952
+	 */
1953
+	public function delete_permanently($query_params, $allow_blocking = true)
1954
+	{
1955
+		/**
1956
+		 * Action called just before performing a real deletion query. You can use the
1957
+		 * model and its $query_params to find exactly which items will be deleted
1958
+		 *
1959
+		 * @param EEM_Base $model
1960
+		 * @param array    $query_params   @see EEM_Base::get_all()
1961
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1962
+		 *                                 to block (prevent) this deletion
1963
+		 */
1964
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1965
+		//some MySQL databases may be running safe mode, which may restrict
1966
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1967
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1968
+		//to delete them
1969
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1970
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1971
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1972
+			$columns_and_ids_for_deleting
1973
+		);
1974
+		/**
1975
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1976
+		 *
1977
+		 * @param EEM_Base $this  The model instance being acted on.
1978
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1979
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1980
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1981
+		 *                                                  derived from the incoming query parameters.
1982
+		 *                                                  @see details on the structure of this array in the phpdocs
1983
+		 *                                                  for the `_get_ids_for_delete_method`
1984
+		 *
1985
+		 */
1986
+		do_action('AHEE__EEM_Base__delete__before_query',
1987
+			$this,
1988
+			$query_params,
1989
+			$allow_blocking,
1990
+			$columns_and_ids_for_deleting
1991
+		);
1992
+		if ($deletion_where_query_part) {
1993
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1994
+			$table_aliases = array_keys($this->_tables);
1995
+			$SQL = "DELETE "
1996
+				   . implode(", ", $table_aliases)
1997
+				   . " FROM "
1998
+				   . $model_query_info->get_full_join_sql()
1999
+				   . " WHERE "
2000
+				   . $deletion_where_query_part;
2001
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2002
+		} else {
2003
+			$rows_deleted = 0;
2004
+		}
2005
+
2006
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2007
+		//there was no error with the delete query.
2008
+		if ($this->has_primary_key_field()
2009
+			&& $rows_deleted !== false
2010
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2011
+		) {
2012
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2013
+			foreach ($ids_for_removal as $id) {
2014
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2015
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2016
+				}
2017
+			}
2018
+
2019
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2020
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2021
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2022
+			// (although it is possible).
2023
+			//Note this can be skipped by using the provided filter and returning false.
2024
+			if (apply_filters(
2025
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2026
+				! $this instanceof EEM_Extra_Meta,
2027
+				$this
2028
+			)) {
2029
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2030
+					0 => array(
2031
+						'EXM_type' => $this->get_this_model_name(),
2032
+						'OBJ_ID'   => array(
2033
+							'IN',
2034
+							$ids_for_removal
2035
+						)
2036
+					)
2037
+				));
2038
+			}
2039
+		}
2040
+
2041
+		/**
2042
+		 * Action called just after performing a real deletion query. Although at this point the
2043
+		 * items should have been deleted
2044
+		 *
2045
+		 * @param EEM_Base $model
2046
+		 * @param array    $query_params @see EEM_Base::get_all()
2047
+		 * @param int      $rows_deleted
2048
+		 */
2049
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
+		return $rows_deleted;//how many supposedly got deleted
2051
+	}
2052
+
2053
+
2054
+
2055
+	/**
2056
+	 * Checks all the relations that throw error messages when there are blocking related objects
2057
+	 * for related model objects. If there are any related model objects on those relations,
2058
+	 * adds an EE_Error, and return true
2059
+	 *
2060
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2061
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2062
+	 *                                                 should be ignored when determining whether there are related
2063
+	 *                                                 model objects which block this model object's deletion. Useful
2064
+	 *                                                 if you know A is related to B and are considering deleting A,
2065
+	 *                                                 but want to see if A has any other objects blocking its deletion
2066
+	 *                                                 before removing the relation between A and B
2067
+	 * @return boolean
2068
+	 * @throws EE_Error
2069
+	 */
2070
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2071
+	{
2072
+		//first, if $ignore_this_model_obj was supplied, get its model
2073
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2074
+			$ignored_model = $ignore_this_model_obj->get_model();
2075
+		} else {
2076
+			$ignored_model = null;
2077
+		}
2078
+		//now check all the relations of $this_model_obj_or_id and see if there
2079
+		//are any related model objects blocking it?
2080
+		$is_blocked = false;
2081
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2082
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2083
+				//if $ignore_this_model_obj was supplied, then for the query
2084
+				//on that model needs to be told to ignore $ignore_this_model_obj
2085
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2086
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2087
+						array(
2088
+							$ignored_model->get_primary_key_field()->get_name() => array(
2089
+								'!=',
2090
+								$ignore_this_model_obj->ID(),
2091
+							),
2092
+						),
2093
+					));
2094
+				} else {
2095
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2096
+				}
2097
+				if ($related_model_objects) {
2098
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2099
+					$is_blocked = true;
2100
+				}
2101
+			}
2102
+		}
2103
+		return $is_blocked;
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2109
+	 * @param array $row_results_for_deleting
2110
+	 * @param bool  $allow_blocking
2111
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2112
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2113
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2114
+	 *                 deleted. Example:
2115
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2116
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2117
+	 *                 where each element is a group of columns and values that get deleted. Example:
2118
+	 *                      array(
2119
+	 *                          0 => array(
2120
+	 *                              'Term_Relationship.object_id' => 1
2121
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2122
+	 *                          ),
2123
+	 *                          1 => array(
2124
+	 *                              'Term_Relationship.object_id' => 1
2125
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2126
+	 *                          )
2127
+	 *                      )
2128
+	 * @throws EE_Error
2129
+	 */
2130
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2131
+	{
2132
+		$ids_to_delete_indexed_by_column = array();
2133
+		if ($this->has_primary_key_field()) {
2134
+			$primary_table = $this->_get_main_table();
2135
+			$other_tables = $this->_get_other_tables();
2136
+			$ids_to_delete_indexed_by_column = $query = array();
2137
+			foreach ($row_results_for_deleting as $item_to_delete) {
2138
+				//before we mark this item for deletion,
2139
+				//make sure there's no related entities blocking its deletion (if we're checking)
2140
+				if (
2141
+					$allow_blocking
2142
+					&& $this->delete_is_blocked_by_related_models(
2143
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2144
+					)
2145
+				) {
2146
+					continue;
2147
+				}
2148
+				//primary table deletes
2149
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2150
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2151
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2152
+				}
2153
+			}
2154
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2155
+			$fields = $this->get_combined_primary_key_fields();
2156
+			foreach ($row_results_for_deleting as $item_to_delete) {
2157
+				$ids_to_delete_indexed_by_column_for_row = array();
2158
+				foreach ($fields as $cpk_field) {
2159
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2160
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2161
+							$item_to_delete[$cpk_field->get_qualified_column()];
2162
+					}
2163
+				}
2164
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2165
+			}
2166
+		} else {
2167
+			//so there's no primary key and no combined key...
2168
+			//sorry, can't help you
2169
+			throw new EE_Error(
2170
+				sprintf(
2171
+					__(
2172
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2173
+						"event_espresso"
2174
+					), get_class($this)
2175
+				)
2176
+			);
2177
+		}    
2178
+		return $ids_to_delete_indexed_by_column;
2179
+	}
2180
+
2181
+
2182
+	/**
2183
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2184
+	 * the corresponding query_part for the query performing the delete.
2185
+	 *
2186
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2187
+	 * @return string
2188
+	 * @throws EE_Error
2189
+	 */
2190
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2191
+		$query_part = '';
2192
+		if (empty($ids_to_delete_indexed_by_column)) {
2193
+			return $query_part;
2194
+		} elseif ($this->has_primary_key_field()) {
2195
+			$query = array();
2196
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2197
+				//make sure we have unique $ids
2198
+				$ids = array_unique($ids);
2199
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2200
+			}
2201
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2202
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2203
+			$ways_to_identify_a_row = array();
2204
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2205
+				$values_for_each_combined_primary_key_for_a_row = array();
2206
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2207
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2208
+				}
2209
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2210
+			}
2211
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2212
+		}
2213
+		return $query_part;
2214
+	}
2215 2215
     
2216 2216
 
2217 2217
 
2218 2218
 
2219
-    /**
2220
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2221
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2222
-     * column
2223
-     *
2224
-     * @param array  $query_params   like EEM_Base::get_all's
2225
-     * @param string $field_to_count field on model to count by (not column name)
2226
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2227
-     *                               that by the setting $distinct to TRUE;
2228
-     * @return int
2229
-     * @throws EE_Error
2230
-     */
2231
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2232
-    {
2233
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2234
-        if ($field_to_count) {
2235
-            $field_obj = $this->field_settings_for($field_to_count);
2236
-            $column_to_count = $field_obj->get_qualified_column();
2237
-        } elseif ($this->has_primary_key_field()) {
2238
-            $pk_field_obj = $this->get_primary_key_field();
2239
-            $column_to_count = $pk_field_obj->get_qualified_column();
2240
-        } else {
2241
-            //there's no primary key
2242
-            //if we're counting distinct items, and there's no primary key,
2243
-            //we need to list out the columns for distinction;
2244
-            //otherwise we can just use star
2245
-            if ($distinct) {
2246
-                $columns_to_use = array();
2247
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2248
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2249
-                }
2250
-                $column_to_count = implode(',', $columns_to_use);
2251
-            } else {
2252
-                $column_to_count = '*';
2253
-            }
2254
-        }
2255
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2256
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2257
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2258
-    }
2259
-
2260
-
2261
-
2262
-    /**
2263
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2264
-     *
2265
-     * @param array  $query_params like EEM_Base::get_all
2266
-     * @param string $field_to_sum name of field (array key in $_fields array)
2267
-     * @return float
2268
-     * @throws EE_Error
2269
-     */
2270
-    public function sum($query_params, $field_to_sum = null)
2271
-    {
2272
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2273
-        if ($field_to_sum) {
2274
-            $field_obj = $this->field_settings_for($field_to_sum);
2275
-        } else {
2276
-            $field_obj = $this->get_primary_key_field();
2277
-        }
2278
-        $column_to_count = $field_obj->get_qualified_column();
2279
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2280
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2281
-        $data_type = $field_obj->get_wpdb_data_type();
2282
-        if ($data_type === '%d' || $data_type === '%s') {
2283
-            return (float)$return_value;
2284
-        }
2285
-        //must be %f
2286
-        return (float)$return_value;
2287
-    }
2288
-
2289
-
2290
-
2291
-    /**
2292
-     * Just calls the specified method on $wpdb with the given arguments
2293
-     * Consolidates a little extra error handling code
2294
-     *
2295
-     * @param string $wpdb_method
2296
-     * @param array  $arguments_to_provide
2297
-     * @throws EE_Error
2298
-     * @global wpdb  $wpdb
2299
-     * @return mixed
2300
-     */
2301
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2302
-    {
2303
-        //if we're in maintenance mode level 2, DON'T run any queries
2304
-        //because level 2 indicates the database needs updating and
2305
-        //is probably out of sync with the code
2306
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2307
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2308
-                "event_espresso")));
2309
-        }
2310
-        /** @type WPDB $wpdb */
2311
-        global $wpdb;
2312
-        if (! method_exists($wpdb, $wpdb_method)) {
2313
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2314
-                'event_espresso'), $wpdb_method));
2315
-        }
2316
-        if (WP_DEBUG) {
2317
-            $old_show_errors_value = $wpdb->show_errors;
2318
-            $wpdb->show_errors(false);
2319
-        }
2320
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2321
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2322
-        if (WP_DEBUG) {
2323
-            $wpdb->show_errors($old_show_errors_value);
2324
-            if (! empty($wpdb->last_error)) {
2325
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2326
-            }
2327
-            if ($result === false) {
2328
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2329
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2330
-            }
2331
-        } elseif ($result === false) {
2332
-            EE_Error::add_error(
2333
-                sprintf(
2334
-                    __('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2335
-                        'event_espresso'),
2336
-                    $wpdb_method,
2337
-                    var_export($arguments_to_provide, true),
2338
-                    $wpdb->last_error
2339
-                ),
2340
-                __FILE__,
2341
-                __FUNCTION__,
2342
-                __LINE__
2343
-            );
2344
-        }
2345
-        return $result;
2346
-    }
2347
-
2348
-
2349
-
2350
-    /**
2351
-     * Attempts to run the indicated WPDB method with the provided arguments,
2352
-     * and if there's an error tries to verify the DB is correct. Uses
2353
-     * the static property EEM_Base::$_db_verification_level to determine whether
2354
-     * we should try to fix the EE core db, the addons, or just give up
2355
-     *
2356
-     * @param string $wpdb_method
2357
-     * @param array  $arguments_to_provide
2358
-     * @return mixed
2359
-     */
2360
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2361
-    {
2362
-        /** @type WPDB $wpdb */
2363
-        global $wpdb;
2364
-        $wpdb->last_error = null;
2365
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2366
-        // was there an error running the query? but we don't care on new activations
2367
-        // (we're going to setup the DB anyway on new activations)
2368
-        if (($result === false || ! empty($wpdb->last_error))
2369
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2370
-        ) {
2371
-            switch (EEM_Base::$_db_verification_level) {
2372
-                case EEM_Base::db_verified_none :
2373
-                    // let's double-check core's DB
2374
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2375
-                    break;
2376
-                case EEM_Base::db_verified_core :
2377
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2378
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2379
-                    break;
2380
-                case EEM_Base::db_verified_addons :
2381
-                    // ummmm... you in trouble
2382
-                    return $result;
2383
-                    break;
2384
-            }
2385
-            if (! empty($error_message)) {
2386
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387
-                trigger_error($error_message);
2388
-            }
2389
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
-        }
2391
-        return $result;
2392
-    }
2393
-
2394
-
2395
-
2396
-    /**
2397
-     * Verifies the EE core database is up-to-date and records that we've done it on
2398
-     * EEM_Base::$_db_verification_level
2399
-     *
2400
-     * @param string $wpdb_method
2401
-     * @param array  $arguments_to_provide
2402
-     * @return string
2403
-     */
2404
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2405
-    {
2406
-        /** @type WPDB $wpdb */
2407
-        global $wpdb;
2408
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2409
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2410
-        $error_message = sprintf(
2411
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2412
-                'event_espresso'),
2413
-            $wpdb->last_error,
2414
-            $wpdb_method,
2415
-            wp_json_encode($arguments_to_provide)
2416
-        );
2417
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2418
-        return $error_message;
2419
-    }
2420
-
2421
-
2422
-
2423
-    /**
2424
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2425
-     * EEM_Base::$_db_verification_level
2426
-     *
2427
-     * @param $wpdb_method
2428
-     * @param $arguments_to_provide
2429
-     * @return string
2430
-     */
2431
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2432
-    {
2433
-        /** @type WPDB $wpdb */
2434
-        global $wpdb;
2435
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2436
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2437
-        $error_message = sprintf(
2438
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2439
-                'event_espresso'),
2440
-            $wpdb->last_error,
2441
-            $wpdb_method,
2442
-            wp_json_encode($arguments_to_provide)
2443
-        );
2444
-        EE_System::instance()->initialize_addons();
2445
-        return $error_message;
2446
-    }
2447
-
2448
-
2449
-
2450
-    /**
2451
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2452
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2453
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2454
-     * ..."
2455
-     *
2456
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2457
-     * @return string
2458
-     */
2459
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2460
-    {
2461
-        return " FROM " . $model_query_info->get_full_join_sql() .
2462
-               $model_query_info->get_where_sql() .
2463
-               $model_query_info->get_group_by_sql() .
2464
-               $model_query_info->get_having_sql() .
2465
-               $model_query_info->get_order_by_sql() .
2466
-               $model_query_info->get_limit_sql();
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * Set to easily debug the next X queries ran from this model.
2473
-     *
2474
-     * @param int $count
2475
-     */
2476
-    public function show_next_x_db_queries($count = 1)
2477
-    {
2478
-        $this->_show_next_x_db_queries = $count;
2479
-    }
2480
-
2481
-
2482
-
2483
-    /**
2484
-     * @param $sql_query
2485
-     */
2486
-    public function show_db_query_if_previously_requested($sql_query)
2487
-    {
2488
-        if ($this->_show_next_x_db_queries > 0) {
2489
-            echo $sql_query;
2490
-            $this->_show_next_x_db_queries--;
2491
-        }
2492
-    }
2493
-
2494
-
2495
-
2496
-    /**
2497
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2498
-     * There are the 3 cases:
2499
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2500
-     * $otherModelObject has no ID, it is first saved.
2501
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2502
-     * has no ID, it is first saved.
2503
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2504
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2505
-     * join table
2506
-     *
2507
-     * @param        EE_Base_Class                     /int $thisModelObject
2508
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2509
-     * @param string $relationName                     , key in EEM_Base::_relations
2510
-     *                                                 an attendee to a group, you also want to specify which role they
2511
-     *                                                 will have in that group. So you would use this parameter to
2512
-     *                                                 specify array('role-column-name'=>'role-id')
2513
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2514
-     *                                                 to for relation to methods that allow you to further specify
2515
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2516
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2517
-     *                                                 because these will be inserted in any new rows created as well.
2518
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2519
-     * @throws EE_Error
2520
-     */
2521
-    public function add_relationship_to(
2522
-        $id_or_obj,
2523
-        $other_model_id_or_obj,
2524
-        $relationName,
2525
-        $extra_join_model_fields_n_values = array()
2526
-    ) {
2527
-        $relation_obj = $this->related_settings_for($relationName);
2528
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2529
-    }
2530
-
2531
-
2532
-
2533
-    /**
2534
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2535
-     * There are the 3 cases:
2536
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2537
-     * error
2538
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2539
-     * an error
2540
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2541
-     *
2542
-     * @param        EE_Base_Class /int $id_or_obj
2543
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2544
-     * @param string $relationName key in EEM_Base::_relations
2545
-     * @return boolean of success
2546
-     * @throws EE_Error
2547
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2548
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2549
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2550
-     *                             because these will be inserted in any new rows created as well.
2551
-     */
2552
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2553
-    {
2554
-        $relation_obj = $this->related_settings_for($relationName);
2555
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2556
-    }
2557
-
2558
-
2559
-
2560
-    /**
2561
-     * @param mixed           $id_or_obj
2562
-     * @param string          $relationName
2563
-     * @param array           $where_query_params
2564
-     * @param EE_Base_Class[] objects to which relations were removed
2565
-     * @return \EE_Base_Class[]
2566
-     * @throws EE_Error
2567
-     */
2568
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2569
-    {
2570
-        $relation_obj = $this->related_settings_for($relationName);
2571
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2572
-    }
2573
-
2574
-
2575
-
2576
-    /**
2577
-     * Gets all the related items of the specified $model_name, using $query_params.
2578
-     * Note: by default, we remove the "default query params"
2579
-     * because we want to get even deleted items etc.
2580
-     *
2581
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2582
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2583
-     * @param array  $query_params like EEM_Base::get_all
2584
-     * @return EE_Base_Class[]
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2588
-    {
2589
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2590
-        $relation_settings = $this->related_settings_for($model_name);
2591
-        return $relation_settings->get_all_related($model_obj, $query_params);
2592
-    }
2593
-
2594
-
2595
-
2596
-    /**
2597
-     * Deletes all the model objects across the relation indicated by $model_name
2598
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2599
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2600
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2601
-     *
2602
-     * @param EE_Base_Class|int|string $id_or_obj
2603
-     * @param string                   $model_name
2604
-     * @param array                    $query_params
2605
-     * @return int how many deleted
2606
-     * @throws EE_Error
2607
-     */
2608
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2609
-    {
2610
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2611
-        $relation_settings = $this->related_settings_for($model_name);
2612
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Hard deletes all the model objects across the relation indicated by $model_name
2619
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2620
-     * the model objects can't be hard deleted because of blocking related model objects,
2621
-     * just does a soft-delete on them instead.
2622
-     *
2623
-     * @param EE_Base_Class|int|string $id_or_obj
2624
-     * @param string                   $model_name
2625
-     * @param array                    $query_params
2626
-     * @return int how many deleted
2627
-     * @throws EE_Error
2628
-     */
2629
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2630
-    {
2631
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2632
-        $relation_settings = $this->related_settings_for($model_name);
2633
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2640
-     * unless otherwise specified in the $query_params
2641
-     *
2642
-     * @param        int             /EE_Base_Class $id_or_obj
2643
-     * @param string $model_name     like 'Event', or 'Registration'
2644
-     * @param array  $query_params   like EEM_Base::get_all's
2645
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2646
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2647
-     *                               that by the setting $distinct to TRUE;
2648
-     * @return int
2649
-     * @throws EE_Error
2650
-     */
2651
-    public function count_related(
2652
-        $id_or_obj,
2653
-        $model_name,
2654
-        $query_params = array(),
2655
-        $field_to_count = null,
2656
-        $distinct = false
2657
-    ) {
2658
-        $related_model = $this->get_related_model_obj($model_name);
2659
-        //we're just going to use the query params on the related model's normal get_all query,
2660
-        //except add a condition to say to match the current mod
2661
-        if (! isset($query_params['default_where_conditions'])) {
2662
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2663
-        }
2664
-        $this_model_name = $this->get_this_model_name();
2665
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2666
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2667
-        return $related_model->count($query_params, $field_to_count, $distinct);
2668
-    }
2669
-
2670
-
2671
-
2672
-    /**
2673
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2674
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2675
-     *
2676
-     * @param        int           /EE_Base_Class $id_or_obj
2677
-     * @param string $model_name   like 'Event', or 'Registration'
2678
-     * @param array  $query_params like EEM_Base::get_all's
2679
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2680
-     * @return float
2681
-     * @throws EE_Error
2682
-     */
2683
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2684
-    {
2685
-        $related_model = $this->get_related_model_obj($model_name);
2686
-        if (! is_array($query_params)) {
2687
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2688
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2689
-                    gettype($query_params)), '4.6.0');
2690
-            $query_params = array();
2691
-        }
2692
-        //we're just going to use the query params on the related model's normal get_all query,
2693
-        //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2695
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
-        }
2697
-        $this_model_name = $this->get_this_model_name();
2698
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
-        return $related_model->sum($query_params, $field_to_sum);
2701
-    }
2702
-
2703
-
2704
-
2705
-    /**
2706
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2707
-     * $modelObject
2708
-     *
2709
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2710
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2711
-     * @param array               $query_params     like EEM_Base::get_all's
2712
-     * @return EE_Base_Class
2713
-     * @throws EE_Error
2714
-     */
2715
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2716
-    {
2717
-        $query_params['limit'] = 1;
2718
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2719
-        if ($results) {
2720
-            return array_shift($results);
2721
-        }
2722
-        return null;
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2729
-     *
2730
-     * @return string
2731
-     */
2732
-    public function get_this_model_name()
2733
-    {
2734
-        return str_replace("EEM_", "", get_class($this));
2735
-    }
2736
-
2737
-
2738
-
2739
-    /**
2740
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2741
-     *
2742
-     * @return EE_Any_Foreign_Model_Name_Field
2743
-     * @throws EE_Error
2744
-     */
2745
-    public function get_field_containing_related_model_name()
2746
-    {
2747
-        foreach ($this->field_settings(true) as $field) {
2748
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2749
-                $field_with_model_name = $field;
2750
-            }
2751
-        }
2752
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2753
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2754
-                $this->get_this_model_name()));
2755
-        }
2756
-        return $field_with_model_name;
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Inserts a new entry into the database, for each table.
2763
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2764
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2765
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2766
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2767
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2768
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2769
-     *
2770
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2771
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2772
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2773
-     *                              of EEM_Base)
2774
-     * @return int new primary key on main table that got inserted
2775
-     * @throws EE_Error
2776
-     */
2777
-    public function insert($field_n_values)
2778
-    {
2779
-        /**
2780
-         * Filters the fields and their values before inserting an item using the models
2781
-         *
2782
-         * @param array    $fields_n_values keys are the fields and values are their new values
2783
-         * @param EEM_Base $model           the model used
2784
-         */
2785
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2786
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2787
-            $main_table = $this->_get_main_table();
2788
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2789
-            if ($new_id !== false) {
2790
-                foreach ($this->_get_other_tables() as $other_table) {
2791
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2792
-                }
2793
-            }
2794
-            /**
2795
-             * Done just after attempting to insert a new model object
2796
-             *
2797
-             * @param EEM_Base   $model           used
2798
-             * @param array      $fields_n_values fields and their values
2799
-             * @param int|string the              ID of the newly-inserted model object
2800
-             */
2801
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2802
-            return $new_id;
2803
-        }
2804
-        return false;
2805
-    }
2806
-
2807
-
2808
-
2809
-    /**
2810
-     * Checks that the result would satisfy the unique indexes on this model
2811
-     *
2812
-     * @param array  $field_n_values
2813
-     * @param string $action
2814
-     * @return boolean
2815
-     * @throws EE_Error
2816
-     */
2817
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2818
-    {
2819
-        foreach ($this->unique_indexes() as $index_name => $index) {
2820
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2821
-            if ($this->exists(array($uniqueness_where_params))) {
2822
-                EE_Error::add_error(
2823
-                    sprintf(
2824
-                        __(
2825
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2826
-                            "event_espresso"
2827
-                        ),
2828
-                        $action,
2829
-                        $this->_get_class_name(),
2830
-                        $index_name,
2831
-                        implode(",", $index->field_names()),
2832
-                        http_build_query($uniqueness_where_params)
2833
-                    ),
2834
-                    __FILE__,
2835
-                    __FUNCTION__,
2836
-                    __LINE__
2837
-                );
2838
-                return false;
2839
-            }
2840
-        }
2841
-        return true;
2842
-    }
2843
-
2844
-
2845
-
2846
-    /**
2847
-     * Checks the database for an item that conflicts (ie, if this item were
2848
-     * saved to the DB would break some uniqueness requirement, like a primary key
2849
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2850
-     * can be either an EE_Base_Class or an array of fields n values
2851
-     *
2852
-     * @param EE_Base_Class|array $obj_or_fields_array
2853
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2854
-     *                                                 when looking for conflicts
2855
-     *                                                 (ie, if false, we ignore the model object's primary key
2856
-     *                                                 when finding "conflicts". If true, it's also considered).
2857
-     *                                                 Only works for INT primary key,
2858
-     *                                                 STRING primary keys cannot be ignored
2859
-     * @throws EE_Error
2860
-     * @return EE_Base_Class|array
2861
-     */
2862
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2863
-    {
2864
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2865
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2866
-        } elseif (is_array($obj_or_fields_array)) {
2867
-            $fields_n_values = $obj_or_fields_array;
2868
-        } else {
2869
-            throw new EE_Error(
2870
-                sprintf(
2871
-                    __(
2872
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2873
-                        "event_espresso"
2874
-                    ),
2875
-                    get_class($this),
2876
-                    $obj_or_fields_array
2877
-                )
2878
-            );
2879
-        }
2880
-        $query_params = array();
2881
-        if ($this->has_primary_key_field()
2882
-            && ($include_primary_key
2883
-                || $this->get_primary_key_field()
2884
-                   instanceof
2885
-                   EE_Primary_Key_String_Field)
2886
-            && isset($fields_n_values[$this->primary_key_name()])
2887
-        ) {
2888
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2889
-        }
2890
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2891
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2892
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2893
-        }
2894
-        //if there is nothing to base this search on, then we shouldn't find anything
2895
-        if (empty($query_params)) {
2896
-            return array();
2897
-        }
2898
-        return $this->get_one($query_params);
2899
-    }
2900
-
2901
-
2902
-
2903
-    /**
2904
-     * Like count, but is optimized and returns a boolean instead of an int
2905
-     *
2906
-     * @param array $query_params
2907
-     * @return boolean
2908
-     * @throws EE_Error
2909
-     */
2910
-    public function exists($query_params)
2911
-    {
2912
-        $query_params['limit'] = 1;
2913
-        return $this->count($query_params) > 0;
2914
-    }
2915
-
2916
-
2917
-
2918
-    /**
2919
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2920
-     *
2921
-     * @param int|string $id
2922
-     * @return boolean
2923
-     * @throws EE_Error
2924
-     */
2925
-    public function exists_by_ID($id)
2926
-    {
2927
-        return $this->exists(
2928
-            array(
2929
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2930
-                array(
2931
-                    $this->primary_key_name() => $id,
2932
-                ),
2933
-            )
2934
-        );
2935
-    }
2936
-
2937
-
2938
-
2939
-    /**
2940
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2941
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2942
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2943
-     * on the main table)
2944
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2945
-     * cases where we want to call it directly rather than via insert().
2946
-     *
2947
-     * @access   protected
2948
-     * @param EE_Table_Base $table
2949
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2950
-     *                                       float
2951
-     * @param int           $new_id          for now we assume only int keys
2952
-     * @throws EE_Error
2953
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2954
-     * @return int ID of new row inserted, or FALSE on failure
2955
-     */
2956
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2957
-    {
2958
-        global $wpdb;
2959
-        $insertion_col_n_values = array();
2960
-        $format_for_insertion = array();
2961
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2962
-        foreach ($fields_on_table as $field_name => $field_obj) {
2963
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2964
-            if ($field_obj->is_auto_increment()) {
2965
-                continue;
2966
-            }
2967
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2968
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2969
-            if ($prepared_value !== null) {
2970
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2971
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2972
-            }
2973
-        }
2974
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2975
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2976
-            //so add the fk to the main table as a column
2977
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2978
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2979
-        }
2980
-        //insert the new entry
2981
-        $result = $this->_do_wpdb_query('insert',
2982
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2983
-        if ($result === false) {
2984
-            return false;
2985
-        }
2986
-        //ok, now what do we return for the ID of the newly-inserted thing?
2987
-        if ($this->has_primary_key_field()) {
2988
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2989
-                return $wpdb->insert_id;
2990
-            }
2991
-            //it's not an auto-increment primary key, so
2992
-            //it must have been supplied
2993
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2994
-        }
2995
-        //we can't return a  primary key because there is none. instead return
2996
-        //a unique string indicating this model
2997
-        return $this->get_index_primary_key_string($fields_n_values);
2998
-    }
2999
-
3000
-
3001
-
3002
-    /**
3003
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3004
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3005
-     * and there is no default, we pass it along. WPDB will take care of it)
3006
-     *
3007
-     * @param EE_Model_Field_Base $field_obj
3008
-     * @param array               $fields_n_values
3009
-     * @return mixed string|int|float depending on what the table column will be expecting
3010
-     * @throws EE_Error
3011
-     */
3012
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3013
-    {
3014
-        //if this field doesn't allow nullable, don't allow it
3015
-        if (
3016
-            ! $field_obj->is_nullable()
3017
-            && (
3018
-                ! isset($fields_n_values[$field_obj->get_name()])
3019
-                || $fields_n_values[$field_obj->get_name()] === null
3020
-            )
3021
-        ) {
3022
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3023
-        }
3024
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3025
-            ? $fields_n_values[$field_obj->get_name()]
3026
-            : null;
3027
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3028
-    }
3029
-
3030
-
3031
-
3032
-    /**
3033
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3034
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3035
-     * the field's prepare_for_set() method.
3036
-     *
3037
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3038
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3039
-     *                                   top of file)
3040
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3041
-     *                                   $value is a custom selection
3042
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3043
-     */
3044
-    private function _prepare_value_for_use_in_db($value, $field)
3045
-    {
3046
-        if ($field && $field instanceof EE_Model_Field_Base) {
3047
-            switch ($this->_values_already_prepared_by_model_object) {
3048
-                /** @noinspection PhpMissingBreakStatementInspection */
3049
-                case self::not_prepared_by_model_object:
3050
-                    $value = $field->prepare_for_set($value);
3051
-                //purposefully left out "return"
3052
-                case self::prepared_by_model_object:
3053
-                    /** @noinspection SuspiciousAssignmentsInspection */
3054
-                    $value = $field->prepare_for_use_in_db($value);
3055
-                case self::prepared_for_use_in_db:
3056
-                    //leave the value alone
3057
-            }
3058
-            return $value;
3059
-        }
3060
-        return $value;
3061
-    }
3062
-
3063
-
3064
-
3065
-    /**
3066
-     * Returns the main table on this model
3067
-     *
3068
-     * @return EE_Primary_Table
3069
-     * @throws EE_Error
3070
-     */
3071
-    protected function _get_main_table()
3072
-    {
3073
-        foreach ($this->_tables as $table) {
3074
-            if ($table instanceof EE_Primary_Table) {
3075
-                return $table;
3076
-            }
3077
-        }
3078
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3079
-            'event_espresso'), get_class($this)));
3080
-    }
3081
-
3082
-
3083
-
3084
-    /**
3085
-     * table
3086
-     * returns EE_Primary_Table table name
3087
-     *
3088
-     * @return string
3089
-     * @throws EE_Error
3090
-     */
3091
-    public function table()
3092
-    {
3093
-        return $this->_get_main_table()->get_table_name();
3094
-    }
3095
-
3096
-
3097
-
3098
-    /**
3099
-     * table
3100
-     * returns first EE_Secondary_Table table name
3101
-     *
3102
-     * @return string
3103
-     */
3104
-    public function second_table()
3105
-    {
3106
-        // grab second table from tables array
3107
-        $second_table = end($this->_tables);
3108
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3109
-    }
3110
-
3111
-
3112
-
3113
-    /**
3114
-     * get_table_obj_by_alias
3115
-     * returns table name given it's alias
3116
-     *
3117
-     * @param string $table_alias
3118
-     * @return EE_Primary_Table | EE_Secondary_Table
3119
-     */
3120
-    public function get_table_obj_by_alias($table_alias = '')
3121
-    {
3122
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3123
-    }
3124
-
3125
-
3126
-
3127
-    /**
3128
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3129
-     *
3130
-     * @return EE_Secondary_Table[]
3131
-     */
3132
-    protected function _get_other_tables()
3133
-    {
3134
-        $other_tables = array();
3135
-        foreach ($this->_tables as $table_alias => $table) {
3136
-            if ($table instanceof EE_Secondary_Table) {
3137
-                $other_tables[$table_alias] = $table;
3138
-            }
3139
-        }
3140
-        return $other_tables;
3141
-    }
3142
-
3143
-
3144
-
3145
-    /**
3146
-     * Finds all the fields that correspond to the given table
3147
-     *
3148
-     * @param string $table_alias , array key in EEM_Base::_tables
3149
-     * @return EE_Model_Field_Base[]
3150
-     */
3151
-    public function _get_fields_for_table($table_alias)
3152
-    {
3153
-        return $this->_fields[$table_alias];
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Recurses through all the where parameters, and finds all the related models we'll need
3160
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3161
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3162
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3163
-     * related Registration, Transaction, and Payment models.
3164
-     *
3165
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3166
-     * @return EE_Model_Query_Info_Carrier
3167
-     * @throws EE_Error
3168
-     */
3169
-    public function _extract_related_models_from_query($query_params)
3170
-    {
3171
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3172
-        if (array_key_exists(0, $query_params)) {
3173
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3174
-        }
3175
-        if (array_key_exists('group_by', $query_params)) {
3176
-            if (is_array($query_params['group_by'])) {
3177
-                $this->_extract_related_models_from_sub_params_array_values(
3178
-                    $query_params['group_by'],
3179
-                    $query_info_carrier,
3180
-                    'group_by'
3181
-                );
3182
-            } elseif (! empty ($query_params['group_by'])) {
3183
-                $this->_extract_related_model_info_from_query_param(
3184
-                    $query_params['group_by'],
3185
-                    $query_info_carrier,
3186
-                    'group_by'
3187
-                );
3188
-            }
3189
-        }
3190
-        if (array_key_exists('having', $query_params)) {
3191
-            $this->_extract_related_models_from_sub_params_array_keys(
3192
-                $query_params[0],
3193
-                $query_info_carrier,
3194
-                'having'
3195
-            );
3196
-        }
3197
-        if (array_key_exists('order_by', $query_params)) {
3198
-            if (is_array($query_params['order_by'])) {
3199
-                $this->_extract_related_models_from_sub_params_array_keys(
3200
-                    $query_params['order_by'],
3201
-                    $query_info_carrier,
3202
-                    'order_by'
3203
-                );
3204
-            } elseif (! empty($query_params['order_by'])) {
3205
-                $this->_extract_related_model_info_from_query_param(
3206
-                    $query_params['order_by'],
3207
-                    $query_info_carrier,
3208
-                    'order_by'
3209
-                );
3210
-            }
3211
-        }
3212
-        if (array_key_exists('force_join', $query_params)) {
3213
-            $this->_extract_related_models_from_sub_params_array_values(
3214
-                $query_params['force_join'],
3215
-                $query_info_carrier,
3216
-                'force_join'
3217
-            );
3218
-        }
3219
-        return $query_info_carrier;
3220
-    }
3221
-
3222
-
3223
-
3224
-    /**
3225
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3226
-     *
3227
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3228
-     *                                                      $query_params['having']
3229
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3230
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3231
-     * @throws EE_Error
3232
-     * @return \EE_Model_Query_Info_Carrier
3233
-     */
3234
-    private function _extract_related_models_from_sub_params_array_keys(
3235
-        $sub_query_params,
3236
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3237
-        $query_param_type
3238
-    ) {
3239
-        if (! empty($sub_query_params)) {
3240
-            $sub_query_params = (array)$sub_query_params;
3241
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3242
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3243
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3244
-                    $query_param_type);
3245
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3246
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3247
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3248
-                //of array('Registration.TXN_ID'=>23)
3249
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3250
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3251
-                    if (! is_array($possibly_array_of_params)) {
3252
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3253
-                            "event_espresso"),
3254
-                            $param, $possibly_array_of_params));
3255
-                    }
3256
-                    $this->_extract_related_models_from_sub_params_array_keys(
3257
-                        $possibly_array_of_params,
3258
-                        $model_query_info_carrier, $query_param_type
3259
-                    );
3260
-                } elseif ($query_param_type === 0 //ie WHERE
3261
-                          && is_array($possibly_array_of_params)
3262
-                          && isset($possibly_array_of_params[2])
3263
-                          && $possibly_array_of_params[2] == true
3264
-                ) {
3265
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3266
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3267
-                    //from which we should extract query parameters!
3268
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3269
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3270
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3271
-                    }
3272
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3273
-                        $model_query_info_carrier, $query_param_type);
3274
-                }
3275
-            }
3276
-        }
3277
-        return $model_query_info_carrier;
3278
-    }
3279
-
3280
-
3281
-
3282
-    /**
3283
-     * For extracting related models from forced_joins, where the array values contain the info about what
3284
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3285
-     *
3286
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3287
-     *                                                      $query_params['having']
3288
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3289
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3290
-     * @throws EE_Error
3291
-     * @return \EE_Model_Query_Info_Carrier
3292
-     */
3293
-    private function _extract_related_models_from_sub_params_array_values(
3294
-        $sub_query_params,
3295
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3296
-        $query_param_type
3297
-    ) {
3298
-        if (! empty($sub_query_params)) {
3299
-            if (! is_array($sub_query_params)) {
3300
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3301
-                    $sub_query_params));
3302
-            }
3303
-            foreach ($sub_query_params as $param) {
3304
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3305
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3306
-                    $query_param_type);
3307
-            }
3308
-        }
3309
-        return $model_query_info_carrier;
3310
-    }
3311
-
3312
-
3313
-
3314
-    /**
3315
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3316
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3317
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3318
-     * but use them in a different order. Eg, we need to know what models we are querying
3319
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3320
-     * other models before we can finalize the where clause SQL.
3321
-     *
3322
-     * @param array $query_params
3323
-     * @throws EE_Error
3324
-     * @return EE_Model_Query_Info_Carrier
3325
-     */
3326
-    public function _create_model_query_info_carrier($query_params)
3327
-    {
3328
-        if (! is_array($query_params)) {
3329
-            EE_Error::doing_it_wrong(
3330
-                'EEM_Base::_create_model_query_info_carrier',
3331
-                sprintf(
3332
-                    __(
3333
-                        '$query_params should be an array, you passed a variable of type %s',
3334
-                        'event_espresso'
3335
-                    ),
3336
-                    gettype($query_params)
3337
-                ),
3338
-                '4.6.0'
3339
-            );
3340
-            $query_params = array();
3341
-        }
3342
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3343
-        //first check if we should alter the query to account for caps or not
3344
-        //because the caps might require us to do extra joins
3345
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3346
-            $query_params[0] = $where_query_params = array_replace_recursive(
3347
-                $where_query_params,
3348
-                $this->caps_where_conditions(
3349
-                    $query_params['caps']
3350
-                )
3351
-            );
3352
-        }
3353
-        $query_object = $this->_extract_related_models_from_query($query_params);
3354
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3355
-        foreach ($where_query_params as $key => $value) {
3356
-            if (is_int($key)) {
3357
-                throw new EE_Error(
3358
-                    sprintf(
3359
-                        __(
3360
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3361
-                            "event_espresso"
3362
-                        ),
3363
-                        $key,
3364
-                        var_export($value, true),
3365
-                        var_export($query_params, true),
3366
-                        get_class($this)
3367
-                    )
3368
-                );
3369
-            }
3370
-        }
3371
-        if (
3372
-            array_key_exists('default_where_conditions', $query_params)
3373
-            && ! empty($query_params['default_where_conditions'])
3374
-        ) {
3375
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3376
-        } else {
3377
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3378
-        }
3379
-        $where_query_params = array_merge(
3380
-            $this->_get_default_where_conditions_for_models_in_query(
3381
-                $query_object,
3382
-                $use_default_where_conditions,
3383
-                $where_query_params
3384
-            ),
3385
-            $where_query_params
3386
-        );
3387
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3388
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3389
-        // So we need to setup a subquery and use that for the main join.
3390
-        // Note for now this only works on the primary table for the model.
3391
-        // So for instance, you could set the limit array like this:
3392
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3393
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3394
-            $query_object->set_main_model_join_sql(
3395
-                $this->_construct_limit_join_select(
3396
-                    $query_params['on_join_limit'][0],
3397
-                    $query_params['on_join_limit'][1]
3398
-                )
3399
-            );
3400
-        }
3401
-        //set limit
3402
-        if (array_key_exists('limit', $query_params)) {
3403
-            if (is_array($query_params['limit'])) {
3404
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3405
-                    $e = sprintf(
3406
-                        __(
3407
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3408
-                            "event_espresso"
3409
-                        ),
3410
-                        http_build_query($query_params['limit'])
3411
-                    );
3412
-                    throw new EE_Error($e . "|" . $e);
3413
-                }
3414
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3415
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3416
-            } elseif (! empty ($query_params['limit'])) {
3417
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3418
-            }
3419
-        }
3420
-        //set order by
3421
-        if (array_key_exists('order_by', $query_params)) {
3422
-            if (is_array($query_params['order_by'])) {
3423
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3424
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3425
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3426
-                if (array_key_exists('order', $query_params)) {
3427
-                    throw new EE_Error(
3428
-                        sprintf(
3429
-                            __(
3430
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3431
-                                "event_espresso"
3432
-                            ),
3433
-                            get_class($this),
3434
-                            implode(", ", array_keys($query_params['order_by'])),
3435
-                            implode(", ", $query_params['order_by']),
3436
-                            $query_params['order']
3437
-                        )
3438
-                    );
3439
-                }
3440
-                $this->_extract_related_models_from_sub_params_array_keys(
3441
-                    $query_params['order_by'],
3442
-                    $query_object,
3443
-                    'order_by'
3444
-                );
3445
-                //assume it's an array of fields to order by
3446
-                $order_array = array();
3447
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3448
-                    $order = $this->_extract_order($order);
3449
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3450
-                }
3451
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3452
-            } elseif (! empty ($query_params['order_by'])) {
3453
-                $this->_extract_related_model_info_from_query_param(
3454
-                    $query_params['order_by'],
3455
-                    $query_object,
3456
-                    'order',
3457
-                    $query_params['order_by']
3458
-                );
3459
-                $order = isset($query_params['order'])
3460
-                    ? $this->_extract_order($query_params['order'])
3461
-                    : 'DESC';
3462
-                $query_object->set_order_by_sql(
3463
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3464
-                );
3465
-            }
3466
-        }
3467
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3468
-        if (! array_key_exists('order_by', $query_params)
3469
-            && array_key_exists('order', $query_params)
3470
-            && ! empty($query_params['order'])
3471
-        ) {
3472
-            $pk_field = $this->get_primary_key_field();
3473
-            $order = $this->_extract_order($query_params['order']);
3474
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3475
-        }
3476
-        //set group by
3477
-        if (array_key_exists('group_by', $query_params)) {
3478
-            if (is_array($query_params['group_by'])) {
3479
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3480
-                $group_by_array = array();
3481
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3482
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3483
-                }
3484
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3485
-            } elseif (! empty ($query_params['group_by'])) {
3486
-                $query_object->set_group_by_sql(
3487
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3488
-                );
3489
-            }
3490
-        }
3491
-        //set having
3492
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3493
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3494
-        }
3495
-        //now, just verify they didn't pass anything wack
3496
-        foreach ($query_params as $query_key => $query_value) {
3497
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3498
-                throw new EE_Error(
3499
-                    sprintf(
3500
-                        __(
3501
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3502
-                            'event_espresso'
3503
-                        ),
3504
-                        $query_key,
3505
-                        get_class($this),
3506
-                        //						print_r( $this->_allowed_query_params, TRUE )
3507
-                        implode(',', $this->_allowed_query_params)
3508
-                    )
3509
-                );
3510
-            }
3511
-        }
3512
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3513
-        if (empty($main_model_join_sql)) {
3514
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3515
-        }
3516
-        return $query_object;
3517
-    }
3518
-
3519
-
3520
-
3521
-    /**
3522
-     * Gets the where conditions that should be imposed on the query based on the
3523
-     * context (eg reading frontend, backend, edit or delete).
3524
-     *
3525
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3526
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3527
-     * @throws EE_Error
3528
-     */
3529
-    public function caps_where_conditions($context = self::caps_read)
3530
-    {
3531
-        EEM_Base::verify_is_valid_cap_context($context);
3532
-        $cap_where_conditions = array();
3533
-        $cap_restrictions = $this->caps_missing($context);
3534
-        /**
3535
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3536
-         */
3537
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3538
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3539
-                $restriction_if_no_cap->get_default_where_conditions());
3540
-        }
3541
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3542
-            $cap_restrictions);
3543
-    }
3544
-
3545
-
3546
-
3547
-    /**
3548
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3549
-     * otherwise throws an exception
3550
-     *
3551
-     * @param string $should_be_order_string
3552
-     * @return string either ASC, asc, DESC or desc
3553
-     * @throws EE_Error
3554
-     */
3555
-    private function _extract_order($should_be_order_string)
3556
-    {
3557
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3558
-            return $should_be_order_string;
3559
-        }
3560
-        throw new EE_Error(
3561
-            sprintf(
3562
-                __(
3563
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3564
-                    "event_espresso"
3565
-                ), get_class($this), $should_be_order_string
3566
-            )
3567
-        );
3568
-    }
3569
-
3570
-
3571
-
3572
-    /**
3573
-     * Looks at all the models which are included in this query, and asks each
3574
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3575
-     * so they can be merged
3576
-     *
3577
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3578
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3579
-     *                                                                  'none' means NO default where conditions will
3580
-     *                                                                  be used AT ALL during this query.
3581
-     *                                                                  'other_models_only' means default where
3582
-     *                                                                  conditions from other models will be used, but
3583
-     *                                                                  not for this primary model. 'all', the default,
3584
-     *                                                                  means default where conditions will apply as
3585
-     *                                                                  normal
3586
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3587
-     * @throws EE_Error
3588
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3589
-     */
3590
-    private function _get_default_where_conditions_for_models_in_query(
3591
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3592
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3593
-        $where_query_params = array()
3594
-    ) {
3595
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3596
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3597
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3598
-                "event_espresso"), $use_default_where_conditions,
3599
-                implode(", ", $allowed_used_default_where_conditions_values)));
3600
-        }
3601
-        $universal_query_params = array();
3602
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3603
-            $universal_query_params = $this->_get_default_where_conditions();
3604
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3605
-            $universal_query_params = $this->_get_minimum_where_conditions();
3606
-        }
3607
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3608
-            $related_model = $this->get_related_model_obj($model_name);
3609
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3610
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3611
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3612
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3613
-            } else {
3614
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3615
-                continue;
3616
-            }
3617
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3618
-                $related_model_universal_where_params,
3619
-                $where_query_params,
3620
-                $related_model,
3621
-                $model_relation_path
3622
-            );
3623
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3624
-                $universal_query_params,
3625
-                $overrides
3626
-            );
3627
-        }
3628
-        return $universal_query_params;
3629
-    }
3630
-
3631
-
3632
-
3633
-    /**
3634
-     * Determines whether or not we should use default where conditions for the model in question
3635
-     * (this model, or other related models).
3636
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3637
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3638
-     * We should use default where conditions on related models when they requested to use default where conditions
3639
-     * on all models, or specifically just on other related models
3640
-     * @param      $default_where_conditions_value
3641
-     * @param bool $for_this_model false means this is for OTHER related models
3642
-     * @return bool
3643
-     */
3644
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3645
-    {
3646
-        return (
3647
-                   $for_this_model
3648
-                   && in_array(
3649
-                       $default_where_conditions_value,
3650
-                       array(
3651
-                           EEM_Base::default_where_conditions_all,
3652
-                           EEM_Base::default_where_conditions_this_only,
3653
-                           EEM_Base::default_where_conditions_minimum_others,
3654
-                       ),
3655
-                       true
3656
-                   )
3657
-               )
3658
-               || (
3659
-                   ! $for_this_model
3660
-                   && in_array(
3661
-                       $default_where_conditions_value,
3662
-                       array(
3663
-                           EEM_Base::default_where_conditions_all,
3664
-                           EEM_Base::default_where_conditions_others_only,
3665
-                       ),
3666
-                       true
3667
-                   )
3668
-               );
3669
-    }
3670
-
3671
-    /**
3672
-     * Determines whether or not we should use default minimum conditions for the model in question
3673
-     * (this model, or other related models).
3674
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3675
-     * where conditions.
3676
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3677
-     * on this model or others
3678
-     * @param      $default_where_conditions_value
3679
-     * @param bool $for_this_model false means this is for OTHER related models
3680
-     * @return bool
3681
-     */
3682
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3683
-    {
3684
-        return (
3685
-                   $for_this_model
3686
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3687
-               )
3688
-               || (
3689
-                   ! $for_this_model
3690
-                   && in_array(
3691
-                       $default_where_conditions_value,
3692
-                       array(
3693
-                           EEM_Base::default_where_conditions_minimum_others,
3694
-                           EEM_Base::default_where_conditions_minimum_all,
3695
-                       ),
3696
-                       true
3697
-                   )
3698
-               );
3699
-    }
3700
-
3701
-
3702
-    /**
3703
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3704
-     * then we also add a special where condition which allows for that model's primary key
3705
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3706
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3707
-     *
3708
-     * @param array    $default_where_conditions
3709
-     * @param array    $provided_where_conditions
3710
-     * @param EEM_Base $model
3711
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3712
-     * @return array like EEM_Base::get_all's $query_params[0]
3713
-     * @throws EE_Error
3714
-     */
3715
-    private function _override_defaults_or_make_null_friendly(
3716
-        $default_where_conditions,
3717
-        $provided_where_conditions,
3718
-        $model,
3719
-        $model_relation_path
3720
-    ) {
3721
-        $null_friendly_where_conditions = array();
3722
-        $none_overridden = true;
3723
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3724
-        foreach ($default_where_conditions as $key => $val) {
3725
-            if (isset($provided_where_conditions[$key])) {
3726
-                $none_overridden = false;
3727
-            } else {
3728
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3729
-            }
3730
-        }
3731
-        if ($none_overridden && $default_where_conditions) {
3732
-            if ($model->has_primary_key_field()) {
3733
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3734
-                                                                                . "."
3735
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3736
-            }/*else{
2219
+	/**
2220
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2221
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2222
+	 * column
2223
+	 *
2224
+	 * @param array  $query_params   like EEM_Base::get_all's
2225
+	 * @param string $field_to_count field on model to count by (not column name)
2226
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2227
+	 *                               that by the setting $distinct to TRUE;
2228
+	 * @return int
2229
+	 * @throws EE_Error
2230
+	 */
2231
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2232
+	{
2233
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2234
+		if ($field_to_count) {
2235
+			$field_obj = $this->field_settings_for($field_to_count);
2236
+			$column_to_count = $field_obj->get_qualified_column();
2237
+		} elseif ($this->has_primary_key_field()) {
2238
+			$pk_field_obj = $this->get_primary_key_field();
2239
+			$column_to_count = $pk_field_obj->get_qualified_column();
2240
+		} else {
2241
+			//there's no primary key
2242
+			//if we're counting distinct items, and there's no primary key,
2243
+			//we need to list out the columns for distinction;
2244
+			//otherwise we can just use star
2245
+			if ($distinct) {
2246
+				$columns_to_use = array();
2247
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2248
+					$columns_to_use[] = $field_obj->get_qualified_column();
2249
+				}
2250
+				$column_to_count = implode(',', $columns_to_use);
2251
+			} else {
2252
+				$column_to_count = '*';
2253
+			}
2254
+		}
2255
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2256
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2257
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2258
+	}
2259
+
2260
+
2261
+
2262
+	/**
2263
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2264
+	 *
2265
+	 * @param array  $query_params like EEM_Base::get_all
2266
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2267
+	 * @return float
2268
+	 * @throws EE_Error
2269
+	 */
2270
+	public function sum($query_params, $field_to_sum = null)
2271
+	{
2272
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2273
+		if ($field_to_sum) {
2274
+			$field_obj = $this->field_settings_for($field_to_sum);
2275
+		} else {
2276
+			$field_obj = $this->get_primary_key_field();
2277
+		}
2278
+		$column_to_count = $field_obj->get_qualified_column();
2279
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2280
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2281
+		$data_type = $field_obj->get_wpdb_data_type();
2282
+		if ($data_type === '%d' || $data_type === '%s') {
2283
+			return (float)$return_value;
2284
+		}
2285
+		//must be %f
2286
+		return (float)$return_value;
2287
+	}
2288
+
2289
+
2290
+
2291
+	/**
2292
+	 * Just calls the specified method on $wpdb with the given arguments
2293
+	 * Consolidates a little extra error handling code
2294
+	 *
2295
+	 * @param string $wpdb_method
2296
+	 * @param array  $arguments_to_provide
2297
+	 * @throws EE_Error
2298
+	 * @global wpdb  $wpdb
2299
+	 * @return mixed
2300
+	 */
2301
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2302
+	{
2303
+		//if we're in maintenance mode level 2, DON'T run any queries
2304
+		//because level 2 indicates the database needs updating and
2305
+		//is probably out of sync with the code
2306
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2307
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2308
+				"event_espresso")));
2309
+		}
2310
+		/** @type WPDB $wpdb */
2311
+		global $wpdb;
2312
+		if (! method_exists($wpdb, $wpdb_method)) {
2313
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2314
+				'event_espresso'), $wpdb_method));
2315
+		}
2316
+		if (WP_DEBUG) {
2317
+			$old_show_errors_value = $wpdb->show_errors;
2318
+			$wpdb->show_errors(false);
2319
+		}
2320
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2321
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2322
+		if (WP_DEBUG) {
2323
+			$wpdb->show_errors($old_show_errors_value);
2324
+			if (! empty($wpdb->last_error)) {
2325
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2326
+			}
2327
+			if ($result === false) {
2328
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2329
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2330
+			}
2331
+		} elseif ($result === false) {
2332
+			EE_Error::add_error(
2333
+				sprintf(
2334
+					__('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2335
+						'event_espresso'),
2336
+					$wpdb_method,
2337
+					var_export($arguments_to_provide, true),
2338
+					$wpdb->last_error
2339
+				),
2340
+				__FILE__,
2341
+				__FUNCTION__,
2342
+				__LINE__
2343
+			);
2344
+		}
2345
+		return $result;
2346
+	}
2347
+
2348
+
2349
+
2350
+	/**
2351
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2352
+	 * and if there's an error tries to verify the DB is correct. Uses
2353
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2354
+	 * we should try to fix the EE core db, the addons, or just give up
2355
+	 *
2356
+	 * @param string $wpdb_method
2357
+	 * @param array  $arguments_to_provide
2358
+	 * @return mixed
2359
+	 */
2360
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2361
+	{
2362
+		/** @type WPDB $wpdb */
2363
+		global $wpdb;
2364
+		$wpdb->last_error = null;
2365
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2366
+		// was there an error running the query? but we don't care on new activations
2367
+		// (we're going to setup the DB anyway on new activations)
2368
+		if (($result === false || ! empty($wpdb->last_error))
2369
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2370
+		) {
2371
+			switch (EEM_Base::$_db_verification_level) {
2372
+				case EEM_Base::db_verified_none :
2373
+					// let's double-check core's DB
2374
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2375
+					break;
2376
+				case EEM_Base::db_verified_core :
2377
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2378
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2379
+					break;
2380
+				case EEM_Base::db_verified_addons :
2381
+					// ummmm... you in trouble
2382
+					return $result;
2383
+					break;
2384
+			}
2385
+			if (! empty($error_message)) {
2386
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387
+				trigger_error($error_message);
2388
+			}
2389
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2390
+		}
2391
+		return $result;
2392
+	}
2393
+
2394
+
2395
+
2396
+	/**
2397
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2398
+	 * EEM_Base::$_db_verification_level
2399
+	 *
2400
+	 * @param string $wpdb_method
2401
+	 * @param array  $arguments_to_provide
2402
+	 * @return string
2403
+	 */
2404
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2405
+	{
2406
+		/** @type WPDB $wpdb */
2407
+		global $wpdb;
2408
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2409
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2410
+		$error_message = sprintf(
2411
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2412
+				'event_espresso'),
2413
+			$wpdb->last_error,
2414
+			$wpdb_method,
2415
+			wp_json_encode($arguments_to_provide)
2416
+		);
2417
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2418
+		return $error_message;
2419
+	}
2420
+
2421
+
2422
+
2423
+	/**
2424
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2425
+	 * EEM_Base::$_db_verification_level
2426
+	 *
2427
+	 * @param $wpdb_method
2428
+	 * @param $arguments_to_provide
2429
+	 * @return string
2430
+	 */
2431
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2432
+	{
2433
+		/** @type WPDB $wpdb */
2434
+		global $wpdb;
2435
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2436
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2437
+		$error_message = sprintf(
2438
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2439
+				'event_espresso'),
2440
+			$wpdb->last_error,
2441
+			$wpdb_method,
2442
+			wp_json_encode($arguments_to_provide)
2443
+		);
2444
+		EE_System::instance()->initialize_addons();
2445
+		return $error_message;
2446
+	}
2447
+
2448
+
2449
+
2450
+	/**
2451
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2452
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2453
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2454
+	 * ..."
2455
+	 *
2456
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2457
+	 * @return string
2458
+	 */
2459
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2460
+	{
2461
+		return " FROM " . $model_query_info->get_full_join_sql() .
2462
+			   $model_query_info->get_where_sql() .
2463
+			   $model_query_info->get_group_by_sql() .
2464
+			   $model_query_info->get_having_sql() .
2465
+			   $model_query_info->get_order_by_sql() .
2466
+			   $model_query_info->get_limit_sql();
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * Set to easily debug the next X queries ran from this model.
2473
+	 *
2474
+	 * @param int $count
2475
+	 */
2476
+	public function show_next_x_db_queries($count = 1)
2477
+	{
2478
+		$this->_show_next_x_db_queries = $count;
2479
+	}
2480
+
2481
+
2482
+
2483
+	/**
2484
+	 * @param $sql_query
2485
+	 */
2486
+	public function show_db_query_if_previously_requested($sql_query)
2487
+	{
2488
+		if ($this->_show_next_x_db_queries > 0) {
2489
+			echo $sql_query;
2490
+			$this->_show_next_x_db_queries--;
2491
+		}
2492
+	}
2493
+
2494
+
2495
+
2496
+	/**
2497
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2498
+	 * There are the 3 cases:
2499
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2500
+	 * $otherModelObject has no ID, it is first saved.
2501
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2502
+	 * has no ID, it is first saved.
2503
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2504
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2505
+	 * join table
2506
+	 *
2507
+	 * @param        EE_Base_Class                     /int $thisModelObject
2508
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2509
+	 * @param string $relationName                     , key in EEM_Base::_relations
2510
+	 *                                                 an attendee to a group, you also want to specify which role they
2511
+	 *                                                 will have in that group. So you would use this parameter to
2512
+	 *                                                 specify array('role-column-name'=>'role-id')
2513
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2514
+	 *                                                 to for relation to methods that allow you to further specify
2515
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2516
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2517
+	 *                                                 because these will be inserted in any new rows created as well.
2518
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2519
+	 * @throws EE_Error
2520
+	 */
2521
+	public function add_relationship_to(
2522
+		$id_or_obj,
2523
+		$other_model_id_or_obj,
2524
+		$relationName,
2525
+		$extra_join_model_fields_n_values = array()
2526
+	) {
2527
+		$relation_obj = $this->related_settings_for($relationName);
2528
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2529
+	}
2530
+
2531
+
2532
+
2533
+	/**
2534
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2535
+	 * There are the 3 cases:
2536
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2537
+	 * error
2538
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2539
+	 * an error
2540
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2541
+	 *
2542
+	 * @param        EE_Base_Class /int $id_or_obj
2543
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2544
+	 * @param string $relationName key in EEM_Base::_relations
2545
+	 * @return boolean of success
2546
+	 * @throws EE_Error
2547
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2548
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2549
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2550
+	 *                             because these will be inserted in any new rows created as well.
2551
+	 */
2552
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2553
+	{
2554
+		$relation_obj = $this->related_settings_for($relationName);
2555
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2556
+	}
2557
+
2558
+
2559
+
2560
+	/**
2561
+	 * @param mixed           $id_or_obj
2562
+	 * @param string          $relationName
2563
+	 * @param array           $where_query_params
2564
+	 * @param EE_Base_Class[] objects to which relations were removed
2565
+	 * @return \EE_Base_Class[]
2566
+	 * @throws EE_Error
2567
+	 */
2568
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2569
+	{
2570
+		$relation_obj = $this->related_settings_for($relationName);
2571
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2572
+	}
2573
+
2574
+
2575
+
2576
+	/**
2577
+	 * Gets all the related items of the specified $model_name, using $query_params.
2578
+	 * Note: by default, we remove the "default query params"
2579
+	 * because we want to get even deleted items etc.
2580
+	 *
2581
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2582
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2583
+	 * @param array  $query_params like EEM_Base::get_all
2584
+	 * @return EE_Base_Class[]
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2588
+	{
2589
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2590
+		$relation_settings = $this->related_settings_for($model_name);
2591
+		return $relation_settings->get_all_related($model_obj, $query_params);
2592
+	}
2593
+
2594
+
2595
+
2596
+	/**
2597
+	 * Deletes all the model objects across the relation indicated by $model_name
2598
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2599
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2600
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2601
+	 *
2602
+	 * @param EE_Base_Class|int|string $id_or_obj
2603
+	 * @param string                   $model_name
2604
+	 * @param array                    $query_params
2605
+	 * @return int how many deleted
2606
+	 * @throws EE_Error
2607
+	 */
2608
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2609
+	{
2610
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2611
+		$relation_settings = $this->related_settings_for($model_name);
2612
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2619
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2620
+	 * the model objects can't be hard deleted because of blocking related model objects,
2621
+	 * just does a soft-delete on them instead.
2622
+	 *
2623
+	 * @param EE_Base_Class|int|string $id_or_obj
2624
+	 * @param string                   $model_name
2625
+	 * @param array                    $query_params
2626
+	 * @return int how many deleted
2627
+	 * @throws EE_Error
2628
+	 */
2629
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2630
+	{
2631
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2632
+		$relation_settings = $this->related_settings_for($model_name);
2633
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2640
+	 * unless otherwise specified in the $query_params
2641
+	 *
2642
+	 * @param        int             /EE_Base_Class $id_or_obj
2643
+	 * @param string $model_name     like 'Event', or 'Registration'
2644
+	 * @param array  $query_params   like EEM_Base::get_all's
2645
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2646
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2647
+	 *                               that by the setting $distinct to TRUE;
2648
+	 * @return int
2649
+	 * @throws EE_Error
2650
+	 */
2651
+	public function count_related(
2652
+		$id_or_obj,
2653
+		$model_name,
2654
+		$query_params = array(),
2655
+		$field_to_count = null,
2656
+		$distinct = false
2657
+	) {
2658
+		$related_model = $this->get_related_model_obj($model_name);
2659
+		//we're just going to use the query params on the related model's normal get_all query,
2660
+		//except add a condition to say to match the current mod
2661
+		if (! isset($query_params['default_where_conditions'])) {
2662
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2663
+		}
2664
+		$this_model_name = $this->get_this_model_name();
2665
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2666
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2667
+		return $related_model->count($query_params, $field_to_count, $distinct);
2668
+	}
2669
+
2670
+
2671
+
2672
+	/**
2673
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2674
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2675
+	 *
2676
+	 * @param        int           /EE_Base_Class $id_or_obj
2677
+	 * @param string $model_name   like 'Event', or 'Registration'
2678
+	 * @param array  $query_params like EEM_Base::get_all's
2679
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2680
+	 * @return float
2681
+	 * @throws EE_Error
2682
+	 */
2683
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2684
+	{
2685
+		$related_model = $this->get_related_model_obj($model_name);
2686
+		if (! is_array($query_params)) {
2687
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2688
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2689
+					gettype($query_params)), '4.6.0');
2690
+			$query_params = array();
2691
+		}
2692
+		//we're just going to use the query params on the related model's normal get_all query,
2693
+		//except add a condition to say to match the current mod
2694
+		if (! isset($query_params['default_where_conditions'])) {
2695
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
+		}
2697
+		$this_model_name = $this->get_this_model_name();
2698
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
+		return $related_model->sum($query_params, $field_to_sum);
2701
+	}
2702
+
2703
+
2704
+
2705
+	/**
2706
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2707
+	 * $modelObject
2708
+	 *
2709
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2710
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2711
+	 * @param array               $query_params     like EEM_Base::get_all's
2712
+	 * @return EE_Base_Class
2713
+	 * @throws EE_Error
2714
+	 */
2715
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2716
+	{
2717
+		$query_params['limit'] = 1;
2718
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2719
+		if ($results) {
2720
+			return array_shift($results);
2721
+		}
2722
+		return null;
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2729
+	 *
2730
+	 * @return string
2731
+	 */
2732
+	public function get_this_model_name()
2733
+	{
2734
+		return str_replace("EEM_", "", get_class($this));
2735
+	}
2736
+
2737
+
2738
+
2739
+	/**
2740
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2741
+	 *
2742
+	 * @return EE_Any_Foreign_Model_Name_Field
2743
+	 * @throws EE_Error
2744
+	 */
2745
+	public function get_field_containing_related_model_name()
2746
+	{
2747
+		foreach ($this->field_settings(true) as $field) {
2748
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2749
+				$field_with_model_name = $field;
2750
+			}
2751
+		}
2752
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2753
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2754
+				$this->get_this_model_name()));
2755
+		}
2756
+		return $field_with_model_name;
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Inserts a new entry into the database, for each table.
2763
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2764
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2765
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2766
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2767
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2768
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2769
+	 *
2770
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2771
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2772
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2773
+	 *                              of EEM_Base)
2774
+	 * @return int new primary key on main table that got inserted
2775
+	 * @throws EE_Error
2776
+	 */
2777
+	public function insert($field_n_values)
2778
+	{
2779
+		/**
2780
+		 * Filters the fields and their values before inserting an item using the models
2781
+		 *
2782
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2783
+		 * @param EEM_Base $model           the model used
2784
+		 */
2785
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2786
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2787
+			$main_table = $this->_get_main_table();
2788
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2789
+			if ($new_id !== false) {
2790
+				foreach ($this->_get_other_tables() as $other_table) {
2791
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2792
+				}
2793
+			}
2794
+			/**
2795
+			 * Done just after attempting to insert a new model object
2796
+			 *
2797
+			 * @param EEM_Base   $model           used
2798
+			 * @param array      $fields_n_values fields and their values
2799
+			 * @param int|string the              ID of the newly-inserted model object
2800
+			 */
2801
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2802
+			return $new_id;
2803
+		}
2804
+		return false;
2805
+	}
2806
+
2807
+
2808
+
2809
+	/**
2810
+	 * Checks that the result would satisfy the unique indexes on this model
2811
+	 *
2812
+	 * @param array  $field_n_values
2813
+	 * @param string $action
2814
+	 * @return boolean
2815
+	 * @throws EE_Error
2816
+	 */
2817
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2818
+	{
2819
+		foreach ($this->unique_indexes() as $index_name => $index) {
2820
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2821
+			if ($this->exists(array($uniqueness_where_params))) {
2822
+				EE_Error::add_error(
2823
+					sprintf(
2824
+						__(
2825
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2826
+							"event_espresso"
2827
+						),
2828
+						$action,
2829
+						$this->_get_class_name(),
2830
+						$index_name,
2831
+						implode(",", $index->field_names()),
2832
+						http_build_query($uniqueness_where_params)
2833
+					),
2834
+					__FILE__,
2835
+					__FUNCTION__,
2836
+					__LINE__
2837
+				);
2838
+				return false;
2839
+			}
2840
+		}
2841
+		return true;
2842
+	}
2843
+
2844
+
2845
+
2846
+	/**
2847
+	 * Checks the database for an item that conflicts (ie, if this item were
2848
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2849
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2850
+	 * can be either an EE_Base_Class or an array of fields n values
2851
+	 *
2852
+	 * @param EE_Base_Class|array $obj_or_fields_array
2853
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2854
+	 *                                                 when looking for conflicts
2855
+	 *                                                 (ie, if false, we ignore the model object's primary key
2856
+	 *                                                 when finding "conflicts". If true, it's also considered).
2857
+	 *                                                 Only works for INT primary key,
2858
+	 *                                                 STRING primary keys cannot be ignored
2859
+	 * @throws EE_Error
2860
+	 * @return EE_Base_Class|array
2861
+	 */
2862
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2863
+	{
2864
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2865
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2866
+		} elseif (is_array($obj_or_fields_array)) {
2867
+			$fields_n_values = $obj_or_fields_array;
2868
+		} else {
2869
+			throw new EE_Error(
2870
+				sprintf(
2871
+					__(
2872
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2873
+						"event_espresso"
2874
+					),
2875
+					get_class($this),
2876
+					$obj_or_fields_array
2877
+				)
2878
+			);
2879
+		}
2880
+		$query_params = array();
2881
+		if ($this->has_primary_key_field()
2882
+			&& ($include_primary_key
2883
+				|| $this->get_primary_key_field()
2884
+				   instanceof
2885
+				   EE_Primary_Key_String_Field)
2886
+			&& isset($fields_n_values[$this->primary_key_name()])
2887
+		) {
2888
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2889
+		}
2890
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2891
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2892
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2893
+		}
2894
+		//if there is nothing to base this search on, then we shouldn't find anything
2895
+		if (empty($query_params)) {
2896
+			return array();
2897
+		}
2898
+		return $this->get_one($query_params);
2899
+	}
2900
+
2901
+
2902
+
2903
+	/**
2904
+	 * Like count, but is optimized and returns a boolean instead of an int
2905
+	 *
2906
+	 * @param array $query_params
2907
+	 * @return boolean
2908
+	 * @throws EE_Error
2909
+	 */
2910
+	public function exists($query_params)
2911
+	{
2912
+		$query_params['limit'] = 1;
2913
+		return $this->count($query_params) > 0;
2914
+	}
2915
+
2916
+
2917
+
2918
+	/**
2919
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2920
+	 *
2921
+	 * @param int|string $id
2922
+	 * @return boolean
2923
+	 * @throws EE_Error
2924
+	 */
2925
+	public function exists_by_ID($id)
2926
+	{
2927
+		return $this->exists(
2928
+			array(
2929
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2930
+				array(
2931
+					$this->primary_key_name() => $id,
2932
+				),
2933
+			)
2934
+		);
2935
+	}
2936
+
2937
+
2938
+
2939
+	/**
2940
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2941
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2942
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2943
+	 * on the main table)
2944
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2945
+	 * cases where we want to call it directly rather than via insert().
2946
+	 *
2947
+	 * @access   protected
2948
+	 * @param EE_Table_Base $table
2949
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2950
+	 *                                       float
2951
+	 * @param int           $new_id          for now we assume only int keys
2952
+	 * @throws EE_Error
2953
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2954
+	 * @return int ID of new row inserted, or FALSE on failure
2955
+	 */
2956
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2957
+	{
2958
+		global $wpdb;
2959
+		$insertion_col_n_values = array();
2960
+		$format_for_insertion = array();
2961
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2962
+		foreach ($fields_on_table as $field_name => $field_obj) {
2963
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2964
+			if ($field_obj->is_auto_increment()) {
2965
+				continue;
2966
+			}
2967
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2968
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2969
+			if ($prepared_value !== null) {
2970
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2971
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2972
+			}
2973
+		}
2974
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2975
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2976
+			//so add the fk to the main table as a column
2977
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2978
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2979
+		}
2980
+		//insert the new entry
2981
+		$result = $this->_do_wpdb_query('insert',
2982
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2983
+		if ($result === false) {
2984
+			return false;
2985
+		}
2986
+		//ok, now what do we return for the ID of the newly-inserted thing?
2987
+		if ($this->has_primary_key_field()) {
2988
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2989
+				return $wpdb->insert_id;
2990
+			}
2991
+			//it's not an auto-increment primary key, so
2992
+			//it must have been supplied
2993
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
2994
+		}
2995
+		//we can't return a  primary key because there is none. instead return
2996
+		//a unique string indicating this model
2997
+		return $this->get_index_primary_key_string($fields_n_values);
2998
+	}
2999
+
3000
+
3001
+
3002
+	/**
3003
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3004
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3005
+	 * and there is no default, we pass it along. WPDB will take care of it)
3006
+	 *
3007
+	 * @param EE_Model_Field_Base $field_obj
3008
+	 * @param array               $fields_n_values
3009
+	 * @return mixed string|int|float depending on what the table column will be expecting
3010
+	 * @throws EE_Error
3011
+	 */
3012
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3013
+	{
3014
+		//if this field doesn't allow nullable, don't allow it
3015
+		if (
3016
+			! $field_obj->is_nullable()
3017
+			&& (
3018
+				! isset($fields_n_values[$field_obj->get_name()])
3019
+				|| $fields_n_values[$field_obj->get_name()] === null
3020
+			)
3021
+		) {
3022
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3023
+		}
3024
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3025
+			? $fields_n_values[$field_obj->get_name()]
3026
+			: null;
3027
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3028
+	}
3029
+
3030
+
3031
+
3032
+	/**
3033
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3034
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3035
+	 * the field's prepare_for_set() method.
3036
+	 *
3037
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3038
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3039
+	 *                                   top of file)
3040
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3041
+	 *                                   $value is a custom selection
3042
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3043
+	 */
3044
+	private function _prepare_value_for_use_in_db($value, $field)
3045
+	{
3046
+		if ($field && $field instanceof EE_Model_Field_Base) {
3047
+			switch ($this->_values_already_prepared_by_model_object) {
3048
+				/** @noinspection PhpMissingBreakStatementInspection */
3049
+				case self::not_prepared_by_model_object:
3050
+					$value = $field->prepare_for_set($value);
3051
+				//purposefully left out "return"
3052
+				case self::prepared_by_model_object:
3053
+					/** @noinspection SuspiciousAssignmentsInspection */
3054
+					$value = $field->prepare_for_use_in_db($value);
3055
+				case self::prepared_for_use_in_db:
3056
+					//leave the value alone
3057
+			}
3058
+			return $value;
3059
+		}
3060
+		return $value;
3061
+	}
3062
+
3063
+
3064
+
3065
+	/**
3066
+	 * Returns the main table on this model
3067
+	 *
3068
+	 * @return EE_Primary_Table
3069
+	 * @throws EE_Error
3070
+	 */
3071
+	protected function _get_main_table()
3072
+	{
3073
+		foreach ($this->_tables as $table) {
3074
+			if ($table instanceof EE_Primary_Table) {
3075
+				return $table;
3076
+			}
3077
+		}
3078
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3079
+			'event_espresso'), get_class($this)));
3080
+	}
3081
+
3082
+
3083
+
3084
+	/**
3085
+	 * table
3086
+	 * returns EE_Primary_Table table name
3087
+	 *
3088
+	 * @return string
3089
+	 * @throws EE_Error
3090
+	 */
3091
+	public function table()
3092
+	{
3093
+		return $this->_get_main_table()->get_table_name();
3094
+	}
3095
+
3096
+
3097
+
3098
+	/**
3099
+	 * table
3100
+	 * returns first EE_Secondary_Table table name
3101
+	 *
3102
+	 * @return string
3103
+	 */
3104
+	public function second_table()
3105
+	{
3106
+		// grab second table from tables array
3107
+		$second_table = end($this->_tables);
3108
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3109
+	}
3110
+
3111
+
3112
+
3113
+	/**
3114
+	 * get_table_obj_by_alias
3115
+	 * returns table name given it's alias
3116
+	 *
3117
+	 * @param string $table_alias
3118
+	 * @return EE_Primary_Table | EE_Secondary_Table
3119
+	 */
3120
+	public function get_table_obj_by_alias($table_alias = '')
3121
+	{
3122
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3123
+	}
3124
+
3125
+
3126
+
3127
+	/**
3128
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3129
+	 *
3130
+	 * @return EE_Secondary_Table[]
3131
+	 */
3132
+	protected function _get_other_tables()
3133
+	{
3134
+		$other_tables = array();
3135
+		foreach ($this->_tables as $table_alias => $table) {
3136
+			if ($table instanceof EE_Secondary_Table) {
3137
+				$other_tables[$table_alias] = $table;
3138
+			}
3139
+		}
3140
+		return $other_tables;
3141
+	}
3142
+
3143
+
3144
+
3145
+	/**
3146
+	 * Finds all the fields that correspond to the given table
3147
+	 *
3148
+	 * @param string $table_alias , array key in EEM_Base::_tables
3149
+	 * @return EE_Model_Field_Base[]
3150
+	 */
3151
+	public function _get_fields_for_table($table_alias)
3152
+	{
3153
+		return $this->_fields[$table_alias];
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3160
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3161
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3162
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3163
+	 * related Registration, Transaction, and Payment models.
3164
+	 *
3165
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3166
+	 * @return EE_Model_Query_Info_Carrier
3167
+	 * @throws EE_Error
3168
+	 */
3169
+	public function _extract_related_models_from_query($query_params)
3170
+	{
3171
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3172
+		if (array_key_exists(0, $query_params)) {
3173
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3174
+		}
3175
+		if (array_key_exists('group_by', $query_params)) {
3176
+			if (is_array($query_params['group_by'])) {
3177
+				$this->_extract_related_models_from_sub_params_array_values(
3178
+					$query_params['group_by'],
3179
+					$query_info_carrier,
3180
+					'group_by'
3181
+				);
3182
+			} elseif (! empty ($query_params['group_by'])) {
3183
+				$this->_extract_related_model_info_from_query_param(
3184
+					$query_params['group_by'],
3185
+					$query_info_carrier,
3186
+					'group_by'
3187
+				);
3188
+			}
3189
+		}
3190
+		if (array_key_exists('having', $query_params)) {
3191
+			$this->_extract_related_models_from_sub_params_array_keys(
3192
+				$query_params[0],
3193
+				$query_info_carrier,
3194
+				'having'
3195
+			);
3196
+		}
3197
+		if (array_key_exists('order_by', $query_params)) {
3198
+			if (is_array($query_params['order_by'])) {
3199
+				$this->_extract_related_models_from_sub_params_array_keys(
3200
+					$query_params['order_by'],
3201
+					$query_info_carrier,
3202
+					'order_by'
3203
+				);
3204
+			} elseif (! empty($query_params['order_by'])) {
3205
+				$this->_extract_related_model_info_from_query_param(
3206
+					$query_params['order_by'],
3207
+					$query_info_carrier,
3208
+					'order_by'
3209
+				);
3210
+			}
3211
+		}
3212
+		if (array_key_exists('force_join', $query_params)) {
3213
+			$this->_extract_related_models_from_sub_params_array_values(
3214
+				$query_params['force_join'],
3215
+				$query_info_carrier,
3216
+				'force_join'
3217
+			);
3218
+		}
3219
+		return $query_info_carrier;
3220
+	}
3221
+
3222
+
3223
+
3224
+	/**
3225
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3226
+	 *
3227
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3228
+	 *                                                      $query_params['having']
3229
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3230
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3231
+	 * @throws EE_Error
3232
+	 * @return \EE_Model_Query_Info_Carrier
3233
+	 */
3234
+	private function _extract_related_models_from_sub_params_array_keys(
3235
+		$sub_query_params,
3236
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3237
+		$query_param_type
3238
+	) {
3239
+		if (! empty($sub_query_params)) {
3240
+			$sub_query_params = (array)$sub_query_params;
3241
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3242
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3243
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3244
+					$query_param_type);
3245
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3246
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3247
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3248
+				//of array('Registration.TXN_ID'=>23)
3249
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3250
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3251
+					if (! is_array($possibly_array_of_params)) {
3252
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3253
+							"event_espresso"),
3254
+							$param, $possibly_array_of_params));
3255
+					}
3256
+					$this->_extract_related_models_from_sub_params_array_keys(
3257
+						$possibly_array_of_params,
3258
+						$model_query_info_carrier, $query_param_type
3259
+					);
3260
+				} elseif ($query_param_type === 0 //ie WHERE
3261
+						  && is_array($possibly_array_of_params)
3262
+						  && isset($possibly_array_of_params[2])
3263
+						  && $possibly_array_of_params[2] == true
3264
+				) {
3265
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3266
+					//indicating that $possible_array_of_params[1] is actually a field name,
3267
+					//from which we should extract query parameters!
3268
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3269
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3270
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3271
+					}
3272
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3273
+						$model_query_info_carrier, $query_param_type);
3274
+				}
3275
+			}
3276
+		}
3277
+		return $model_query_info_carrier;
3278
+	}
3279
+
3280
+
3281
+
3282
+	/**
3283
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3284
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3285
+	 *
3286
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3287
+	 *                                                      $query_params['having']
3288
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3289
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3290
+	 * @throws EE_Error
3291
+	 * @return \EE_Model_Query_Info_Carrier
3292
+	 */
3293
+	private function _extract_related_models_from_sub_params_array_values(
3294
+		$sub_query_params,
3295
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3296
+		$query_param_type
3297
+	) {
3298
+		if (! empty($sub_query_params)) {
3299
+			if (! is_array($sub_query_params)) {
3300
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3301
+					$sub_query_params));
3302
+			}
3303
+			foreach ($sub_query_params as $param) {
3304
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3305
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3306
+					$query_param_type);
3307
+			}
3308
+		}
3309
+		return $model_query_info_carrier;
3310
+	}
3311
+
3312
+
3313
+
3314
+	/**
3315
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3316
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3317
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3318
+	 * but use them in a different order. Eg, we need to know what models we are querying
3319
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3320
+	 * other models before we can finalize the where clause SQL.
3321
+	 *
3322
+	 * @param array $query_params
3323
+	 * @throws EE_Error
3324
+	 * @return EE_Model_Query_Info_Carrier
3325
+	 */
3326
+	public function _create_model_query_info_carrier($query_params)
3327
+	{
3328
+		if (! is_array($query_params)) {
3329
+			EE_Error::doing_it_wrong(
3330
+				'EEM_Base::_create_model_query_info_carrier',
3331
+				sprintf(
3332
+					__(
3333
+						'$query_params should be an array, you passed a variable of type %s',
3334
+						'event_espresso'
3335
+					),
3336
+					gettype($query_params)
3337
+				),
3338
+				'4.6.0'
3339
+			);
3340
+			$query_params = array();
3341
+		}
3342
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3343
+		//first check if we should alter the query to account for caps or not
3344
+		//because the caps might require us to do extra joins
3345
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3346
+			$query_params[0] = $where_query_params = array_replace_recursive(
3347
+				$where_query_params,
3348
+				$this->caps_where_conditions(
3349
+					$query_params['caps']
3350
+				)
3351
+			);
3352
+		}
3353
+		$query_object = $this->_extract_related_models_from_query($query_params);
3354
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3355
+		foreach ($where_query_params as $key => $value) {
3356
+			if (is_int($key)) {
3357
+				throw new EE_Error(
3358
+					sprintf(
3359
+						__(
3360
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3361
+							"event_espresso"
3362
+						),
3363
+						$key,
3364
+						var_export($value, true),
3365
+						var_export($query_params, true),
3366
+						get_class($this)
3367
+					)
3368
+				);
3369
+			}
3370
+		}
3371
+		if (
3372
+			array_key_exists('default_where_conditions', $query_params)
3373
+			&& ! empty($query_params['default_where_conditions'])
3374
+		) {
3375
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3376
+		} else {
3377
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3378
+		}
3379
+		$where_query_params = array_merge(
3380
+			$this->_get_default_where_conditions_for_models_in_query(
3381
+				$query_object,
3382
+				$use_default_where_conditions,
3383
+				$where_query_params
3384
+			),
3385
+			$where_query_params
3386
+		);
3387
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3388
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3389
+		// So we need to setup a subquery and use that for the main join.
3390
+		// Note for now this only works on the primary table for the model.
3391
+		// So for instance, you could set the limit array like this:
3392
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3393
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3394
+			$query_object->set_main_model_join_sql(
3395
+				$this->_construct_limit_join_select(
3396
+					$query_params['on_join_limit'][0],
3397
+					$query_params['on_join_limit'][1]
3398
+				)
3399
+			);
3400
+		}
3401
+		//set limit
3402
+		if (array_key_exists('limit', $query_params)) {
3403
+			if (is_array($query_params['limit'])) {
3404
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3405
+					$e = sprintf(
3406
+						__(
3407
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3408
+							"event_espresso"
3409
+						),
3410
+						http_build_query($query_params['limit'])
3411
+					);
3412
+					throw new EE_Error($e . "|" . $e);
3413
+				}
3414
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3415
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3416
+			} elseif (! empty ($query_params['limit'])) {
3417
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3418
+			}
3419
+		}
3420
+		//set order by
3421
+		if (array_key_exists('order_by', $query_params)) {
3422
+			if (is_array($query_params['order_by'])) {
3423
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3424
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3425
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3426
+				if (array_key_exists('order', $query_params)) {
3427
+					throw new EE_Error(
3428
+						sprintf(
3429
+							__(
3430
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3431
+								"event_espresso"
3432
+							),
3433
+							get_class($this),
3434
+							implode(", ", array_keys($query_params['order_by'])),
3435
+							implode(", ", $query_params['order_by']),
3436
+							$query_params['order']
3437
+						)
3438
+					);
3439
+				}
3440
+				$this->_extract_related_models_from_sub_params_array_keys(
3441
+					$query_params['order_by'],
3442
+					$query_object,
3443
+					'order_by'
3444
+				);
3445
+				//assume it's an array of fields to order by
3446
+				$order_array = array();
3447
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3448
+					$order = $this->_extract_order($order);
3449
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3450
+				}
3451
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3452
+			} elseif (! empty ($query_params['order_by'])) {
3453
+				$this->_extract_related_model_info_from_query_param(
3454
+					$query_params['order_by'],
3455
+					$query_object,
3456
+					'order',
3457
+					$query_params['order_by']
3458
+				);
3459
+				$order = isset($query_params['order'])
3460
+					? $this->_extract_order($query_params['order'])
3461
+					: 'DESC';
3462
+				$query_object->set_order_by_sql(
3463
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3464
+				);
3465
+			}
3466
+		}
3467
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3468
+		if (! array_key_exists('order_by', $query_params)
3469
+			&& array_key_exists('order', $query_params)
3470
+			&& ! empty($query_params['order'])
3471
+		) {
3472
+			$pk_field = $this->get_primary_key_field();
3473
+			$order = $this->_extract_order($query_params['order']);
3474
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3475
+		}
3476
+		//set group by
3477
+		if (array_key_exists('group_by', $query_params)) {
3478
+			if (is_array($query_params['group_by'])) {
3479
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3480
+				$group_by_array = array();
3481
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3482
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3483
+				}
3484
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3485
+			} elseif (! empty ($query_params['group_by'])) {
3486
+				$query_object->set_group_by_sql(
3487
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3488
+				);
3489
+			}
3490
+		}
3491
+		//set having
3492
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3493
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3494
+		}
3495
+		//now, just verify they didn't pass anything wack
3496
+		foreach ($query_params as $query_key => $query_value) {
3497
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3498
+				throw new EE_Error(
3499
+					sprintf(
3500
+						__(
3501
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3502
+							'event_espresso'
3503
+						),
3504
+						$query_key,
3505
+						get_class($this),
3506
+						//						print_r( $this->_allowed_query_params, TRUE )
3507
+						implode(',', $this->_allowed_query_params)
3508
+					)
3509
+				);
3510
+			}
3511
+		}
3512
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3513
+		if (empty($main_model_join_sql)) {
3514
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3515
+		}
3516
+		return $query_object;
3517
+	}
3518
+
3519
+
3520
+
3521
+	/**
3522
+	 * Gets the where conditions that should be imposed on the query based on the
3523
+	 * context (eg reading frontend, backend, edit or delete).
3524
+	 *
3525
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3526
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3527
+	 * @throws EE_Error
3528
+	 */
3529
+	public function caps_where_conditions($context = self::caps_read)
3530
+	{
3531
+		EEM_Base::verify_is_valid_cap_context($context);
3532
+		$cap_where_conditions = array();
3533
+		$cap_restrictions = $this->caps_missing($context);
3534
+		/**
3535
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3536
+		 */
3537
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3538
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3539
+				$restriction_if_no_cap->get_default_where_conditions());
3540
+		}
3541
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3542
+			$cap_restrictions);
3543
+	}
3544
+
3545
+
3546
+
3547
+	/**
3548
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3549
+	 * otherwise throws an exception
3550
+	 *
3551
+	 * @param string $should_be_order_string
3552
+	 * @return string either ASC, asc, DESC or desc
3553
+	 * @throws EE_Error
3554
+	 */
3555
+	private function _extract_order($should_be_order_string)
3556
+	{
3557
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3558
+			return $should_be_order_string;
3559
+		}
3560
+		throw new EE_Error(
3561
+			sprintf(
3562
+				__(
3563
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3564
+					"event_espresso"
3565
+				), get_class($this), $should_be_order_string
3566
+			)
3567
+		);
3568
+	}
3569
+
3570
+
3571
+
3572
+	/**
3573
+	 * Looks at all the models which are included in this query, and asks each
3574
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3575
+	 * so they can be merged
3576
+	 *
3577
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3578
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3579
+	 *                                                                  'none' means NO default where conditions will
3580
+	 *                                                                  be used AT ALL during this query.
3581
+	 *                                                                  'other_models_only' means default where
3582
+	 *                                                                  conditions from other models will be used, but
3583
+	 *                                                                  not for this primary model. 'all', the default,
3584
+	 *                                                                  means default where conditions will apply as
3585
+	 *                                                                  normal
3586
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3587
+	 * @throws EE_Error
3588
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3589
+	 */
3590
+	private function _get_default_where_conditions_for_models_in_query(
3591
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3592
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3593
+		$where_query_params = array()
3594
+	) {
3595
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3596
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3597
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3598
+				"event_espresso"), $use_default_where_conditions,
3599
+				implode(", ", $allowed_used_default_where_conditions_values)));
3600
+		}
3601
+		$universal_query_params = array();
3602
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3603
+			$universal_query_params = $this->_get_default_where_conditions();
3604
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3605
+			$universal_query_params = $this->_get_minimum_where_conditions();
3606
+		}
3607
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3608
+			$related_model = $this->get_related_model_obj($model_name);
3609
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3610
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3611
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3612
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3613
+			} else {
3614
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3615
+				continue;
3616
+			}
3617
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3618
+				$related_model_universal_where_params,
3619
+				$where_query_params,
3620
+				$related_model,
3621
+				$model_relation_path
3622
+			);
3623
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3624
+				$universal_query_params,
3625
+				$overrides
3626
+			);
3627
+		}
3628
+		return $universal_query_params;
3629
+	}
3630
+
3631
+
3632
+
3633
+	/**
3634
+	 * Determines whether or not we should use default where conditions for the model in question
3635
+	 * (this model, or other related models).
3636
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3637
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3638
+	 * We should use default where conditions on related models when they requested to use default where conditions
3639
+	 * on all models, or specifically just on other related models
3640
+	 * @param      $default_where_conditions_value
3641
+	 * @param bool $for_this_model false means this is for OTHER related models
3642
+	 * @return bool
3643
+	 */
3644
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3645
+	{
3646
+		return (
3647
+				   $for_this_model
3648
+				   && in_array(
3649
+					   $default_where_conditions_value,
3650
+					   array(
3651
+						   EEM_Base::default_where_conditions_all,
3652
+						   EEM_Base::default_where_conditions_this_only,
3653
+						   EEM_Base::default_where_conditions_minimum_others,
3654
+					   ),
3655
+					   true
3656
+				   )
3657
+			   )
3658
+			   || (
3659
+				   ! $for_this_model
3660
+				   && in_array(
3661
+					   $default_where_conditions_value,
3662
+					   array(
3663
+						   EEM_Base::default_where_conditions_all,
3664
+						   EEM_Base::default_where_conditions_others_only,
3665
+					   ),
3666
+					   true
3667
+				   )
3668
+			   );
3669
+	}
3670
+
3671
+	/**
3672
+	 * Determines whether or not we should use default minimum conditions for the model in question
3673
+	 * (this model, or other related models).
3674
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3675
+	 * where conditions.
3676
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3677
+	 * on this model or others
3678
+	 * @param      $default_where_conditions_value
3679
+	 * @param bool $for_this_model false means this is for OTHER related models
3680
+	 * @return bool
3681
+	 */
3682
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3683
+	{
3684
+		return (
3685
+				   $for_this_model
3686
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3687
+			   )
3688
+			   || (
3689
+				   ! $for_this_model
3690
+				   && in_array(
3691
+					   $default_where_conditions_value,
3692
+					   array(
3693
+						   EEM_Base::default_where_conditions_minimum_others,
3694
+						   EEM_Base::default_where_conditions_minimum_all,
3695
+					   ),
3696
+					   true
3697
+				   )
3698
+			   );
3699
+	}
3700
+
3701
+
3702
+	/**
3703
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3704
+	 * then we also add a special where condition which allows for that model's primary key
3705
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3706
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3707
+	 *
3708
+	 * @param array    $default_where_conditions
3709
+	 * @param array    $provided_where_conditions
3710
+	 * @param EEM_Base $model
3711
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3712
+	 * @return array like EEM_Base::get_all's $query_params[0]
3713
+	 * @throws EE_Error
3714
+	 */
3715
+	private function _override_defaults_or_make_null_friendly(
3716
+		$default_where_conditions,
3717
+		$provided_where_conditions,
3718
+		$model,
3719
+		$model_relation_path
3720
+	) {
3721
+		$null_friendly_where_conditions = array();
3722
+		$none_overridden = true;
3723
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3724
+		foreach ($default_where_conditions as $key => $val) {
3725
+			if (isset($provided_where_conditions[$key])) {
3726
+				$none_overridden = false;
3727
+			} else {
3728
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3729
+			}
3730
+		}
3731
+		if ($none_overridden && $default_where_conditions) {
3732
+			if ($model->has_primary_key_field()) {
3733
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3734
+																				. "."
3735
+																				. $model->primary_key_name()] = array('IS NULL');
3736
+			}/*else{
3737 3737
 				//@todo NO PK, use other defaults
3738 3738
 			}*/
3739
-        }
3740
-        return $null_friendly_where_conditions;
3741
-    }
3742
-
3743
-
3744
-
3745
-    /**
3746
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3747
-     * default where conditions on all get_all, update, and delete queries done by this model.
3748
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3749
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3750
-     *
3751
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3752
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3753
-     */
3754
-    private function _get_default_where_conditions($model_relation_path = null)
3755
-    {
3756
-        if ($this->_ignore_where_strategy) {
3757
-            return array();
3758
-        }
3759
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3760
-    }
3761
-
3762
-
3763
-
3764
-    /**
3765
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3766
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3767
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3768
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3769
-     * Similar to _get_default_where_conditions
3770
-     *
3771
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3772
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3773
-     */
3774
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3775
-    {
3776
-        if ($this->_ignore_where_strategy) {
3777
-            return array();
3778
-        }
3779
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3780
-    }
3781
-
3782
-
3783
-
3784
-    /**
3785
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3786
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3787
-     *
3788
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3789
-     * @return string
3790
-     * @throws EE_Error
3791
-     */
3792
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3793
-    {
3794
-        $selects = $this->_get_columns_to_select_for_this_model();
3795
-        foreach (
3796
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3797
-            $name_of_other_model_included
3798
-        ) {
3799
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3800
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3801
-            foreach ($other_model_selects as $key => $value) {
3802
-                $selects[] = $value;
3803
-            }
3804
-        }
3805
-        return implode(", ", $selects);
3806
-    }
3807
-
3808
-
3809
-
3810
-    /**
3811
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3812
-     * So that's going to be the columns for all the fields on the model
3813
-     *
3814
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3815
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3816
-     */
3817
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3818
-    {
3819
-        $fields = $this->field_settings();
3820
-        $selects = array();
3821
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3822
-            $this->get_this_model_name());
3823
-        foreach ($fields as $field_obj) {
3824
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3825
-                         . $field_obj->get_table_alias()
3826
-                         . "."
3827
-                         . $field_obj->get_table_column()
3828
-                         . " AS '"
3829
-                         . $table_alias_with_model_relation_chain_prefix
3830
-                         . $field_obj->get_table_alias()
3831
-                         . "."
3832
-                         . $field_obj->get_table_column()
3833
-                         . "'";
3834
-        }
3835
-        //make sure we are also getting the PKs of each table
3836
-        $tables = $this->get_tables();
3837
-        if (count($tables) > 1) {
3838
-            foreach ($tables as $table_obj) {
3839
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3840
-                                       . $table_obj->get_fully_qualified_pk_column();
3841
-                if (! in_array($qualified_pk_column, $selects)) {
3842
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3843
-                }
3844
-            }
3845
-        }
3846
-        return $selects;
3847
-    }
3848
-
3849
-
3850
-
3851
-    /**
3852
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3853
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3854
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3855
-     * SQL for joining, and the data types
3856
-     *
3857
-     * @param null|string                 $original_query_param
3858
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3859
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3860
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3861
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3862
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3863
-     *                                                          or 'Registration's
3864
-     * @param string                      $original_query_param what it originally was (eg
3865
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3866
-     *                                                          matches $query_param
3867
-     * @throws EE_Error
3868
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3869
-     */
3870
-    private function _extract_related_model_info_from_query_param(
3871
-        $query_param,
3872
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3873
-        $query_param_type,
3874
-        $original_query_param = null
3875
-    ) {
3876
-        if ($original_query_param === null) {
3877
-            $original_query_param = $query_param;
3878
-        }
3879
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3880
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3881
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3882
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3883
-        //check to see if we have a field on this model
3884
-        $this_model_fields = $this->field_settings(true);
3885
-        if (array_key_exists($query_param, $this_model_fields)) {
3886
-            if ($allow_fields) {
3887
-                return;
3888
-            }
3889
-            throw new EE_Error(
3890
-                sprintf(
3891
-                    __(
3892
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3893
-                        "event_espresso"
3894
-                    ),
3895
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3896
-                )
3897
-            );
3898
-        }
3899
-        //check if this is a special logic query param
3900
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3901
-            if ($allow_logic_query_params) {
3902
-                return;
3903
-            }
3904
-            throw new EE_Error(
3905
-                sprintf(
3906
-                    __(
3907
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3908
-                        'event_espresso'
3909
-                    ),
3910
-                    implode('", "', $this->_logic_query_param_keys),
3911
-                    $query_param,
3912
-                    get_class($this),
3913
-                    '<br />',
3914
-                    "\t"
3915
-                    . ' $passed_in_query_info = <pre>'
3916
-                    . print_r($passed_in_query_info, true)
3917
-                    . '</pre>'
3918
-                    . "\n\t"
3919
-                    . ' $query_param_type = '
3920
-                    . $query_param_type
3921
-                    . "\n\t"
3922
-                    . ' $original_query_param = '
3923
-                    . $original_query_param
3924
-                )
3925
-            );
3926
-        }
3927
-        //check if it's a custom selection
3928
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3929
-            return;
3930
-        }
3931
-        //check if has a model name at the beginning
3932
-        //and
3933
-        //check if it's a field on a related model
3934
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3935
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3936
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3937
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3938
-                if ($query_param === '') {
3939
-                    //nothing left to $query_param
3940
-                    //we should actually end in a field name, not a model like this!
3941
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3942
-                        "event_espresso"),
3943
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3944
-                }
3945
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3946
-                $related_model_obj->_extract_related_model_info_from_query_param(
3947
-                    $query_param,
3948
-                    $passed_in_query_info, $query_param_type, $original_query_param
3949
-                );
3950
-                return;
3951
-            }
3952
-            if ($query_param === $valid_related_model_name) {
3953
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3954
-                return;
3955
-            }
3956
-        }
3957
-        //ok so $query_param didn't start with a model name
3958
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3959
-        //it's wack, that's what it is
3960
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3961
-            "event_espresso"),
3962
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3963
-    }
3964
-
3965
-
3966
-
3967
-    /**
3968
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3969
-     * and store it on $passed_in_query_info
3970
-     *
3971
-     * @param string                      $model_name
3972
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3973
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3974
-     *                                                          model and $model_name. Eg, if we are querying Event,
3975
-     *                                                          and are adding a join to 'Payment' with the original
3976
-     *                                                          query param key
3977
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3978
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3979
-     *                                                          Payment wants to add default query params so that it
3980
-     *                                                          will know what models to prepend onto its default query
3981
-     *                                                          params or in case it wants to rename tables (in case
3982
-     *                                                          there are multiple joins to the same table)
3983
-     * @return void
3984
-     * @throws EE_Error
3985
-     */
3986
-    private function _add_join_to_model(
3987
-        $model_name,
3988
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3989
-        $original_query_param
3990
-    ) {
3991
-        $relation_obj = $this->related_settings_for($model_name);
3992
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3993
-        //check if the relation is HABTM, because then we're essentially doing two joins
3994
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3995
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3996
-            $join_model_obj = $relation_obj->get_join_model();
3997
-            //replace the model specified with the join model for this relation chain, whi
3998
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3999
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4000
-            $new_query_info = new EE_Model_Query_Info_Carrier(
4001
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4002
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
4003
-            $passed_in_query_info->merge($new_query_info);
4004
-        }
4005
-        //now just join to the other table pointed to by the relation object, and add its data types
4006
-        $new_query_info = new EE_Model_Query_Info_Carrier(
4007
-            array($model_relation_chain => $model_name),
4008
-            $relation_obj->get_join_statement($model_relation_chain));
4009
-        $passed_in_query_info->merge($new_query_info);
4010
-    }
4011
-
4012
-
4013
-
4014
-    /**
4015
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4016
-     *
4017
-     * @param array $where_params like EEM_Base::get_all
4018
-     * @return string of SQL
4019
-     * @throws EE_Error
4020
-     */
4021
-    private function _construct_where_clause($where_params)
4022
-    {
4023
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4024
-        if ($SQL) {
4025
-            return " WHERE " . $SQL;
4026
-        }
4027
-        return '';
4028
-    }
4029
-
4030
-
4031
-
4032
-    /**
4033
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4034
-     * and should be passed HAVING parameters, not WHERE parameters
4035
-     *
4036
-     * @param array $having_params
4037
-     * @return string
4038
-     * @throws EE_Error
4039
-     */
4040
-    private function _construct_having_clause($having_params)
4041
-    {
4042
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4043
-        if ($SQL) {
4044
-            return " HAVING " . $SQL;
4045
-        }
4046
-        return '';
4047
-    }
4048
-
4049
-
4050
-
4051
-    /**
4052
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
4053
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
4054
-     * EEM_Attendee.
4055
-     *
4056
-     * @param string $field_name
4057
-     * @param string $model_name
4058
-     * @return EE_Model_Field_Base
4059
-     * @throws EE_Error
4060
-     */
4061
-    protected function _get_field_on_model($field_name, $model_name)
4062
-    {
4063
-        $model_class = 'EEM_' . $model_name;
4064
-        $model_filepath = $model_class . ".model.php";
4065
-        if (is_readable($model_filepath)) {
4066
-            require_once($model_filepath);
4067
-            $model_instance = call_user_func($model_name . "::instance");
4068
-            /* @var $model_instance EEM_Base */
4069
-            return $model_instance->field_settings_for($field_name);
4070
-        }
4071
-        throw new EE_Error(
4072
-            sprintf(
4073
-                __(
4074
-                    'No model named %s exists, with classname %s and filepath %s',
4075
-                    'event_espresso'
4076
-                ), $model_name, $model_class, $model_filepath
4077
-            )
4078
-        );
4079
-    }
4080
-
4081
-
4082
-
4083
-    /**
4084
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4085
-     * Event_Meta.meta_value = 'foo'))"
4086
-     *
4087
-     * @param array  $where_params see EEM_Base::get_all for documentation
4088
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4089
-     * @throws EE_Error
4090
-     * @return string of SQL
4091
-     */
4092
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4093
-    {
4094
-        $where_clauses = array();
4095
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4096
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4097
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4098
-                switch ($query_param) {
4099
-                    case 'not':
4100
-                    case 'NOT':
4101
-                        $where_clauses[] = "! ("
4102
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4103
-                                $glue)
4104
-                                           . ")";
4105
-                        break;
4106
-                    case 'and':
4107
-                    case 'AND':
4108
-                        $where_clauses[] = " ("
4109
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4110
-                                ' AND ')
4111
-                                           . ")";
4112
-                        break;
4113
-                    case 'or':
4114
-                    case 'OR':
4115
-                        $where_clauses[] = " ("
4116
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4117
-                                ' OR ')
4118
-                                           . ")";
4119
-                        break;
4120
-                }
4121
-            } else {
4122
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4123
-                //if it's not a normal field, maybe it's a custom selection?
4124
-                if (! $field_obj) {
4125
-                    if (isset($this->_custom_selections[$query_param][1])) {
4126
-                        $field_obj = $this->_custom_selections[$query_param][1];
4127
-                    } else {
4128
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4129
-                            "event_espresso"), $query_param));
4130
-                    }
4131
-                }
4132
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4133
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4134
-            }
4135
-        }
4136
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4137
-    }
4138
-
4139
-
4140
-
4141
-    /**
4142
-     * Takes the input parameter and extract the table name (alias) and column name
4143
-     *
4144
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4145
-     * @throws EE_Error
4146
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4147
-     */
4148
-    private function _deduce_column_name_from_query_param($query_param)
4149
-    {
4150
-        $field = $this->_deduce_field_from_query_param($query_param);
4151
-        if ($field) {
4152
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4153
-                $query_param);
4154
-            return $table_alias_prefix . $field->get_qualified_column();
4155
-        }
4156
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4157
-            //maybe it's custom selection item?
4158
-            //if so, just use it as the "column name"
4159
-            return $query_param;
4160
-        }
4161
-        throw new EE_Error(
4162
-            sprintf(
4163
-                __(
4164
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4165
-                    "event_espresso"
4166
-                ), $query_param, implode(",", $this->_custom_selections)
4167
-            )
4168
-        );
4169
-    }
4170
-
4171
-
4172
-
4173
-    /**
4174
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4175
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4176
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4177
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4178
-     *
4179
-     * @param string $condition_query_param_key
4180
-     * @return string
4181
-     */
4182
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4183
-    {
4184
-        $pos_of_star = strpos($condition_query_param_key, '*');
4185
-        if ($pos_of_star === false) {
4186
-            return $condition_query_param_key;
4187
-        }
4188
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4189
-        return $condition_query_param_sans_star;
4190
-    }
4191
-
4192
-
4193
-
4194
-    /**
4195
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4196
-     *
4197
-     * @param                            mixed      array | string    $op_and_value
4198
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4199
-     * @throws EE_Error
4200
-     * @return string
4201
-     */
4202
-    private function _construct_op_and_value($op_and_value, $field_obj)
4203
-    {
4204
-        if (is_array($op_and_value)) {
4205
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4206
-            if (! $operator) {
4207
-                $php_array_like_string = array();
4208
-                foreach ($op_and_value as $key => $value) {
4209
-                    $php_array_like_string[] = "$key=>$value";
4210
-                }
4211
-                throw new EE_Error(
4212
-                    sprintf(
4213
-                        __(
4214
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4215
-                            "event_espresso"
4216
-                        ),
4217
-                        implode(",", $php_array_like_string)
4218
-                    )
4219
-                );
4220
-            }
4221
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4222
-        } else {
4223
-            $operator = '=';
4224
-            $value = $op_and_value;
4225
-        }
4226
-        //check to see if the value is actually another field
4227
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4228
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4229
-        }
4230
-        if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4231
-            //in this case, the value should be an array, or at least a comma-separated list
4232
-            //it will need to handle a little differently
4233
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4234
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4235
-            return $operator . SP . $cleaned_value;
4236
-        }
4237
-        if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4238
-            //the value should be an array with count of two.
4239
-            if (count($value) !== 2) {
4240
-                throw new EE_Error(
4241
-                    sprintf(
4242
-                        __(
4243
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4244
-                            'event_espresso'
4245
-                        ),
4246
-                        "BETWEEN"
4247
-                    )
4248
-                );
4249
-            }
4250
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4251
-            return $operator . SP . $cleaned_value;
4252
-        }
4253
-        if (in_array($operator, $this->_null_style_operators)) {
4254
-            if ($value !== null) {
4255
-                throw new EE_Error(
4256
-                    sprintf(
4257
-                        __(
4258
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4259
-                            "event_espresso"
4260
-                        ),
4261
-                        $value,
4262
-                        $operator
4263
-                    )
4264
-                );
4265
-            }
4266
-            return $operator;
4267
-        }
4268
-        if ($operator === 'LIKE' && ! is_array($value)) {
4269
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4270
-            //remove other junk. So just treat it as a string.
4271
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4272
-        }
4273
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4274
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4275
-        }
4276
-        if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4277
-            throw new EE_Error(
4278
-                sprintf(
4279
-                    __(
4280
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4281
-                        'event_espresso'
4282
-                    ),
4283
-                    $operator,
4284
-                    $operator
4285
-                )
4286
-            );
4287
-        }
4288
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4289
-            throw new EE_Error(
4290
-                sprintf(
4291
-                    __(
4292
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4293
-                        'event_espresso'
4294
-                    ),
4295
-                    $operator,
4296
-                    $operator
4297
-                )
4298
-            );
4299
-        }
4300
-        throw new EE_Error(
4301
-            sprintf(
4302
-                __(
4303
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4304
-                    "event_espresso"
4305
-                ),
4306
-                http_build_query($op_and_value)
4307
-            )
4308
-        );
4309
-    }
4310
-
4311
-
4312
-
4313
-    /**
4314
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4315
-     *
4316
-     * @param array                      $values
4317
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4318
-     *                                              '%s'
4319
-     * @return string
4320
-     * @throws EE_Error
4321
-     */
4322
-    public function _construct_between_value($values, $field_obj)
4323
-    {
4324
-        $cleaned_values = array();
4325
-        foreach ($values as $value) {
4326
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4327
-        }
4328
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4329
-    }
4330
-
4331
-
4332
-
4333
-    /**
4334
-     * Takes an array or a comma-separated list of $values and cleans them
4335
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4336
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4337
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4338
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4339
-     *
4340
-     * @param mixed                      $values    array or comma-separated string
4341
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4342
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4343
-     * @throws EE_Error
4344
-     */
4345
-    public function _construct_in_value($values, $field_obj)
4346
-    {
4347
-        //check if the value is a CSV list
4348
-        if (is_string($values)) {
4349
-            //in which case, turn it into an array
4350
-            $values = explode(",", $values);
4351
-        }
4352
-        $cleaned_values = array();
4353
-        foreach ($values as $value) {
4354
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4355
-        }
4356
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4357
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4358
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4359
-        if (empty($cleaned_values)) {
4360
-            $all_fields = $this->field_settings();
4361
-            $a_field = array_shift($all_fields);
4362
-            $main_table = $this->_get_main_table();
4363
-            $cleaned_values[] = "SELECT "
4364
-                                . $a_field->get_table_column()
4365
-                                . " FROM "
4366
-                                . $main_table->get_table_name()
4367
-                                . " WHERE FALSE";
4368
-        }
4369
-        return "(" . implode(",", $cleaned_values) . ")";
4370
-    }
4371
-
4372
-
4373
-
4374
-    /**
4375
-     * @param mixed                      $value
4376
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4377
-     * @throws EE_Error
4378
-     * @return false|null|string
4379
-     */
4380
-    private function _wpdb_prepare_using_field($value, $field_obj)
4381
-    {
4382
-        /** @type WPDB $wpdb */
4383
-        global $wpdb;
4384
-        if ($field_obj instanceof EE_Model_Field_Base) {
4385
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4386
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4387
-        } //$field_obj should really just be a data type
4388
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4389
-            throw new EE_Error(
4390
-                sprintf(
4391
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4392
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4393
-                )
4394
-            );
4395
-        }
4396
-        return $wpdb->prepare($field_obj, $value);
4397
-    }
4398
-
4399
-
4400
-
4401
-    /**
4402
-     * Takes the input parameter and finds the model field that it indicates.
4403
-     *
4404
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4405
-     * @throws EE_Error
4406
-     * @return EE_Model_Field_Base
4407
-     */
4408
-    protected function _deduce_field_from_query_param($query_param_name)
4409
-    {
4410
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4411
-        //which will help us find the database table and column
4412
-        $query_param_parts = explode(".", $query_param_name);
4413
-        if (empty($query_param_parts)) {
4414
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4415
-                'event_espresso'), $query_param_name));
4416
-        }
4417
-        $number_of_parts = count($query_param_parts);
4418
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4419
-        if ($number_of_parts === 1) {
4420
-            $field_name = $last_query_param_part;
4421
-            $model_obj = $this;
4422
-        } else {// $number_of_parts >= 2
4423
-            //the last part is the column name, and there are only 2parts. therefore...
4424
-            $field_name = $last_query_param_part;
4425
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4426
-        }
4427
-        try {
4428
-            return $model_obj->field_settings_for($field_name);
4429
-        } catch (EE_Error $e) {
4430
-            return null;
4431
-        }
4432
-    }
4433
-
4434
-
4435
-
4436
-    /**
4437
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4438
-     * alias and column which corresponds to it
4439
-     *
4440
-     * @param string $field_name
4441
-     * @throws EE_Error
4442
-     * @return string
4443
-     */
4444
-    public function _get_qualified_column_for_field($field_name)
4445
-    {
4446
-        $all_fields = $this->field_settings();
4447
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4448
-        if ($field) {
4449
-            return $field->get_qualified_column();
4450
-        }
4451
-        throw new EE_Error(
4452
-            sprintf(
4453
-                __(
4454
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4455
-                    'event_espresso'
4456
-                ), $field_name, get_class($this)
4457
-            )
4458
-        );
4459
-    }
4460
-
4461
-
4462
-
4463
-    /**
4464
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4465
-     * Example usage:
4466
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4467
-     *      array(),
4468
-     *      ARRAY_A,
4469
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4470
-     *  );
4471
-     * is equivalent to
4472
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4473
-     * and
4474
-     *  EEM_Event::instance()->get_all_wpdb_results(
4475
-     *      array(
4476
-     *          array(
4477
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4478
-     *          ),
4479
-     *          ARRAY_A,
4480
-     *          implode(
4481
-     *              ', ',
4482
-     *              array_merge(
4483
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4484
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4485
-     *              )
4486
-     *          )
4487
-     *      )
4488
-     *  );
4489
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4490
-     *
4491
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4492
-     *                                            and the one whose fields you are selecting for example: when querying
4493
-     *                                            tickets model and selecting fields from the tickets model you would
4494
-     *                                            leave this parameter empty, because no models are needed to join
4495
-     *                                            between the queried model and the selected one. Likewise when
4496
-     *                                            querying the datetime model and selecting fields from the tickets
4497
-     *                                            model, it would also be left empty, because there is a direct
4498
-     *                                            relation from datetimes to tickets, so no model is needed to join
4499
-     *                                            them together. However, when querying from the event model and
4500
-     *                                            selecting fields from the ticket model, you should provide the string
4501
-     *                                            'Datetime', indicating that the event model must first join to the
4502
-     *                                            datetime model in order to find its relation to ticket model.
4503
-     *                                            Also, when querying from the venue model and selecting fields from
4504
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4505
-     *                                            indicating you need to join the venue model to the event model,
4506
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4507
-     *                                            This string is used to deduce the prefix that gets added onto the
4508
-     *                                            models' tables qualified columns
4509
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4510
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4511
-     *                                            qualified column names
4512
-     * @return array|string
4513
-     */
4514
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4515
-    {
4516
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4517
-        $qualified_columns = array();
4518
-        foreach ($this->field_settings() as $field_name => $field) {
4519
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4520
-        }
4521
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4522
-    }
4523
-
4524
-
4525
-
4526
-    /**
4527
-     * constructs the select use on special limit joins
4528
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4529
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4530
-     * (as that is typically where the limits would be set).
4531
-     *
4532
-     * @param  string       $table_alias The table the select is being built for
4533
-     * @param  mixed|string $limit       The limit for this select
4534
-     * @return string                The final select join element for the query.
4535
-     */
4536
-    public function _construct_limit_join_select($table_alias, $limit)
4537
-    {
4538
-        $SQL = '';
4539
-        foreach ($this->_tables as $table_obj) {
4540
-            if ($table_obj instanceof EE_Primary_Table) {
4541
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4542
-                    ? $table_obj->get_select_join_limit($limit)
4543
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4544
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4545
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4546
-                    ? $table_obj->get_select_join_limit_join($limit)
4547
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4548
-            }
4549
-        }
4550
-        return $SQL;
4551
-    }
4552
-
4553
-
4554
-
4555
-    /**
4556
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4557
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4558
-     *
4559
-     * @return string SQL
4560
-     * @throws EE_Error
4561
-     */
4562
-    public function _construct_internal_join()
4563
-    {
4564
-        $SQL = $this->_get_main_table()->get_table_sql();
4565
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4566
-        return $SQL;
4567
-    }
4568
-
4569
-
4570
-
4571
-    /**
4572
-     * Constructs the SQL for joining all the tables on this model.
4573
-     * Normally $alias should be the primary table's alias, but in cases where
4574
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4575
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4576
-     * alias, this will construct SQL like:
4577
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4578
-     * With $alias being a secondary table's alias, this will construct SQL like:
4579
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4580
-     *
4581
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4582
-     * @return string
4583
-     */
4584
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4585
-    {
4586
-        $SQL = '';
4587
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4588
-        foreach ($this->_tables as $table_obj) {
4589
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4590
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4591
-                    //so we're joining to this table, meaning the table is already in
4592
-                    //the FROM statement, BUT the primary table isn't. So we want
4593
-                    //to add the inverse join sql
4594
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4595
-                } else {
4596
-                    //just add a regular JOIN to this table from the primary table
4597
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4598
-                }
4599
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4600
-        }
4601
-        return $SQL;
4602
-    }
4603
-
4604
-
4605
-
4606
-    /**
4607
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4608
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4609
-     * their data type (eg, '%s', '%d', etc)
4610
-     *
4611
-     * @return array
4612
-     */
4613
-    public function _get_data_types()
4614
-    {
4615
-        $data_types = array();
4616
-        foreach ($this->field_settings() as $field_obj) {
4617
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4618
-            /** @var $field_obj EE_Model_Field_Base */
4619
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4620
-        }
4621
-        return $data_types;
4622
-    }
4623
-
4624
-
4625
-
4626
-    /**
4627
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4628
-     *
4629
-     * @param string $model_name
4630
-     * @throws EE_Error
4631
-     * @return EEM_Base
4632
-     */
4633
-    public function get_related_model_obj($model_name)
4634
-    {
4635
-        $model_classname = "EEM_" . $model_name;
4636
-        if (! class_exists($model_classname)) {
4637
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4638
-                'event_espresso'), $model_name, $model_classname));
4639
-        }
4640
-        return call_user_func($model_classname . "::instance");
4641
-    }
4642
-
4643
-
4644
-
4645
-    /**
4646
-     * Returns the array of EE_ModelRelations for this model.
4647
-     *
4648
-     * @return EE_Model_Relation_Base[]
4649
-     */
4650
-    public function relation_settings()
4651
-    {
4652
-        return $this->_model_relations;
4653
-    }
4654
-
4655
-
4656
-
4657
-    /**
4658
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4659
-     * because without THOSE models, this model probably doesn't have much purpose.
4660
-     * (Eg, without an event, datetimes have little purpose.)
4661
-     *
4662
-     * @return EE_Belongs_To_Relation[]
4663
-     */
4664
-    public function belongs_to_relations()
4665
-    {
4666
-        $belongs_to_relations = array();
4667
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4668
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4669
-                $belongs_to_relations[$model_name] = $relation_obj;
4670
-            }
4671
-        }
4672
-        return $belongs_to_relations;
4673
-    }
4674
-
4675
-
4676
-
4677
-    /**
4678
-     * Returns the specified EE_Model_Relation, or throws an exception
4679
-     *
4680
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4681
-     * @throws EE_Error
4682
-     * @return EE_Model_Relation_Base
4683
-     */
4684
-    public function related_settings_for($relation_name)
4685
-    {
4686
-        $relatedModels = $this->relation_settings();
4687
-        if (! array_key_exists($relation_name, $relatedModels)) {
4688
-            throw new EE_Error(
4689
-                sprintf(
4690
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4691
-                        'event_espresso'),
4692
-                    $relation_name,
4693
-                    $this->_get_class_name(),
4694
-                    implode(', ', array_keys($relatedModels))
4695
-                )
4696
-            );
4697
-        }
4698
-        return $relatedModels[$relation_name];
4699
-    }
4700
-
4701
-
4702
-
4703
-    /**
4704
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4705
-     * fields
4706
-     *
4707
-     * @param string $fieldName
4708
-     * @throws EE_Error
4709
-     * @return EE_Model_Field_Base
4710
-     */
4711
-    public function field_settings_for($fieldName)
4712
-    {
4713
-        $fieldSettings = $this->field_settings(true);
4714
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4715
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4716
-                get_class($this)));
4717
-        }
4718
-        return $fieldSettings[$fieldName];
4719
-    }
4720
-
4721
-
4722
-
4723
-    /**
4724
-     * Checks if this field exists on this model
4725
-     *
4726
-     * @param string $fieldName a key in the model's _field_settings array
4727
-     * @return boolean
4728
-     */
4729
-    public function has_field($fieldName)
4730
-    {
4731
-        $fieldSettings = $this->field_settings(true);
4732
-        if (isset($fieldSettings[$fieldName])) {
4733
-            return true;
4734
-        }
4735
-        return false;
4736
-    }
4737
-
4738
-
4739
-
4740
-    /**
4741
-     * Returns whether or not this model has a relation to the specified model
4742
-     *
4743
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4744
-     * @return boolean
4745
-     */
4746
-    public function has_relation($relation_name)
4747
-    {
4748
-        $relations = $this->relation_settings();
4749
-        if (isset($relations[$relation_name])) {
4750
-            return true;
4751
-        }
4752
-        return false;
4753
-    }
4754
-
4755
-
4756
-
4757
-    /**
4758
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4759
-     * Eg, on EE_Answer that would be ANS_ID field object
4760
-     *
4761
-     * @param $field_obj
4762
-     * @return boolean
4763
-     */
4764
-    public function is_primary_key_field($field_obj)
4765
-    {
4766
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4773
-     * Eg, on EE_Answer that would be ANS_ID field object
4774
-     *
4775
-     * @return EE_Model_Field_Base
4776
-     * @throws EE_Error
4777
-     */
4778
-    public function get_primary_key_field()
4779
-    {
4780
-        if ($this->_primary_key_field === null) {
4781
-            foreach ($this->field_settings(true) as $field_obj) {
4782
-                if ($this->is_primary_key_field($field_obj)) {
4783
-                    $this->_primary_key_field = $field_obj;
4784
-                    break;
4785
-                }
4786
-            }
4787
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4788
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4789
-                    get_class($this)));
4790
-            }
4791
-        }
4792
-        return $this->_primary_key_field;
4793
-    }
4794
-
4795
-
4796
-
4797
-    /**
4798
-     * Returns whether or not not there is a primary key on this model.
4799
-     * Internally does some caching.
4800
-     *
4801
-     * @return boolean
4802
-     */
4803
-    public function has_primary_key_field()
4804
-    {
4805
-        if ($this->_has_primary_key_field === null) {
4806
-            try {
4807
-                $this->get_primary_key_field();
4808
-                $this->_has_primary_key_field = true;
4809
-            } catch (EE_Error $e) {
4810
-                $this->_has_primary_key_field = false;
4811
-            }
4812
-        }
4813
-        return $this->_has_primary_key_field;
4814
-    }
4815
-
4816
-
4817
-
4818
-    /**
4819
-     * Finds the first field of type $field_class_name.
4820
-     *
4821
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4822
-     *                                 EE_Foreign_Key_Field, etc
4823
-     * @return EE_Model_Field_Base or null if none is found
4824
-     */
4825
-    public function get_a_field_of_type($field_class_name)
4826
-    {
4827
-        foreach ($this->field_settings() as $field) {
4828
-            if ($field instanceof $field_class_name) {
4829
-                return $field;
4830
-            }
4831
-        }
4832
-        return null;
4833
-    }
4834
-
4835
-
4836
-
4837
-    /**
4838
-     * Gets a foreign key field pointing to model.
4839
-     *
4840
-     * @param string $model_name eg Event, Registration, not EEM_Event
4841
-     * @return EE_Foreign_Key_Field_Base
4842
-     * @throws EE_Error
4843
-     */
4844
-    public function get_foreign_key_to($model_name)
4845
-    {
4846
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4847
-            foreach ($this->field_settings() as $field) {
4848
-                if (
4849
-                    $field instanceof EE_Foreign_Key_Field_Base
4850
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4851
-                ) {
4852
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4853
-                    break;
4854
-                }
4855
-            }
4856
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4857
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4858
-                    'event_espresso'), $model_name, get_class($this)));
4859
-            }
4860
-        }
4861
-        return $this->_cache_foreign_key_to_fields[$model_name];
4862
-    }
4863
-
4864
-
4865
-
4866
-    /**
4867
-     * Gets the table name (including $wpdb->prefix) for the table alias
4868
-     *
4869
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4870
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4871
-     *                            Either one works
4872
-     * @return string
4873
-     */
4874
-    public function get_table_for_alias($table_alias)
4875
-    {
4876
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4877
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4878
-    }
4879
-
4880
-
4881
-
4882
-    /**
4883
-     * Returns a flat array of all field son this model, instead of organizing them
4884
-     * by table_alias as they are in the constructor.
4885
-     *
4886
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4887
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4888
-     */
4889
-    public function field_settings($include_db_only_fields = false)
4890
-    {
4891
-        if ($include_db_only_fields) {
4892
-            if ($this->_cached_fields === null) {
4893
-                $this->_cached_fields = array();
4894
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4895
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4896
-                        $this->_cached_fields[$field_name] = $field_obj;
4897
-                    }
4898
-                }
4899
-            }
4900
-            return $this->_cached_fields;
4901
-        }
4902
-        if ($this->_cached_fields_non_db_only === null) {
4903
-            $this->_cached_fields_non_db_only = array();
4904
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4905
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4906
-                    /** @var $field_obj EE_Model_Field_Base */
4907
-                    if (! $field_obj->is_db_only_field()) {
4908
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4909
-                    }
4910
-                }
4911
-            }
4912
-        }
4913
-        return $this->_cached_fields_non_db_only;
4914
-    }
4915
-
4916
-
4917
-
4918
-    /**
4919
-     *        cycle though array of attendees and create objects out of each item
4920
-     *
4921
-     * @access        private
4922
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4923
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4924
-     *                           numerically indexed)
4925
-     * @throws EE_Error
4926
-     */
4927
-    protected function _create_objects($rows = array())
4928
-    {
4929
-        $array_of_objects = array();
4930
-        if (empty($rows)) {
4931
-            return array();
4932
-        }
4933
-        $count_if_model_has_no_primary_key = 0;
4934
-        $has_primary_key = $this->has_primary_key_field();
4935
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4936
-        foreach ((array)$rows as $row) {
4937
-            if (empty($row)) {
4938
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4939
-                return array();
4940
-            }
4941
-            //check if we've already set this object in the results array,
4942
-            //in which case there's no need to process it further (again)
4943
-            if ($has_primary_key) {
4944
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4945
-                    $row,
4946
-                    $primary_key_field->get_qualified_column(),
4947
-                    $primary_key_field->get_table_column()
4948
-                );
4949
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4950
-                    continue;
4951
-                }
4952
-            }
4953
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4954
-            if (! $classInstance) {
4955
-                throw new EE_Error(
4956
-                    sprintf(
4957
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4958
-                        $this->get_this_model_name(),
4959
-                        http_build_query($row)
4960
-                    )
4961
-                );
4962
-            }
4963
-            //set the timezone on the instantiated objects
4964
-            $classInstance->set_timezone($this->_timezone);
4965
-            //make sure if there is any timezone setting present that we set the timezone for the object
4966
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4967
-            $array_of_objects[$key] = $classInstance;
4968
-            //also, for all the relations of type BelongsTo, see if we can cache
4969
-            //those related models
4970
-            //(we could do this for other relations too, but if there are conditions
4971
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4972
-            //so it requires a little more thought than just caching them immediately...)
4973
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4974
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4975
-                    //check if this model's INFO is present. If so, cache it on the model
4976
-                    $other_model = $relation_obj->get_other_model();
4977
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4978
-                    //if we managed to make a model object from the results, cache it on the main model object
4979
-                    if ($other_model_obj_maybe) {
4980
-                        //set timezone on these other model objects if they are present
4981
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4982
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4983
-                    }
4984
-                }
4985
-            }
4986
-        }
4987
-        return $array_of_objects;
4988
-    }
4989
-
4990
-
4991
-
4992
-    /**
4993
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4994
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4995
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4996
-     * object (as set in the model_field!).
4997
-     *
4998
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4999
-     */
5000
-    public function create_default_object()
5001
-    {
5002
-        $this_model_fields_and_values = array();
5003
-        //setup the row using default values;
5004
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5005
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5006
-        }
5007
-        $className = $this->_get_class_name();
5008
-        $classInstance = EE_Registry::instance()
5009
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5010
-        return $classInstance;
5011
-    }
5012
-
5013
-
5014
-
5015
-    /**
5016
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5017
-     *                             or an stdClass where each property is the name of a column,
5018
-     * @return EE_Base_Class
5019
-     * @throws EE_Error
5020
-     */
5021
-    public function instantiate_class_from_array_or_object($cols_n_values)
5022
-    {
5023
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5024
-            $cols_n_values = get_object_vars($cols_n_values);
5025
-        }
5026
-        $primary_key = null;
5027
-        //make sure the array only has keys that are fields/columns on this model
5028
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5029
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5030
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5031
-        }
5032
-        $className = $this->_get_class_name();
5033
-        //check we actually found results that we can use to build our model object
5034
-        //if not, return null
5035
-        if ($this->has_primary_key_field()) {
5036
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5037
-                return null;
5038
-            }
5039
-        } else if ($this->unique_indexes()) {
5040
-            $first_column = reset($this_model_fields_n_values);
5041
-            if (empty($first_column)) {
5042
-                return null;
5043
-            }
5044
-        }
5045
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5046
-        if ($primary_key) {
5047
-            $classInstance = $this->get_from_entity_map($primary_key);
5048
-            if (! $classInstance) {
5049
-                $classInstance = EE_Registry::instance()
5050
-                                            ->load_class($className,
5051
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5052
-                // add this new object to the entity map
5053
-                $classInstance = $this->add_to_entity_map($classInstance);
5054
-            }
5055
-        } else {
5056
-            $classInstance = EE_Registry::instance()
5057
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5058
-                                            true, false);
5059
-        }
5060
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
5061
-        $this->set_timezone($classInstance->get_timezone());
5062
-        return $classInstance;
5063
-    }
5064
-
5065
-
5066
-
5067
-    /**
5068
-     * Gets the model object from the  entity map if it exists
5069
-     *
5070
-     * @param int|string $id the ID of the model object
5071
-     * @return EE_Base_Class
5072
-     */
5073
-    public function get_from_entity_map($id)
5074
-    {
5075
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5076
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5077
-    }
5078
-
5079
-
5080
-
5081
-    /**
5082
-     * add_to_entity_map
5083
-     * Adds the object to the model's entity mappings
5084
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5085
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5086
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5087
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5088
-     *        then this method should be called immediately after the update query
5089
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5090
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5091
-     *
5092
-     * @param    EE_Base_Class $object
5093
-     * @throws EE_Error
5094
-     * @return \EE_Base_Class
5095
-     */
5096
-    public function add_to_entity_map(EE_Base_Class $object)
5097
-    {
5098
-        $className = $this->_get_class_name();
5099
-        if (! $object instanceof $className) {
5100
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5101
-                is_object($object) ? get_class($object) : $object, $className));
5102
-        }
5103
-        /** @var $object EE_Base_Class */
5104
-        if (! $object->ID()) {
5105
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5106
-                "event_espresso"), get_class($this)));
5107
-        }
5108
-        // double check it's not already there
5109
-        $classInstance = $this->get_from_entity_map($object->ID());
5110
-        if ($classInstance) {
5111
-            return $classInstance;
5112
-        }
5113
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5114
-        return $object;
5115
-    }
5116
-
5117
-
5118
-
5119
-    /**
5120
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5121
-     * if no identifier is provided, then the entire entity map is emptied
5122
-     *
5123
-     * @param int|string $id the ID of the model object
5124
-     * @return boolean
5125
-     */
5126
-    public function clear_entity_map($id = null)
5127
-    {
5128
-        if (empty($id)) {
5129
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5130
-            return true;
5131
-        }
5132
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5133
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5134
-            return true;
5135
-        }
5136
-        return false;
5137
-    }
5138
-
5139
-
5140
-
5141
-    /**
5142
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5143
-     * Given an array where keys are column (or column alias) names and values,
5144
-     * returns an array of their corresponding field names and database values
5145
-     *
5146
-     * @param array $cols_n_values
5147
-     * @return array
5148
-     */
5149
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5150
-    {
5151
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5152
-    }
5153
-
5154
-
5155
-
5156
-    /**
5157
-     * _deduce_fields_n_values_from_cols_n_values
5158
-     * Given an array where keys are column (or column alias) names and values,
5159
-     * returns an array of their corresponding field names and database values
5160
-     *
5161
-     * @param string $cols_n_values
5162
-     * @return array
5163
-     */
5164
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5165
-    {
5166
-        $this_model_fields_n_values = array();
5167
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5168
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5169
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5170
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5171
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5172
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5173
-                    if (! $field_obj->is_db_only_field()) {
5174
-                        //prepare field as if its coming from db
5175
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5176
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5177
-                    }
5178
-                }
5179
-            } else {
5180
-                //the table's rows existed. Use their values
5181
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5182
-                    if (! $field_obj->is_db_only_field()) {
5183
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5184
-                            $cols_n_values, $field_obj->get_qualified_column(),
5185
-                            $field_obj->get_table_column()
5186
-                        );
5187
-                    }
5188
-                }
5189
-            }
5190
-        }
5191
-        return $this_model_fields_n_values;
5192
-    }
5193
-
5194
-
5195
-
5196
-    /**
5197
-     * @param $cols_n_values
5198
-     * @param $qualified_column
5199
-     * @param $regular_column
5200
-     * @return null
5201
-     */
5202
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5203
-    {
5204
-        $value = null;
5205
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5206
-        //does the field on the model relate to this column retrieved from the db?
5207
-        //or is it a db-only field? (not relating to the model)
5208
-        if (isset($cols_n_values[$qualified_column])) {
5209
-            $value = $cols_n_values[$qualified_column];
5210
-        } elseif (isset($cols_n_values[$regular_column])) {
5211
-            $value = $cols_n_values[$regular_column];
5212
-        }
5213
-        return $value;
5214
-    }
5215
-
5216
-
5217
-
5218
-    /**
5219
-     * refresh_entity_map_from_db
5220
-     * Makes sure the model object in the entity map at $id assumes the values
5221
-     * of the database (opposite of EE_base_Class::save())
5222
-     *
5223
-     * @param int|string $id
5224
-     * @return EE_Base_Class
5225
-     * @throws EE_Error
5226
-     */
5227
-    public function refresh_entity_map_from_db($id)
5228
-    {
5229
-        $obj_in_map = $this->get_from_entity_map($id);
5230
-        if ($obj_in_map) {
5231
-            $wpdb_results = $this->_get_all_wpdb_results(
5232
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5233
-            );
5234
-            if ($wpdb_results && is_array($wpdb_results)) {
5235
-                $one_row = reset($wpdb_results);
5236
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5237
-                    $obj_in_map->set_from_db($field_name, $db_value);
5238
-                }
5239
-                //clear the cache of related model objects
5240
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5241
-                    $obj_in_map->clear_cache($relation_name, null, true);
5242
-                }
5243
-            }
5244
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5245
-            return $obj_in_map;
5246
-        }
5247
-        return $this->get_one_by_ID($id);
5248
-    }
5249
-
5250
-
5251
-
5252
-    /**
5253
-     * refresh_entity_map_with
5254
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5255
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5256
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5257
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5258
-     *
5259
-     * @param int|string    $id
5260
-     * @param EE_Base_Class $replacing_model_obj
5261
-     * @return \EE_Base_Class
5262
-     * @throws EE_Error
5263
-     */
5264
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5265
-    {
5266
-        $obj_in_map = $this->get_from_entity_map($id);
5267
-        if ($obj_in_map) {
5268
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5269
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5270
-                    $obj_in_map->set($field_name, $value);
5271
-                }
5272
-                //make the model object in the entity map's cache match the $replacing_model_obj
5273
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5274
-                    $obj_in_map->clear_cache($relation_name, null, true);
5275
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5276
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5277
-                    }
5278
-                }
5279
-            }
5280
-            return $obj_in_map;
5281
-        }
5282
-        $this->add_to_entity_map($replacing_model_obj);
5283
-        return $replacing_model_obj;
5284
-    }
5285
-
5286
-
5287
-
5288
-    /**
5289
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5290
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5291
-     * require_once($this->_getClassName().".class.php");
5292
-     *
5293
-     * @return string
5294
-     */
5295
-    private function _get_class_name()
5296
-    {
5297
-        return "EE_" . $this->get_this_model_name();
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5304
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5305
-     * it would be 'Events'.
5306
-     *
5307
-     * @param int $quantity
5308
-     * @return string
5309
-     */
5310
-    public function item_name($quantity = 1)
5311
-    {
5312
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5313
-    }
5314
-
5315
-
5316
-
5317
-    /**
5318
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5319
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5320
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5321
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5322
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5323
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5324
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5325
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5326
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5327
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5328
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5329
-     *        return $previousReturnValue.$returnString;
5330
-     * }
5331
-     * require('EEM_Answer.model.php');
5332
-     * $answer=EEM_Answer::instance();
5333
-     * echo $answer->my_callback('monkeys',100);
5334
-     * //will output "you called my_callback! and passed args:monkeys,100"
5335
-     *
5336
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5337
-     * @param array  $args       array of original arguments passed to the function
5338
-     * @throws EE_Error
5339
-     * @return mixed whatever the plugin which calls add_filter decides
5340
-     */
5341
-    public function __call($methodName, $args)
5342
-    {
5343
-        $className = get_class($this);
5344
-        $tagName = "FHEE__{$className}__{$methodName}";
5345
-        if (! has_filter($tagName)) {
5346
-            throw new EE_Error(
5347
-                sprintf(
5348
-                    __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5349
-                        'event_espresso'),
5350
-                    $methodName,
5351
-                    $className,
5352
-                    $tagName,
5353
-                    '<br />'
5354
-                )
5355
-            );
5356
-        }
5357
-        return apply_filters($tagName, null, $this, $args);
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5364
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5365
-     *
5366
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5367
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5368
-     *                                                       the object's class name
5369
-     *                                                       or object's ID
5370
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5371
-     *                                                       exists in the database. If it does not, we add it
5372
-     * @throws EE_Error
5373
-     * @return EE_Base_Class
5374
-     */
5375
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5376
-    {
5377
-        $className = $this->_get_class_name();
5378
-        if ($base_class_obj_or_id instanceof $className) {
5379
-            $model_object = $base_class_obj_or_id;
5380
-        } else {
5381
-            $primary_key_field = $this->get_primary_key_field();
5382
-            if (
5383
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5384
-                && (
5385
-                    is_int($base_class_obj_or_id)
5386
-                    || is_string($base_class_obj_or_id)
5387
-                )
5388
-            ) {
5389
-                // assume it's an ID.
5390
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5391
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5392
-            } else if (
5393
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5394
-                && is_string($base_class_obj_or_id)
5395
-            ) {
5396
-                // assume its a string representation of the object
5397
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5398
-            } else {
5399
-                throw new EE_Error(
5400
-                    sprintf(
5401
-                        __(
5402
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5403
-                            'event_espresso'
5404
-                        ),
5405
-                        $base_class_obj_or_id,
5406
-                        $this->_get_class_name(),
5407
-                        print_r($base_class_obj_or_id, true)
5408
-                    )
5409
-                );
5410
-            }
5411
-        }
5412
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5413
-            $model_object->save();
5414
-        }
5415
-        return $model_object;
5416
-    }
5417
-
5418
-
5419
-
5420
-    /**
5421
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5422
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5423
-     * returns it ID.
5424
-     *
5425
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5426
-     * @return int|string depending on the type of this model object's ID
5427
-     * @throws EE_Error
5428
-     */
5429
-    public function ensure_is_ID($base_class_obj_or_id)
5430
-    {
5431
-        $className = $this->_get_class_name();
5432
-        if ($base_class_obj_or_id instanceof $className) {
5433
-            /** @var $base_class_obj_or_id EE_Base_Class */
5434
-            $id = $base_class_obj_or_id->ID();
5435
-        } elseif (is_int($base_class_obj_or_id)) {
5436
-            //assume it's an ID
5437
-            $id = $base_class_obj_or_id;
5438
-        } elseif (is_string($base_class_obj_or_id)) {
5439
-            //assume its a string representation of the object
5440
-            $id = $base_class_obj_or_id;
5441
-        } else {
5442
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5443
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5444
-                print_r($base_class_obj_or_id, true)));
5445
-        }
5446
-        return $id;
5447
-    }
5448
-
5449
-
5450
-
5451
-    /**
5452
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5453
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5454
-     * been sanitized and converted into the appropriate domain.
5455
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5456
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5457
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5458
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5459
-     * $EVT = EEM_Event::instance(); $old_setting =
5460
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5461
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5462
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5463
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5464
-     *
5465
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5466
-     * @return void
5467
-     */
5468
-    public function assume_values_already_prepared_by_model_object(
5469
-        $values_already_prepared = self::not_prepared_by_model_object
5470
-    ) {
5471
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5472
-    }
5473
-
5474
-
5475
-
5476
-    /**
5477
-     * Read comments for assume_values_already_prepared_by_model_object()
5478
-     *
5479
-     * @return int
5480
-     */
5481
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5482
-    {
5483
-        return $this->_values_already_prepared_by_model_object;
5484
-    }
5485
-
5486
-
5487
-
5488
-    /**
5489
-     * Gets all the indexes on this model
5490
-     *
5491
-     * @return EE_Index[]
5492
-     */
5493
-    public function indexes()
5494
-    {
5495
-        return $this->_indexes;
5496
-    }
5497
-
5498
-
5499
-
5500
-    /**
5501
-     * Gets all the Unique Indexes on this model
5502
-     *
5503
-     * @return EE_Unique_Index[]
5504
-     */
5505
-    public function unique_indexes()
5506
-    {
5507
-        $unique_indexes = array();
5508
-        foreach ($this->_indexes as $name => $index) {
5509
-            if ($index instanceof EE_Unique_Index) {
5510
-                $unique_indexes [$name] = $index;
5511
-            }
5512
-        }
5513
-        return $unique_indexes;
5514
-    }
5515
-
5516
-
5517
-
5518
-    /**
5519
-     * Gets all the fields which, when combined, make the primary key.
5520
-     * This is usually just an array with 1 element (the primary key), but in cases
5521
-     * where there is no primary key, it's a combination of fields as defined
5522
-     * on a primary index
5523
-     *
5524
-     * @return EE_Model_Field_Base[] indexed by the field's name
5525
-     * @throws EE_Error
5526
-     */
5527
-    public function get_combined_primary_key_fields()
5528
-    {
5529
-        foreach ($this->indexes() as $index) {
5530
-            if ($index instanceof EE_Primary_Key_Index) {
5531
-                return $index->fields();
5532
-            }
5533
-        }
5534
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5535
-    }
5536
-
5537
-
5538
-
5539
-    /**
5540
-     * Used to build a primary key string (when the model has no primary key),
5541
-     * which can be used a unique string to identify this model object.
5542
-     *
5543
-     * @param array $cols_n_values keys are field names, values are their values
5544
-     * @return string
5545
-     * @throws EE_Error
5546
-     */
5547
-    public function get_index_primary_key_string($cols_n_values)
5548
-    {
5549
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5550
-            $this->get_combined_primary_key_fields());
5551
-        return http_build_query($cols_n_values_for_primary_key_index);
5552
-    }
5553
-
5554
-
5555
-
5556
-    /**
5557
-     * Gets the field values from the primary key string
5558
-     *
5559
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5560
-     * @param string $index_primary_key_string
5561
-     * @return null|array
5562
-     * @throws EE_Error
5563
-     */
5564
-    public function parse_index_primary_key_string($index_primary_key_string)
5565
-    {
5566
-        $key_fields = $this->get_combined_primary_key_fields();
5567
-        //check all of them are in the $id
5568
-        $key_vals_in_combined_pk = array();
5569
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5570
-        foreach ($key_fields as $key_field_name => $field_obj) {
5571
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5572
-                return null;
5573
-            }
5574
-        }
5575
-        return $key_vals_in_combined_pk;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * verifies that an array of key-value pairs for model fields has a key
5582
-     * for each field comprising the primary key index
5583
-     *
5584
-     * @param array $key_vals
5585
-     * @return boolean
5586
-     * @throws EE_Error
5587
-     */
5588
-    public function has_all_combined_primary_key_fields($key_vals)
5589
-    {
5590
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5591
-        foreach ($keys_it_should_have as $key) {
5592
-            if (! isset($key_vals[$key])) {
5593
-                return false;
5594
-            }
5595
-        }
5596
-        return true;
5597
-    }
5598
-
5599
-
5600
-
5601
-    /**
5602
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5603
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5604
-     *
5605
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5606
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5607
-     * @throws EE_Error
5608
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5609
-     *                                                              indexed)
5610
-     */
5611
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5612
-    {
5613
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5614
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5615
-        } elseif (is_array($model_object_or_attributes_array)) {
5616
-            $attributes_array = $model_object_or_attributes_array;
5617
-        } else {
5618
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5619
-                "event_espresso"), $model_object_or_attributes_array));
5620
-        }
5621
-        //even copies obviously won't have the same ID, so remove the primary key
5622
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5623
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5624
-            unset($attributes_array[$this->primary_key_name()]);
5625
-        }
5626
-        if (isset($query_params[0])) {
5627
-            $query_params[0] = array_merge($attributes_array, $query_params);
5628
-        } else {
5629
-            $query_params[0] = $attributes_array;
5630
-        }
5631
-        return $this->get_all($query_params);
5632
-    }
5633
-
5634
-
5635
-
5636
-    /**
5637
-     * Gets the first copy we find. See get_all_copies for more details
5638
-     *
5639
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5640
-     * @param array $query_params
5641
-     * @return EE_Base_Class
5642
-     * @throws EE_Error
5643
-     */
5644
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5645
-    {
5646
-        if (! is_array($query_params)) {
5647
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5648
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5649
-                    gettype($query_params)), '4.6.0');
5650
-            $query_params = array();
5651
-        }
5652
-        $query_params['limit'] = 1;
5653
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5654
-        if (is_array($copies)) {
5655
-            return array_shift($copies);
5656
-        }
5657
-        return null;
5658
-    }
5659
-
5660
-
5661
-
5662
-    /**
5663
-     * Updates the item with the specified id. Ignores default query parameters because
5664
-     * we have specified the ID, and its assumed we KNOW what we're doing
5665
-     *
5666
-     * @param array      $fields_n_values keys are field names, values are their new values
5667
-     * @param int|string $id              the value of the primary key to update
5668
-     * @return int number of rows updated
5669
-     * @throws EE_Error
5670
-     */
5671
-    public function update_by_ID($fields_n_values, $id)
5672
-    {
5673
-        $query_params = array(
5674
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5675
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5676
-        );
5677
-        return $this->update($fields_n_values, $query_params);
5678
-    }
5679
-
5680
-
5681
-
5682
-    /**
5683
-     * Changes an operator which was supplied to the models into one usable in SQL
5684
-     *
5685
-     * @param string $operator_supplied
5686
-     * @return string an operator which can be used in SQL
5687
-     * @throws EE_Error
5688
-     */
5689
-    private function _prepare_operator_for_sql($operator_supplied)
5690
-    {
5691
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5692
-            : null;
5693
-        if ($sql_operator) {
5694
-            return $sql_operator;
5695
-        }
5696
-        throw new EE_Error(
5697
-            sprintf(
5698
-                __(
5699
-                    "The operator '%s' is not in the list of valid operators: %s",
5700
-                    "event_espresso"
5701
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5702
-            )
5703
-        );
5704
-    }
5705
-
5706
-
5707
-
5708
-    /**
5709
-     * Gets an array where keys are the primary keys and values are their 'names'
5710
-     * (as determined by the model object's name() function, which is often overridden)
5711
-     *
5712
-     * @param array $query_params like get_all's
5713
-     * @return string[]
5714
-     * @throws EE_Error
5715
-     */
5716
-    public function get_all_names($query_params = array())
5717
-    {
5718
-        $objs = $this->get_all($query_params);
5719
-        $names = array();
5720
-        foreach ($objs as $obj) {
5721
-            $names[$obj->ID()] = $obj->name();
5722
-        }
5723
-        return $names;
5724
-    }
5725
-
5726
-
5727
-
5728
-    /**
5729
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5730
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5731
-     * this is duplicated effort and reduces efficiency) you would be better to use
5732
-     * array_keys() on $model_objects.
5733
-     *
5734
-     * @param \EE_Base_Class[] $model_objects
5735
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5736
-     *                                               in the returned array
5737
-     * @return array
5738
-     * @throws EE_Error
5739
-     */
5740
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5741
-    {
5742
-        if (! $this->has_primary_key_field()) {
5743
-            if (WP_DEBUG) {
5744
-                EE_Error::add_error(
5745
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5746
-                    __FILE__,
5747
-                    __FUNCTION__,
5748
-                    __LINE__
5749
-                );
5750
-            }
5751
-        }
5752
-        $IDs = array();
5753
-        foreach ($model_objects as $model_object) {
5754
-            $id = $model_object->ID();
5755
-            if (! $id) {
5756
-                if ($filter_out_empty_ids) {
5757
-                    continue;
5758
-                }
5759
-                if (WP_DEBUG) {
5760
-                    EE_Error::add_error(
5761
-                        __(
5762
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5763
-                            'event_espresso'
5764
-                        ),
5765
-                        __FILE__,
5766
-                        __FUNCTION__,
5767
-                        __LINE__
5768
-                    );
5769
-                }
5770
-            }
5771
-            $IDs[] = $id;
5772
-        }
5773
-        return $IDs;
5774
-    }
5775
-
5776
-
5777
-
5778
-    /**
5779
-     * Returns the string used in capabilities relating to this model. If there
5780
-     * are no capabilities that relate to this model returns false
5781
-     *
5782
-     * @return string|false
5783
-     */
5784
-    public function cap_slug()
5785
-    {
5786
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5787
-    }
5788
-
5789
-
5790
-
5791
-    /**
5792
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5793
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5794
-     * only returns the cap restrictions array in that context (ie, the array
5795
-     * at that key)
5796
-     *
5797
-     * @param string $context
5798
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5799
-     * @throws EE_Error
5800
-     */
5801
-    public function cap_restrictions($context = EEM_Base::caps_read)
5802
-    {
5803
-        EEM_Base::verify_is_valid_cap_context($context);
5804
-        //check if we ought to run the restriction generator first
5805
-        if (
5806
-            isset($this->_cap_restriction_generators[$context])
5807
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5808
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5809
-        ) {
5810
-            $this->_cap_restrictions[$context] = array_merge(
5811
-                $this->_cap_restrictions[$context],
5812
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5813
-            );
5814
-        }
5815
-        //and make sure we've finalized the construction of each restriction
5816
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5817
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5818
-                $where_conditions_obj->_finalize_construct($this);
5819
-            }
5820
-        }
5821
-        return $this->_cap_restrictions[$context];
5822
-    }
5823
-
5824
-
5825
-
5826
-    /**
5827
-     * Indicating whether or not this model thinks its a wp core model
5828
-     *
5829
-     * @return boolean
5830
-     */
5831
-    public function is_wp_core_model()
5832
-    {
5833
-        return $this->_wp_core_model;
5834
-    }
5835
-
5836
-
5837
-
5838
-    /**
5839
-     * Gets all the caps that are missing which impose a restriction on
5840
-     * queries made in this context
5841
-     *
5842
-     * @param string $context one of EEM_Base::caps_ constants
5843
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5844
-     * @throws EE_Error
5845
-     */
5846
-    public function caps_missing($context = EEM_Base::caps_read)
5847
-    {
5848
-        $missing_caps = array();
5849
-        $cap_restrictions = $this->cap_restrictions($context);
5850
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5851
-            if (! EE_Capabilities::instance()
5852
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5853
-            ) {
5854
-                $missing_caps[$cap] = $restriction_if_no_cap;
5855
-            }
5856
-        }
5857
-        return $missing_caps;
5858
-    }
5859
-
5860
-
5861
-
5862
-    /**
5863
-     * Gets the mapping from capability contexts to action strings used in capability names
5864
-     *
5865
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5866
-     * one of 'read', 'edit', or 'delete'
5867
-     */
5868
-    public function cap_contexts_to_cap_action_map()
5869
-    {
5870
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5871
-            $this);
5872
-    }
5873
-
5874
-
5875
-
5876
-    /**
5877
-     * Gets the action string for the specified capability context
5878
-     *
5879
-     * @param string $context
5880
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5881
-     * @throws EE_Error
5882
-     */
5883
-    public function cap_action_for_context($context)
5884
-    {
5885
-        $mapping = $this->cap_contexts_to_cap_action_map();
5886
-        if (isset($mapping[$context])) {
5887
-            return $mapping[$context];
5888
-        }
5889
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5890
-            return $action;
5891
-        }
5892
-        throw new EE_Error(
5893
-            sprintf(
5894
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5895
-                $context,
5896
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5897
-            )
5898
-        );
5899
-    }
5900
-
5901
-
5902
-
5903
-    /**
5904
-     * Returns all the capability contexts which are valid when querying models
5905
-     *
5906
-     * @return array
5907
-     */
5908
-    public static function valid_cap_contexts()
5909
-    {
5910
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5911
-            self::caps_read,
5912
-            self::caps_read_admin,
5913
-            self::caps_edit,
5914
-            self::caps_delete,
5915
-        ));
5916
-    }
5917
-
5918
-
5919
-
5920
-    /**
5921
-     * Returns all valid options for 'default_where_conditions'
5922
-     *
5923
-     * @return array
5924
-     */
5925
-    public static function valid_default_where_conditions()
5926
-    {
5927
-        return array(
5928
-            EEM_Base::default_where_conditions_all,
5929
-            EEM_Base::default_where_conditions_this_only,
5930
-            EEM_Base::default_where_conditions_others_only,
5931
-            EEM_Base::default_where_conditions_minimum_all,
5932
-            EEM_Base::default_where_conditions_minimum_others,
5933
-            EEM_Base::default_where_conditions_none
5934
-        );
5935
-    }
5936
-
5937
-    // public static function default_where_conditions_full
5938
-    /**
5939
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5940
-     *
5941
-     * @param string $context
5942
-     * @return bool
5943
-     * @throws EE_Error
5944
-     */
5945
-    static public function verify_is_valid_cap_context($context)
5946
-    {
5947
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5948
-        if (in_array($context, $valid_cap_contexts)) {
5949
-            return true;
5950
-        }
5951
-        throw new EE_Error(
5952
-            sprintf(
5953
-                __(
5954
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5955
-                    'event_espresso'
5956
-                ),
5957
-                $context,
5958
-                'EEM_Base',
5959
-                implode(',', $valid_cap_contexts)
5960
-            )
5961
-        );
5962
-    }
5963
-
5964
-
5965
-
5966
-    /**
5967
-     * Clears all the models field caches. This is only useful when a sub-class
5968
-     * might have added a field or something and these caches might be invalidated
5969
-     */
5970
-    protected function _invalidate_field_caches()
5971
-    {
5972
-        $this->_cache_foreign_key_to_fields = array();
5973
-        $this->_cached_fields = null;
5974
-        $this->_cached_fields_non_db_only = null;
5975
-    }
5976
-
5977
-
5978
-
5979
-    /**
5980
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5981
-     * (eg "and", "or", "not").
5982
-     *
5983
-     * @return array
5984
-     */
5985
-    public function logic_query_param_keys()
5986
-    {
5987
-        return $this->_logic_query_param_keys;
5988
-    }
5989
-
5990
-
5991
-
5992
-    /**
5993
-     * Determines whether or not the where query param array key is for a logic query param.
5994
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
5995
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5996
-     *
5997
-     * @param $query_param_key
5998
-     * @return bool
5999
-     */
6000
-    public function is_logic_query_param_key($query_param_key)
6001
-    {
6002
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6003
-            if ($query_param_key === $logic_query_param_key
6004
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6005
-            ) {
6006
-                return true;
6007
-            }
6008
-        }
6009
-        return false;
6010
-    }
3739
+		}
3740
+		return $null_friendly_where_conditions;
3741
+	}
3742
+
3743
+
3744
+
3745
+	/**
3746
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3747
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3748
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3749
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3750
+	 *
3751
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3752
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3753
+	 */
3754
+	private function _get_default_where_conditions($model_relation_path = null)
3755
+	{
3756
+		if ($this->_ignore_where_strategy) {
3757
+			return array();
3758
+		}
3759
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3760
+	}
3761
+
3762
+
3763
+
3764
+	/**
3765
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3766
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3767
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3768
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3769
+	 * Similar to _get_default_where_conditions
3770
+	 *
3771
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3772
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3773
+	 */
3774
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3775
+	{
3776
+		if ($this->_ignore_where_strategy) {
3777
+			return array();
3778
+		}
3779
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3780
+	}
3781
+
3782
+
3783
+
3784
+	/**
3785
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3786
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3787
+	 *
3788
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3789
+	 * @return string
3790
+	 * @throws EE_Error
3791
+	 */
3792
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3793
+	{
3794
+		$selects = $this->_get_columns_to_select_for_this_model();
3795
+		foreach (
3796
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3797
+			$name_of_other_model_included
3798
+		) {
3799
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3800
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3801
+			foreach ($other_model_selects as $key => $value) {
3802
+				$selects[] = $value;
3803
+			}
3804
+		}
3805
+		return implode(", ", $selects);
3806
+	}
3807
+
3808
+
3809
+
3810
+	/**
3811
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3812
+	 * So that's going to be the columns for all the fields on the model
3813
+	 *
3814
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3815
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3816
+	 */
3817
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3818
+	{
3819
+		$fields = $this->field_settings();
3820
+		$selects = array();
3821
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3822
+			$this->get_this_model_name());
3823
+		foreach ($fields as $field_obj) {
3824
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3825
+						 . $field_obj->get_table_alias()
3826
+						 . "."
3827
+						 . $field_obj->get_table_column()
3828
+						 . " AS '"
3829
+						 . $table_alias_with_model_relation_chain_prefix
3830
+						 . $field_obj->get_table_alias()
3831
+						 . "."
3832
+						 . $field_obj->get_table_column()
3833
+						 . "'";
3834
+		}
3835
+		//make sure we are also getting the PKs of each table
3836
+		$tables = $this->get_tables();
3837
+		if (count($tables) > 1) {
3838
+			foreach ($tables as $table_obj) {
3839
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3840
+									   . $table_obj->get_fully_qualified_pk_column();
3841
+				if (! in_array($qualified_pk_column, $selects)) {
3842
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3843
+				}
3844
+			}
3845
+		}
3846
+		return $selects;
3847
+	}
3848
+
3849
+
3850
+
3851
+	/**
3852
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3853
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3854
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3855
+	 * SQL for joining, and the data types
3856
+	 *
3857
+	 * @param null|string                 $original_query_param
3858
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3859
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3860
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3861
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3862
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3863
+	 *                                                          or 'Registration's
3864
+	 * @param string                      $original_query_param what it originally was (eg
3865
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3866
+	 *                                                          matches $query_param
3867
+	 * @throws EE_Error
3868
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3869
+	 */
3870
+	private function _extract_related_model_info_from_query_param(
3871
+		$query_param,
3872
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3873
+		$query_param_type,
3874
+		$original_query_param = null
3875
+	) {
3876
+		if ($original_query_param === null) {
3877
+			$original_query_param = $query_param;
3878
+		}
3879
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3880
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3881
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3882
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3883
+		//check to see if we have a field on this model
3884
+		$this_model_fields = $this->field_settings(true);
3885
+		if (array_key_exists($query_param, $this_model_fields)) {
3886
+			if ($allow_fields) {
3887
+				return;
3888
+			}
3889
+			throw new EE_Error(
3890
+				sprintf(
3891
+					__(
3892
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3893
+						"event_espresso"
3894
+					),
3895
+					$query_param, get_class($this), $query_param_type, $original_query_param
3896
+				)
3897
+			);
3898
+		}
3899
+		//check if this is a special logic query param
3900
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3901
+			if ($allow_logic_query_params) {
3902
+				return;
3903
+			}
3904
+			throw new EE_Error(
3905
+				sprintf(
3906
+					__(
3907
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3908
+						'event_espresso'
3909
+					),
3910
+					implode('", "', $this->_logic_query_param_keys),
3911
+					$query_param,
3912
+					get_class($this),
3913
+					'<br />',
3914
+					"\t"
3915
+					. ' $passed_in_query_info = <pre>'
3916
+					. print_r($passed_in_query_info, true)
3917
+					. '</pre>'
3918
+					. "\n\t"
3919
+					. ' $query_param_type = '
3920
+					. $query_param_type
3921
+					. "\n\t"
3922
+					. ' $original_query_param = '
3923
+					. $original_query_param
3924
+				)
3925
+			);
3926
+		}
3927
+		//check if it's a custom selection
3928
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3929
+			return;
3930
+		}
3931
+		//check if has a model name at the beginning
3932
+		//and
3933
+		//check if it's a field on a related model
3934
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3935
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3936
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3937
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3938
+				if ($query_param === '') {
3939
+					//nothing left to $query_param
3940
+					//we should actually end in a field name, not a model like this!
3941
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3942
+						"event_espresso"),
3943
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3944
+				}
3945
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3946
+				$related_model_obj->_extract_related_model_info_from_query_param(
3947
+					$query_param,
3948
+					$passed_in_query_info, $query_param_type, $original_query_param
3949
+				);
3950
+				return;
3951
+			}
3952
+			if ($query_param === $valid_related_model_name) {
3953
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3954
+				return;
3955
+			}
3956
+		}
3957
+		//ok so $query_param didn't start with a model name
3958
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3959
+		//it's wack, that's what it is
3960
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3961
+			"event_espresso"),
3962
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3963
+	}
3964
+
3965
+
3966
+
3967
+	/**
3968
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3969
+	 * and store it on $passed_in_query_info
3970
+	 *
3971
+	 * @param string                      $model_name
3972
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3973
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3974
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3975
+	 *                                                          and are adding a join to 'Payment' with the original
3976
+	 *                                                          query param key
3977
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3978
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3979
+	 *                                                          Payment wants to add default query params so that it
3980
+	 *                                                          will know what models to prepend onto its default query
3981
+	 *                                                          params or in case it wants to rename tables (in case
3982
+	 *                                                          there are multiple joins to the same table)
3983
+	 * @return void
3984
+	 * @throws EE_Error
3985
+	 */
3986
+	private function _add_join_to_model(
3987
+		$model_name,
3988
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3989
+		$original_query_param
3990
+	) {
3991
+		$relation_obj = $this->related_settings_for($model_name);
3992
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3993
+		//check if the relation is HABTM, because then we're essentially doing two joins
3994
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3995
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3996
+			$join_model_obj = $relation_obj->get_join_model();
3997
+			//replace the model specified with the join model for this relation chain, whi
3998
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3999
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4000
+			$new_query_info = new EE_Model_Query_Info_Carrier(
4001
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4002
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
4003
+			$passed_in_query_info->merge($new_query_info);
4004
+		}
4005
+		//now just join to the other table pointed to by the relation object, and add its data types
4006
+		$new_query_info = new EE_Model_Query_Info_Carrier(
4007
+			array($model_relation_chain => $model_name),
4008
+			$relation_obj->get_join_statement($model_relation_chain));
4009
+		$passed_in_query_info->merge($new_query_info);
4010
+	}
4011
+
4012
+
4013
+
4014
+	/**
4015
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4016
+	 *
4017
+	 * @param array $where_params like EEM_Base::get_all
4018
+	 * @return string of SQL
4019
+	 * @throws EE_Error
4020
+	 */
4021
+	private function _construct_where_clause($where_params)
4022
+	{
4023
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4024
+		if ($SQL) {
4025
+			return " WHERE " . $SQL;
4026
+		}
4027
+		return '';
4028
+	}
4029
+
4030
+
4031
+
4032
+	/**
4033
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4034
+	 * and should be passed HAVING parameters, not WHERE parameters
4035
+	 *
4036
+	 * @param array $having_params
4037
+	 * @return string
4038
+	 * @throws EE_Error
4039
+	 */
4040
+	private function _construct_having_clause($having_params)
4041
+	{
4042
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4043
+		if ($SQL) {
4044
+			return " HAVING " . $SQL;
4045
+		}
4046
+		return '';
4047
+	}
4048
+
4049
+
4050
+
4051
+	/**
4052
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
4053
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
4054
+	 * EEM_Attendee.
4055
+	 *
4056
+	 * @param string $field_name
4057
+	 * @param string $model_name
4058
+	 * @return EE_Model_Field_Base
4059
+	 * @throws EE_Error
4060
+	 */
4061
+	protected function _get_field_on_model($field_name, $model_name)
4062
+	{
4063
+		$model_class = 'EEM_' . $model_name;
4064
+		$model_filepath = $model_class . ".model.php";
4065
+		if (is_readable($model_filepath)) {
4066
+			require_once($model_filepath);
4067
+			$model_instance = call_user_func($model_name . "::instance");
4068
+			/* @var $model_instance EEM_Base */
4069
+			return $model_instance->field_settings_for($field_name);
4070
+		}
4071
+		throw new EE_Error(
4072
+			sprintf(
4073
+				__(
4074
+					'No model named %s exists, with classname %s and filepath %s',
4075
+					'event_espresso'
4076
+				), $model_name, $model_class, $model_filepath
4077
+			)
4078
+		);
4079
+	}
4080
+
4081
+
4082
+
4083
+	/**
4084
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4085
+	 * Event_Meta.meta_value = 'foo'))"
4086
+	 *
4087
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4088
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4089
+	 * @throws EE_Error
4090
+	 * @return string of SQL
4091
+	 */
4092
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4093
+	{
4094
+		$where_clauses = array();
4095
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4096
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4097
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4098
+				switch ($query_param) {
4099
+					case 'not':
4100
+					case 'NOT':
4101
+						$where_clauses[] = "! ("
4102
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4103
+								$glue)
4104
+										   . ")";
4105
+						break;
4106
+					case 'and':
4107
+					case 'AND':
4108
+						$where_clauses[] = " ("
4109
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4110
+								' AND ')
4111
+										   . ")";
4112
+						break;
4113
+					case 'or':
4114
+					case 'OR':
4115
+						$where_clauses[] = " ("
4116
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4117
+								' OR ')
4118
+										   . ")";
4119
+						break;
4120
+				}
4121
+			} else {
4122
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4123
+				//if it's not a normal field, maybe it's a custom selection?
4124
+				if (! $field_obj) {
4125
+					if (isset($this->_custom_selections[$query_param][1])) {
4126
+						$field_obj = $this->_custom_selections[$query_param][1];
4127
+					} else {
4128
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4129
+							"event_espresso"), $query_param));
4130
+					}
4131
+				}
4132
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4133
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4134
+			}
4135
+		}
4136
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4137
+	}
4138
+
4139
+
4140
+
4141
+	/**
4142
+	 * Takes the input parameter and extract the table name (alias) and column name
4143
+	 *
4144
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4145
+	 * @throws EE_Error
4146
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4147
+	 */
4148
+	private function _deduce_column_name_from_query_param($query_param)
4149
+	{
4150
+		$field = $this->_deduce_field_from_query_param($query_param);
4151
+		if ($field) {
4152
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4153
+				$query_param);
4154
+			return $table_alias_prefix . $field->get_qualified_column();
4155
+		}
4156
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4157
+			//maybe it's custom selection item?
4158
+			//if so, just use it as the "column name"
4159
+			return $query_param;
4160
+		}
4161
+		throw new EE_Error(
4162
+			sprintf(
4163
+				__(
4164
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4165
+					"event_espresso"
4166
+				), $query_param, implode(",", $this->_custom_selections)
4167
+			)
4168
+		);
4169
+	}
4170
+
4171
+
4172
+
4173
+	/**
4174
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4175
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4176
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4177
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4178
+	 *
4179
+	 * @param string $condition_query_param_key
4180
+	 * @return string
4181
+	 */
4182
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4183
+	{
4184
+		$pos_of_star = strpos($condition_query_param_key, '*');
4185
+		if ($pos_of_star === false) {
4186
+			return $condition_query_param_key;
4187
+		}
4188
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4189
+		return $condition_query_param_sans_star;
4190
+	}
4191
+
4192
+
4193
+
4194
+	/**
4195
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4196
+	 *
4197
+	 * @param                            mixed      array | string    $op_and_value
4198
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4199
+	 * @throws EE_Error
4200
+	 * @return string
4201
+	 */
4202
+	private function _construct_op_and_value($op_and_value, $field_obj)
4203
+	{
4204
+		if (is_array($op_and_value)) {
4205
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4206
+			if (! $operator) {
4207
+				$php_array_like_string = array();
4208
+				foreach ($op_and_value as $key => $value) {
4209
+					$php_array_like_string[] = "$key=>$value";
4210
+				}
4211
+				throw new EE_Error(
4212
+					sprintf(
4213
+						__(
4214
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4215
+							"event_espresso"
4216
+						),
4217
+						implode(",", $php_array_like_string)
4218
+					)
4219
+				);
4220
+			}
4221
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4222
+		} else {
4223
+			$operator = '=';
4224
+			$value = $op_and_value;
4225
+		}
4226
+		//check to see if the value is actually another field
4227
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4228
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4229
+		}
4230
+		if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4231
+			//in this case, the value should be an array, or at least a comma-separated list
4232
+			//it will need to handle a little differently
4233
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4234
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4235
+			return $operator . SP . $cleaned_value;
4236
+		}
4237
+		if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4238
+			//the value should be an array with count of two.
4239
+			if (count($value) !== 2) {
4240
+				throw new EE_Error(
4241
+					sprintf(
4242
+						__(
4243
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4244
+							'event_espresso'
4245
+						),
4246
+						"BETWEEN"
4247
+					)
4248
+				);
4249
+			}
4250
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4251
+			return $operator . SP . $cleaned_value;
4252
+		}
4253
+		if (in_array($operator, $this->_null_style_operators)) {
4254
+			if ($value !== null) {
4255
+				throw new EE_Error(
4256
+					sprintf(
4257
+						__(
4258
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4259
+							"event_espresso"
4260
+						),
4261
+						$value,
4262
+						$operator
4263
+					)
4264
+				);
4265
+			}
4266
+			return $operator;
4267
+		}
4268
+		if ($operator === 'LIKE' && ! is_array($value)) {
4269
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4270
+			//remove other junk. So just treat it as a string.
4271
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4272
+		}
4273
+		if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4274
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4275
+		}
4276
+		if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4277
+			throw new EE_Error(
4278
+				sprintf(
4279
+					__(
4280
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4281
+						'event_espresso'
4282
+					),
4283
+					$operator,
4284
+					$operator
4285
+				)
4286
+			);
4287
+		}
4288
+		if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4289
+			throw new EE_Error(
4290
+				sprintf(
4291
+					__(
4292
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4293
+						'event_espresso'
4294
+					),
4295
+					$operator,
4296
+					$operator
4297
+				)
4298
+			);
4299
+		}
4300
+		throw new EE_Error(
4301
+			sprintf(
4302
+				__(
4303
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4304
+					"event_espresso"
4305
+				),
4306
+				http_build_query($op_and_value)
4307
+			)
4308
+		);
4309
+	}
4310
+
4311
+
4312
+
4313
+	/**
4314
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4315
+	 *
4316
+	 * @param array                      $values
4317
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4318
+	 *                                              '%s'
4319
+	 * @return string
4320
+	 * @throws EE_Error
4321
+	 */
4322
+	public function _construct_between_value($values, $field_obj)
4323
+	{
4324
+		$cleaned_values = array();
4325
+		foreach ($values as $value) {
4326
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4327
+		}
4328
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4329
+	}
4330
+
4331
+
4332
+
4333
+	/**
4334
+	 * Takes an array or a comma-separated list of $values and cleans them
4335
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4336
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4337
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4338
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4339
+	 *
4340
+	 * @param mixed                      $values    array or comma-separated string
4341
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4342
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4343
+	 * @throws EE_Error
4344
+	 */
4345
+	public function _construct_in_value($values, $field_obj)
4346
+	{
4347
+		//check if the value is a CSV list
4348
+		if (is_string($values)) {
4349
+			//in which case, turn it into an array
4350
+			$values = explode(",", $values);
4351
+		}
4352
+		$cleaned_values = array();
4353
+		foreach ($values as $value) {
4354
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4355
+		}
4356
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4357
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4358
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4359
+		if (empty($cleaned_values)) {
4360
+			$all_fields = $this->field_settings();
4361
+			$a_field = array_shift($all_fields);
4362
+			$main_table = $this->_get_main_table();
4363
+			$cleaned_values[] = "SELECT "
4364
+								. $a_field->get_table_column()
4365
+								. " FROM "
4366
+								. $main_table->get_table_name()
4367
+								. " WHERE FALSE";
4368
+		}
4369
+		return "(" . implode(",", $cleaned_values) . ")";
4370
+	}
4371
+
4372
+
4373
+
4374
+	/**
4375
+	 * @param mixed                      $value
4376
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4377
+	 * @throws EE_Error
4378
+	 * @return false|null|string
4379
+	 */
4380
+	private function _wpdb_prepare_using_field($value, $field_obj)
4381
+	{
4382
+		/** @type WPDB $wpdb */
4383
+		global $wpdb;
4384
+		if ($field_obj instanceof EE_Model_Field_Base) {
4385
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4386
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4387
+		} //$field_obj should really just be a data type
4388
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4389
+			throw new EE_Error(
4390
+				sprintf(
4391
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4392
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4393
+				)
4394
+			);
4395
+		}
4396
+		return $wpdb->prepare($field_obj, $value);
4397
+	}
4398
+
4399
+
4400
+
4401
+	/**
4402
+	 * Takes the input parameter and finds the model field that it indicates.
4403
+	 *
4404
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4405
+	 * @throws EE_Error
4406
+	 * @return EE_Model_Field_Base
4407
+	 */
4408
+	protected function _deduce_field_from_query_param($query_param_name)
4409
+	{
4410
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4411
+		//which will help us find the database table and column
4412
+		$query_param_parts = explode(".", $query_param_name);
4413
+		if (empty($query_param_parts)) {
4414
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4415
+				'event_espresso'), $query_param_name));
4416
+		}
4417
+		$number_of_parts = count($query_param_parts);
4418
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4419
+		if ($number_of_parts === 1) {
4420
+			$field_name = $last_query_param_part;
4421
+			$model_obj = $this;
4422
+		} else {// $number_of_parts >= 2
4423
+			//the last part is the column name, and there are only 2parts. therefore...
4424
+			$field_name = $last_query_param_part;
4425
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4426
+		}
4427
+		try {
4428
+			return $model_obj->field_settings_for($field_name);
4429
+		} catch (EE_Error $e) {
4430
+			return null;
4431
+		}
4432
+	}
4433
+
4434
+
4435
+
4436
+	/**
4437
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4438
+	 * alias and column which corresponds to it
4439
+	 *
4440
+	 * @param string $field_name
4441
+	 * @throws EE_Error
4442
+	 * @return string
4443
+	 */
4444
+	public function _get_qualified_column_for_field($field_name)
4445
+	{
4446
+		$all_fields = $this->field_settings();
4447
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4448
+		if ($field) {
4449
+			return $field->get_qualified_column();
4450
+		}
4451
+		throw new EE_Error(
4452
+			sprintf(
4453
+				__(
4454
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4455
+					'event_espresso'
4456
+				), $field_name, get_class($this)
4457
+			)
4458
+		);
4459
+	}
4460
+
4461
+
4462
+
4463
+	/**
4464
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4465
+	 * Example usage:
4466
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4467
+	 *      array(),
4468
+	 *      ARRAY_A,
4469
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4470
+	 *  );
4471
+	 * is equivalent to
4472
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4473
+	 * and
4474
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4475
+	 *      array(
4476
+	 *          array(
4477
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4478
+	 *          ),
4479
+	 *          ARRAY_A,
4480
+	 *          implode(
4481
+	 *              ', ',
4482
+	 *              array_merge(
4483
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4484
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4485
+	 *              )
4486
+	 *          )
4487
+	 *      )
4488
+	 *  );
4489
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4490
+	 *
4491
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4492
+	 *                                            and the one whose fields you are selecting for example: when querying
4493
+	 *                                            tickets model and selecting fields from the tickets model you would
4494
+	 *                                            leave this parameter empty, because no models are needed to join
4495
+	 *                                            between the queried model and the selected one. Likewise when
4496
+	 *                                            querying the datetime model and selecting fields from the tickets
4497
+	 *                                            model, it would also be left empty, because there is a direct
4498
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4499
+	 *                                            them together. However, when querying from the event model and
4500
+	 *                                            selecting fields from the ticket model, you should provide the string
4501
+	 *                                            'Datetime', indicating that the event model must first join to the
4502
+	 *                                            datetime model in order to find its relation to ticket model.
4503
+	 *                                            Also, when querying from the venue model and selecting fields from
4504
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4505
+	 *                                            indicating you need to join the venue model to the event model,
4506
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4507
+	 *                                            This string is used to deduce the prefix that gets added onto the
4508
+	 *                                            models' tables qualified columns
4509
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4510
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4511
+	 *                                            qualified column names
4512
+	 * @return array|string
4513
+	 */
4514
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4515
+	{
4516
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4517
+		$qualified_columns = array();
4518
+		foreach ($this->field_settings() as $field_name => $field) {
4519
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4520
+		}
4521
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4522
+	}
4523
+
4524
+
4525
+
4526
+	/**
4527
+	 * constructs the select use on special limit joins
4528
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4529
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4530
+	 * (as that is typically where the limits would be set).
4531
+	 *
4532
+	 * @param  string       $table_alias The table the select is being built for
4533
+	 * @param  mixed|string $limit       The limit for this select
4534
+	 * @return string                The final select join element for the query.
4535
+	 */
4536
+	public function _construct_limit_join_select($table_alias, $limit)
4537
+	{
4538
+		$SQL = '';
4539
+		foreach ($this->_tables as $table_obj) {
4540
+			if ($table_obj instanceof EE_Primary_Table) {
4541
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4542
+					? $table_obj->get_select_join_limit($limit)
4543
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4544
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4545
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4546
+					? $table_obj->get_select_join_limit_join($limit)
4547
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4548
+			}
4549
+		}
4550
+		return $SQL;
4551
+	}
4552
+
4553
+
4554
+
4555
+	/**
4556
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4557
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4558
+	 *
4559
+	 * @return string SQL
4560
+	 * @throws EE_Error
4561
+	 */
4562
+	public function _construct_internal_join()
4563
+	{
4564
+		$SQL = $this->_get_main_table()->get_table_sql();
4565
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4566
+		return $SQL;
4567
+	}
4568
+
4569
+
4570
+
4571
+	/**
4572
+	 * Constructs the SQL for joining all the tables on this model.
4573
+	 * Normally $alias should be the primary table's alias, but in cases where
4574
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4575
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4576
+	 * alias, this will construct SQL like:
4577
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4578
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4579
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4580
+	 *
4581
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4582
+	 * @return string
4583
+	 */
4584
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4585
+	{
4586
+		$SQL = '';
4587
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4588
+		foreach ($this->_tables as $table_obj) {
4589
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4590
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4591
+					//so we're joining to this table, meaning the table is already in
4592
+					//the FROM statement, BUT the primary table isn't. So we want
4593
+					//to add the inverse join sql
4594
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4595
+				} else {
4596
+					//just add a regular JOIN to this table from the primary table
4597
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4598
+				}
4599
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4600
+		}
4601
+		return $SQL;
4602
+	}
4603
+
4604
+
4605
+
4606
+	/**
4607
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4608
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4609
+	 * their data type (eg, '%s', '%d', etc)
4610
+	 *
4611
+	 * @return array
4612
+	 */
4613
+	public function _get_data_types()
4614
+	{
4615
+		$data_types = array();
4616
+		foreach ($this->field_settings() as $field_obj) {
4617
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4618
+			/** @var $field_obj EE_Model_Field_Base */
4619
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4620
+		}
4621
+		return $data_types;
4622
+	}
4623
+
4624
+
4625
+
4626
+	/**
4627
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4628
+	 *
4629
+	 * @param string $model_name
4630
+	 * @throws EE_Error
4631
+	 * @return EEM_Base
4632
+	 */
4633
+	public function get_related_model_obj($model_name)
4634
+	{
4635
+		$model_classname = "EEM_" . $model_name;
4636
+		if (! class_exists($model_classname)) {
4637
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4638
+				'event_espresso'), $model_name, $model_classname));
4639
+		}
4640
+		return call_user_func($model_classname . "::instance");
4641
+	}
4642
+
4643
+
4644
+
4645
+	/**
4646
+	 * Returns the array of EE_ModelRelations for this model.
4647
+	 *
4648
+	 * @return EE_Model_Relation_Base[]
4649
+	 */
4650
+	public function relation_settings()
4651
+	{
4652
+		return $this->_model_relations;
4653
+	}
4654
+
4655
+
4656
+
4657
+	/**
4658
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4659
+	 * because without THOSE models, this model probably doesn't have much purpose.
4660
+	 * (Eg, without an event, datetimes have little purpose.)
4661
+	 *
4662
+	 * @return EE_Belongs_To_Relation[]
4663
+	 */
4664
+	public function belongs_to_relations()
4665
+	{
4666
+		$belongs_to_relations = array();
4667
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4668
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4669
+				$belongs_to_relations[$model_name] = $relation_obj;
4670
+			}
4671
+		}
4672
+		return $belongs_to_relations;
4673
+	}
4674
+
4675
+
4676
+
4677
+	/**
4678
+	 * Returns the specified EE_Model_Relation, or throws an exception
4679
+	 *
4680
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4681
+	 * @throws EE_Error
4682
+	 * @return EE_Model_Relation_Base
4683
+	 */
4684
+	public function related_settings_for($relation_name)
4685
+	{
4686
+		$relatedModels = $this->relation_settings();
4687
+		if (! array_key_exists($relation_name, $relatedModels)) {
4688
+			throw new EE_Error(
4689
+				sprintf(
4690
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4691
+						'event_espresso'),
4692
+					$relation_name,
4693
+					$this->_get_class_name(),
4694
+					implode(', ', array_keys($relatedModels))
4695
+				)
4696
+			);
4697
+		}
4698
+		return $relatedModels[$relation_name];
4699
+	}
4700
+
4701
+
4702
+
4703
+	/**
4704
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4705
+	 * fields
4706
+	 *
4707
+	 * @param string $fieldName
4708
+	 * @throws EE_Error
4709
+	 * @return EE_Model_Field_Base
4710
+	 */
4711
+	public function field_settings_for($fieldName)
4712
+	{
4713
+		$fieldSettings = $this->field_settings(true);
4714
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4715
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4716
+				get_class($this)));
4717
+		}
4718
+		return $fieldSettings[$fieldName];
4719
+	}
4720
+
4721
+
4722
+
4723
+	/**
4724
+	 * Checks if this field exists on this model
4725
+	 *
4726
+	 * @param string $fieldName a key in the model's _field_settings array
4727
+	 * @return boolean
4728
+	 */
4729
+	public function has_field($fieldName)
4730
+	{
4731
+		$fieldSettings = $this->field_settings(true);
4732
+		if (isset($fieldSettings[$fieldName])) {
4733
+			return true;
4734
+		}
4735
+		return false;
4736
+	}
4737
+
4738
+
4739
+
4740
+	/**
4741
+	 * Returns whether or not this model has a relation to the specified model
4742
+	 *
4743
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4744
+	 * @return boolean
4745
+	 */
4746
+	public function has_relation($relation_name)
4747
+	{
4748
+		$relations = $this->relation_settings();
4749
+		if (isset($relations[$relation_name])) {
4750
+			return true;
4751
+		}
4752
+		return false;
4753
+	}
4754
+
4755
+
4756
+
4757
+	/**
4758
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4759
+	 * Eg, on EE_Answer that would be ANS_ID field object
4760
+	 *
4761
+	 * @param $field_obj
4762
+	 * @return boolean
4763
+	 */
4764
+	public function is_primary_key_field($field_obj)
4765
+	{
4766
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4773
+	 * Eg, on EE_Answer that would be ANS_ID field object
4774
+	 *
4775
+	 * @return EE_Model_Field_Base
4776
+	 * @throws EE_Error
4777
+	 */
4778
+	public function get_primary_key_field()
4779
+	{
4780
+		if ($this->_primary_key_field === null) {
4781
+			foreach ($this->field_settings(true) as $field_obj) {
4782
+				if ($this->is_primary_key_field($field_obj)) {
4783
+					$this->_primary_key_field = $field_obj;
4784
+					break;
4785
+				}
4786
+			}
4787
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4788
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4789
+					get_class($this)));
4790
+			}
4791
+		}
4792
+		return $this->_primary_key_field;
4793
+	}
4794
+
4795
+
4796
+
4797
+	/**
4798
+	 * Returns whether or not not there is a primary key on this model.
4799
+	 * Internally does some caching.
4800
+	 *
4801
+	 * @return boolean
4802
+	 */
4803
+	public function has_primary_key_field()
4804
+	{
4805
+		if ($this->_has_primary_key_field === null) {
4806
+			try {
4807
+				$this->get_primary_key_field();
4808
+				$this->_has_primary_key_field = true;
4809
+			} catch (EE_Error $e) {
4810
+				$this->_has_primary_key_field = false;
4811
+			}
4812
+		}
4813
+		return $this->_has_primary_key_field;
4814
+	}
4815
+
4816
+
4817
+
4818
+	/**
4819
+	 * Finds the first field of type $field_class_name.
4820
+	 *
4821
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4822
+	 *                                 EE_Foreign_Key_Field, etc
4823
+	 * @return EE_Model_Field_Base or null if none is found
4824
+	 */
4825
+	public function get_a_field_of_type($field_class_name)
4826
+	{
4827
+		foreach ($this->field_settings() as $field) {
4828
+			if ($field instanceof $field_class_name) {
4829
+				return $field;
4830
+			}
4831
+		}
4832
+		return null;
4833
+	}
4834
+
4835
+
4836
+
4837
+	/**
4838
+	 * Gets a foreign key field pointing to model.
4839
+	 *
4840
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4841
+	 * @return EE_Foreign_Key_Field_Base
4842
+	 * @throws EE_Error
4843
+	 */
4844
+	public function get_foreign_key_to($model_name)
4845
+	{
4846
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4847
+			foreach ($this->field_settings() as $field) {
4848
+				if (
4849
+					$field instanceof EE_Foreign_Key_Field_Base
4850
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4851
+				) {
4852
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4853
+					break;
4854
+				}
4855
+			}
4856
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4857
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4858
+					'event_espresso'), $model_name, get_class($this)));
4859
+			}
4860
+		}
4861
+		return $this->_cache_foreign_key_to_fields[$model_name];
4862
+	}
4863
+
4864
+
4865
+
4866
+	/**
4867
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4868
+	 *
4869
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4870
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4871
+	 *                            Either one works
4872
+	 * @return string
4873
+	 */
4874
+	public function get_table_for_alias($table_alias)
4875
+	{
4876
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4877
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4878
+	}
4879
+
4880
+
4881
+
4882
+	/**
4883
+	 * Returns a flat array of all field son this model, instead of organizing them
4884
+	 * by table_alias as they are in the constructor.
4885
+	 *
4886
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4887
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4888
+	 */
4889
+	public function field_settings($include_db_only_fields = false)
4890
+	{
4891
+		if ($include_db_only_fields) {
4892
+			if ($this->_cached_fields === null) {
4893
+				$this->_cached_fields = array();
4894
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4895
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4896
+						$this->_cached_fields[$field_name] = $field_obj;
4897
+					}
4898
+				}
4899
+			}
4900
+			return $this->_cached_fields;
4901
+		}
4902
+		if ($this->_cached_fields_non_db_only === null) {
4903
+			$this->_cached_fields_non_db_only = array();
4904
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4905
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4906
+					/** @var $field_obj EE_Model_Field_Base */
4907
+					if (! $field_obj->is_db_only_field()) {
4908
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4909
+					}
4910
+				}
4911
+			}
4912
+		}
4913
+		return $this->_cached_fields_non_db_only;
4914
+	}
4915
+
4916
+
4917
+
4918
+	/**
4919
+	 *        cycle though array of attendees and create objects out of each item
4920
+	 *
4921
+	 * @access        private
4922
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4923
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4924
+	 *                           numerically indexed)
4925
+	 * @throws EE_Error
4926
+	 */
4927
+	protected function _create_objects($rows = array())
4928
+	{
4929
+		$array_of_objects = array();
4930
+		if (empty($rows)) {
4931
+			return array();
4932
+		}
4933
+		$count_if_model_has_no_primary_key = 0;
4934
+		$has_primary_key = $this->has_primary_key_field();
4935
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4936
+		foreach ((array)$rows as $row) {
4937
+			if (empty($row)) {
4938
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4939
+				return array();
4940
+			}
4941
+			//check if we've already set this object in the results array,
4942
+			//in which case there's no need to process it further (again)
4943
+			if ($has_primary_key) {
4944
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4945
+					$row,
4946
+					$primary_key_field->get_qualified_column(),
4947
+					$primary_key_field->get_table_column()
4948
+				);
4949
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4950
+					continue;
4951
+				}
4952
+			}
4953
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4954
+			if (! $classInstance) {
4955
+				throw new EE_Error(
4956
+					sprintf(
4957
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4958
+						$this->get_this_model_name(),
4959
+						http_build_query($row)
4960
+					)
4961
+				);
4962
+			}
4963
+			//set the timezone on the instantiated objects
4964
+			$classInstance->set_timezone($this->_timezone);
4965
+			//make sure if there is any timezone setting present that we set the timezone for the object
4966
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4967
+			$array_of_objects[$key] = $classInstance;
4968
+			//also, for all the relations of type BelongsTo, see if we can cache
4969
+			//those related models
4970
+			//(we could do this for other relations too, but if there are conditions
4971
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4972
+			//so it requires a little more thought than just caching them immediately...)
4973
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4974
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4975
+					//check if this model's INFO is present. If so, cache it on the model
4976
+					$other_model = $relation_obj->get_other_model();
4977
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4978
+					//if we managed to make a model object from the results, cache it on the main model object
4979
+					if ($other_model_obj_maybe) {
4980
+						//set timezone on these other model objects if they are present
4981
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4982
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4983
+					}
4984
+				}
4985
+			}
4986
+		}
4987
+		return $array_of_objects;
4988
+	}
4989
+
4990
+
4991
+
4992
+	/**
4993
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4994
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4995
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4996
+	 * object (as set in the model_field!).
4997
+	 *
4998
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4999
+	 */
5000
+	public function create_default_object()
5001
+	{
5002
+		$this_model_fields_and_values = array();
5003
+		//setup the row using default values;
5004
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5005
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5006
+		}
5007
+		$className = $this->_get_class_name();
5008
+		$classInstance = EE_Registry::instance()
5009
+									->load_class($className, array($this_model_fields_and_values), false, false);
5010
+		return $classInstance;
5011
+	}
5012
+
5013
+
5014
+
5015
+	/**
5016
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5017
+	 *                             or an stdClass where each property is the name of a column,
5018
+	 * @return EE_Base_Class
5019
+	 * @throws EE_Error
5020
+	 */
5021
+	public function instantiate_class_from_array_or_object($cols_n_values)
5022
+	{
5023
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5024
+			$cols_n_values = get_object_vars($cols_n_values);
5025
+		}
5026
+		$primary_key = null;
5027
+		//make sure the array only has keys that are fields/columns on this model
5028
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5029
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5030
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5031
+		}
5032
+		$className = $this->_get_class_name();
5033
+		//check we actually found results that we can use to build our model object
5034
+		//if not, return null
5035
+		if ($this->has_primary_key_field()) {
5036
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5037
+				return null;
5038
+			}
5039
+		} else if ($this->unique_indexes()) {
5040
+			$first_column = reset($this_model_fields_n_values);
5041
+			if (empty($first_column)) {
5042
+				return null;
5043
+			}
5044
+		}
5045
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5046
+		if ($primary_key) {
5047
+			$classInstance = $this->get_from_entity_map($primary_key);
5048
+			if (! $classInstance) {
5049
+				$classInstance = EE_Registry::instance()
5050
+											->load_class($className,
5051
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5052
+				// add this new object to the entity map
5053
+				$classInstance = $this->add_to_entity_map($classInstance);
5054
+			}
5055
+		} else {
5056
+			$classInstance = EE_Registry::instance()
5057
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5058
+											true, false);
5059
+		}
5060
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
5061
+		$this->set_timezone($classInstance->get_timezone());
5062
+		return $classInstance;
5063
+	}
5064
+
5065
+
5066
+
5067
+	/**
5068
+	 * Gets the model object from the  entity map if it exists
5069
+	 *
5070
+	 * @param int|string $id the ID of the model object
5071
+	 * @return EE_Base_Class
5072
+	 */
5073
+	public function get_from_entity_map($id)
5074
+	{
5075
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5076
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5077
+	}
5078
+
5079
+
5080
+
5081
+	/**
5082
+	 * add_to_entity_map
5083
+	 * Adds the object to the model's entity mappings
5084
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5085
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5086
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5087
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5088
+	 *        then this method should be called immediately after the update query
5089
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5090
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5091
+	 *
5092
+	 * @param    EE_Base_Class $object
5093
+	 * @throws EE_Error
5094
+	 * @return \EE_Base_Class
5095
+	 */
5096
+	public function add_to_entity_map(EE_Base_Class $object)
5097
+	{
5098
+		$className = $this->_get_class_name();
5099
+		if (! $object instanceof $className) {
5100
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5101
+				is_object($object) ? get_class($object) : $object, $className));
5102
+		}
5103
+		/** @var $object EE_Base_Class */
5104
+		if (! $object->ID()) {
5105
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5106
+				"event_espresso"), get_class($this)));
5107
+		}
5108
+		// double check it's not already there
5109
+		$classInstance = $this->get_from_entity_map($object->ID());
5110
+		if ($classInstance) {
5111
+			return $classInstance;
5112
+		}
5113
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5114
+		return $object;
5115
+	}
5116
+
5117
+
5118
+
5119
+	/**
5120
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5121
+	 * if no identifier is provided, then the entire entity map is emptied
5122
+	 *
5123
+	 * @param int|string $id the ID of the model object
5124
+	 * @return boolean
5125
+	 */
5126
+	public function clear_entity_map($id = null)
5127
+	{
5128
+		if (empty($id)) {
5129
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5130
+			return true;
5131
+		}
5132
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5133
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5134
+			return true;
5135
+		}
5136
+		return false;
5137
+	}
5138
+
5139
+
5140
+
5141
+	/**
5142
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5143
+	 * Given an array where keys are column (or column alias) names and values,
5144
+	 * returns an array of their corresponding field names and database values
5145
+	 *
5146
+	 * @param array $cols_n_values
5147
+	 * @return array
5148
+	 */
5149
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5150
+	{
5151
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5152
+	}
5153
+
5154
+
5155
+
5156
+	/**
5157
+	 * _deduce_fields_n_values_from_cols_n_values
5158
+	 * Given an array where keys are column (or column alias) names and values,
5159
+	 * returns an array of their corresponding field names and database values
5160
+	 *
5161
+	 * @param string $cols_n_values
5162
+	 * @return array
5163
+	 */
5164
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5165
+	{
5166
+		$this_model_fields_n_values = array();
5167
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5168
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5169
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5170
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5171
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5172
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5173
+					if (! $field_obj->is_db_only_field()) {
5174
+						//prepare field as if its coming from db
5175
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5176
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5177
+					}
5178
+				}
5179
+			} else {
5180
+				//the table's rows existed. Use their values
5181
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5182
+					if (! $field_obj->is_db_only_field()) {
5183
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5184
+							$cols_n_values, $field_obj->get_qualified_column(),
5185
+							$field_obj->get_table_column()
5186
+						);
5187
+					}
5188
+				}
5189
+			}
5190
+		}
5191
+		return $this_model_fields_n_values;
5192
+	}
5193
+
5194
+
5195
+
5196
+	/**
5197
+	 * @param $cols_n_values
5198
+	 * @param $qualified_column
5199
+	 * @param $regular_column
5200
+	 * @return null
5201
+	 */
5202
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5203
+	{
5204
+		$value = null;
5205
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5206
+		//does the field on the model relate to this column retrieved from the db?
5207
+		//or is it a db-only field? (not relating to the model)
5208
+		if (isset($cols_n_values[$qualified_column])) {
5209
+			$value = $cols_n_values[$qualified_column];
5210
+		} elseif (isset($cols_n_values[$regular_column])) {
5211
+			$value = $cols_n_values[$regular_column];
5212
+		}
5213
+		return $value;
5214
+	}
5215
+
5216
+
5217
+
5218
+	/**
5219
+	 * refresh_entity_map_from_db
5220
+	 * Makes sure the model object in the entity map at $id assumes the values
5221
+	 * of the database (opposite of EE_base_Class::save())
5222
+	 *
5223
+	 * @param int|string $id
5224
+	 * @return EE_Base_Class
5225
+	 * @throws EE_Error
5226
+	 */
5227
+	public function refresh_entity_map_from_db($id)
5228
+	{
5229
+		$obj_in_map = $this->get_from_entity_map($id);
5230
+		if ($obj_in_map) {
5231
+			$wpdb_results = $this->_get_all_wpdb_results(
5232
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5233
+			);
5234
+			if ($wpdb_results && is_array($wpdb_results)) {
5235
+				$one_row = reset($wpdb_results);
5236
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5237
+					$obj_in_map->set_from_db($field_name, $db_value);
5238
+				}
5239
+				//clear the cache of related model objects
5240
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5241
+					$obj_in_map->clear_cache($relation_name, null, true);
5242
+				}
5243
+			}
5244
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5245
+			return $obj_in_map;
5246
+		}
5247
+		return $this->get_one_by_ID($id);
5248
+	}
5249
+
5250
+
5251
+
5252
+	/**
5253
+	 * refresh_entity_map_with
5254
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5255
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5256
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5257
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5258
+	 *
5259
+	 * @param int|string    $id
5260
+	 * @param EE_Base_Class $replacing_model_obj
5261
+	 * @return \EE_Base_Class
5262
+	 * @throws EE_Error
5263
+	 */
5264
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5265
+	{
5266
+		$obj_in_map = $this->get_from_entity_map($id);
5267
+		if ($obj_in_map) {
5268
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5269
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5270
+					$obj_in_map->set($field_name, $value);
5271
+				}
5272
+				//make the model object in the entity map's cache match the $replacing_model_obj
5273
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5274
+					$obj_in_map->clear_cache($relation_name, null, true);
5275
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5276
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5277
+					}
5278
+				}
5279
+			}
5280
+			return $obj_in_map;
5281
+		}
5282
+		$this->add_to_entity_map($replacing_model_obj);
5283
+		return $replacing_model_obj;
5284
+	}
5285
+
5286
+
5287
+
5288
+	/**
5289
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5290
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5291
+	 * require_once($this->_getClassName().".class.php");
5292
+	 *
5293
+	 * @return string
5294
+	 */
5295
+	private function _get_class_name()
5296
+	{
5297
+		return "EE_" . $this->get_this_model_name();
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5304
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5305
+	 * it would be 'Events'.
5306
+	 *
5307
+	 * @param int $quantity
5308
+	 * @return string
5309
+	 */
5310
+	public function item_name($quantity = 1)
5311
+	{
5312
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5313
+	}
5314
+
5315
+
5316
+
5317
+	/**
5318
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5319
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5320
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5321
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5322
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5323
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5324
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5325
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5326
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5327
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5328
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5329
+	 *        return $previousReturnValue.$returnString;
5330
+	 * }
5331
+	 * require('EEM_Answer.model.php');
5332
+	 * $answer=EEM_Answer::instance();
5333
+	 * echo $answer->my_callback('monkeys',100);
5334
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5335
+	 *
5336
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5337
+	 * @param array  $args       array of original arguments passed to the function
5338
+	 * @throws EE_Error
5339
+	 * @return mixed whatever the plugin which calls add_filter decides
5340
+	 */
5341
+	public function __call($methodName, $args)
5342
+	{
5343
+		$className = get_class($this);
5344
+		$tagName = "FHEE__{$className}__{$methodName}";
5345
+		if (! has_filter($tagName)) {
5346
+			throw new EE_Error(
5347
+				sprintf(
5348
+					__('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5349
+						'event_espresso'),
5350
+					$methodName,
5351
+					$className,
5352
+					$tagName,
5353
+					'<br />'
5354
+				)
5355
+			);
5356
+		}
5357
+		return apply_filters($tagName, null, $this, $args);
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5364
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5365
+	 *
5366
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5367
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5368
+	 *                                                       the object's class name
5369
+	 *                                                       or object's ID
5370
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5371
+	 *                                                       exists in the database. If it does not, we add it
5372
+	 * @throws EE_Error
5373
+	 * @return EE_Base_Class
5374
+	 */
5375
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5376
+	{
5377
+		$className = $this->_get_class_name();
5378
+		if ($base_class_obj_or_id instanceof $className) {
5379
+			$model_object = $base_class_obj_or_id;
5380
+		} else {
5381
+			$primary_key_field = $this->get_primary_key_field();
5382
+			if (
5383
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5384
+				&& (
5385
+					is_int($base_class_obj_or_id)
5386
+					|| is_string($base_class_obj_or_id)
5387
+				)
5388
+			) {
5389
+				// assume it's an ID.
5390
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5391
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5392
+			} else if (
5393
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5394
+				&& is_string($base_class_obj_or_id)
5395
+			) {
5396
+				// assume its a string representation of the object
5397
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5398
+			} else {
5399
+				throw new EE_Error(
5400
+					sprintf(
5401
+						__(
5402
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5403
+							'event_espresso'
5404
+						),
5405
+						$base_class_obj_or_id,
5406
+						$this->_get_class_name(),
5407
+						print_r($base_class_obj_or_id, true)
5408
+					)
5409
+				);
5410
+			}
5411
+		}
5412
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5413
+			$model_object->save();
5414
+		}
5415
+		return $model_object;
5416
+	}
5417
+
5418
+
5419
+
5420
+	/**
5421
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5422
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5423
+	 * returns it ID.
5424
+	 *
5425
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5426
+	 * @return int|string depending on the type of this model object's ID
5427
+	 * @throws EE_Error
5428
+	 */
5429
+	public function ensure_is_ID($base_class_obj_or_id)
5430
+	{
5431
+		$className = $this->_get_class_name();
5432
+		if ($base_class_obj_or_id instanceof $className) {
5433
+			/** @var $base_class_obj_or_id EE_Base_Class */
5434
+			$id = $base_class_obj_or_id->ID();
5435
+		} elseif (is_int($base_class_obj_or_id)) {
5436
+			//assume it's an ID
5437
+			$id = $base_class_obj_or_id;
5438
+		} elseif (is_string($base_class_obj_or_id)) {
5439
+			//assume its a string representation of the object
5440
+			$id = $base_class_obj_or_id;
5441
+		} else {
5442
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5443
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5444
+				print_r($base_class_obj_or_id, true)));
5445
+		}
5446
+		return $id;
5447
+	}
5448
+
5449
+
5450
+
5451
+	/**
5452
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5453
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5454
+	 * been sanitized and converted into the appropriate domain.
5455
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5456
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5457
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5458
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5459
+	 * $EVT = EEM_Event::instance(); $old_setting =
5460
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5461
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5462
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5463
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5464
+	 *
5465
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5466
+	 * @return void
5467
+	 */
5468
+	public function assume_values_already_prepared_by_model_object(
5469
+		$values_already_prepared = self::not_prepared_by_model_object
5470
+	) {
5471
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5472
+	}
5473
+
5474
+
5475
+
5476
+	/**
5477
+	 * Read comments for assume_values_already_prepared_by_model_object()
5478
+	 *
5479
+	 * @return int
5480
+	 */
5481
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5482
+	{
5483
+		return $this->_values_already_prepared_by_model_object;
5484
+	}
5485
+
5486
+
5487
+
5488
+	/**
5489
+	 * Gets all the indexes on this model
5490
+	 *
5491
+	 * @return EE_Index[]
5492
+	 */
5493
+	public function indexes()
5494
+	{
5495
+		return $this->_indexes;
5496
+	}
5497
+
5498
+
5499
+
5500
+	/**
5501
+	 * Gets all the Unique Indexes on this model
5502
+	 *
5503
+	 * @return EE_Unique_Index[]
5504
+	 */
5505
+	public function unique_indexes()
5506
+	{
5507
+		$unique_indexes = array();
5508
+		foreach ($this->_indexes as $name => $index) {
5509
+			if ($index instanceof EE_Unique_Index) {
5510
+				$unique_indexes [$name] = $index;
5511
+			}
5512
+		}
5513
+		return $unique_indexes;
5514
+	}
5515
+
5516
+
5517
+
5518
+	/**
5519
+	 * Gets all the fields which, when combined, make the primary key.
5520
+	 * This is usually just an array with 1 element (the primary key), but in cases
5521
+	 * where there is no primary key, it's a combination of fields as defined
5522
+	 * on a primary index
5523
+	 *
5524
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5525
+	 * @throws EE_Error
5526
+	 */
5527
+	public function get_combined_primary_key_fields()
5528
+	{
5529
+		foreach ($this->indexes() as $index) {
5530
+			if ($index instanceof EE_Primary_Key_Index) {
5531
+				return $index->fields();
5532
+			}
5533
+		}
5534
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5535
+	}
5536
+
5537
+
5538
+
5539
+	/**
5540
+	 * Used to build a primary key string (when the model has no primary key),
5541
+	 * which can be used a unique string to identify this model object.
5542
+	 *
5543
+	 * @param array $cols_n_values keys are field names, values are their values
5544
+	 * @return string
5545
+	 * @throws EE_Error
5546
+	 */
5547
+	public function get_index_primary_key_string($cols_n_values)
5548
+	{
5549
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5550
+			$this->get_combined_primary_key_fields());
5551
+		return http_build_query($cols_n_values_for_primary_key_index);
5552
+	}
5553
+
5554
+
5555
+
5556
+	/**
5557
+	 * Gets the field values from the primary key string
5558
+	 *
5559
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5560
+	 * @param string $index_primary_key_string
5561
+	 * @return null|array
5562
+	 * @throws EE_Error
5563
+	 */
5564
+	public function parse_index_primary_key_string($index_primary_key_string)
5565
+	{
5566
+		$key_fields = $this->get_combined_primary_key_fields();
5567
+		//check all of them are in the $id
5568
+		$key_vals_in_combined_pk = array();
5569
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5570
+		foreach ($key_fields as $key_field_name => $field_obj) {
5571
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5572
+				return null;
5573
+			}
5574
+		}
5575
+		return $key_vals_in_combined_pk;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * verifies that an array of key-value pairs for model fields has a key
5582
+	 * for each field comprising the primary key index
5583
+	 *
5584
+	 * @param array $key_vals
5585
+	 * @return boolean
5586
+	 * @throws EE_Error
5587
+	 */
5588
+	public function has_all_combined_primary_key_fields($key_vals)
5589
+	{
5590
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5591
+		foreach ($keys_it_should_have as $key) {
5592
+			if (! isset($key_vals[$key])) {
5593
+				return false;
5594
+			}
5595
+		}
5596
+		return true;
5597
+	}
5598
+
5599
+
5600
+
5601
+	/**
5602
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5603
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5604
+	 *
5605
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5606
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5607
+	 * @throws EE_Error
5608
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5609
+	 *                                                              indexed)
5610
+	 */
5611
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5612
+	{
5613
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5614
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5615
+		} elseif (is_array($model_object_or_attributes_array)) {
5616
+			$attributes_array = $model_object_or_attributes_array;
5617
+		} else {
5618
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5619
+				"event_espresso"), $model_object_or_attributes_array));
5620
+		}
5621
+		//even copies obviously won't have the same ID, so remove the primary key
5622
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5623
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5624
+			unset($attributes_array[$this->primary_key_name()]);
5625
+		}
5626
+		if (isset($query_params[0])) {
5627
+			$query_params[0] = array_merge($attributes_array, $query_params);
5628
+		} else {
5629
+			$query_params[0] = $attributes_array;
5630
+		}
5631
+		return $this->get_all($query_params);
5632
+	}
5633
+
5634
+
5635
+
5636
+	/**
5637
+	 * Gets the first copy we find. See get_all_copies for more details
5638
+	 *
5639
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5640
+	 * @param array $query_params
5641
+	 * @return EE_Base_Class
5642
+	 * @throws EE_Error
5643
+	 */
5644
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5645
+	{
5646
+		if (! is_array($query_params)) {
5647
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5648
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5649
+					gettype($query_params)), '4.6.0');
5650
+			$query_params = array();
5651
+		}
5652
+		$query_params['limit'] = 1;
5653
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5654
+		if (is_array($copies)) {
5655
+			return array_shift($copies);
5656
+		}
5657
+		return null;
5658
+	}
5659
+
5660
+
5661
+
5662
+	/**
5663
+	 * Updates the item with the specified id. Ignores default query parameters because
5664
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5665
+	 *
5666
+	 * @param array      $fields_n_values keys are field names, values are their new values
5667
+	 * @param int|string $id              the value of the primary key to update
5668
+	 * @return int number of rows updated
5669
+	 * @throws EE_Error
5670
+	 */
5671
+	public function update_by_ID($fields_n_values, $id)
5672
+	{
5673
+		$query_params = array(
5674
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5675
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5676
+		);
5677
+		return $this->update($fields_n_values, $query_params);
5678
+	}
5679
+
5680
+
5681
+
5682
+	/**
5683
+	 * Changes an operator which was supplied to the models into one usable in SQL
5684
+	 *
5685
+	 * @param string $operator_supplied
5686
+	 * @return string an operator which can be used in SQL
5687
+	 * @throws EE_Error
5688
+	 */
5689
+	private function _prepare_operator_for_sql($operator_supplied)
5690
+	{
5691
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5692
+			: null;
5693
+		if ($sql_operator) {
5694
+			return $sql_operator;
5695
+		}
5696
+		throw new EE_Error(
5697
+			sprintf(
5698
+				__(
5699
+					"The operator '%s' is not in the list of valid operators: %s",
5700
+					"event_espresso"
5701
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5702
+			)
5703
+		);
5704
+	}
5705
+
5706
+
5707
+
5708
+	/**
5709
+	 * Gets an array where keys are the primary keys and values are their 'names'
5710
+	 * (as determined by the model object's name() function, which is often overridden)
5711
+	 *
5712
+	 * @param array $query_params like get_all's
5713
+	 * @return string[]
5714
+	 * @throws EE_Error
5715
+	 */
5716
+	public function get_all_names($query_params = array())
5717
+	{
5718
+		$objs = $this->get_all($query_params);
5719
+		$names = array();
5720
+		foreach ($objs as $obj) {
5721
+			$names[$obj->ID()] = $obj->name();
5722
+		}
5723
+		return $names;
5724
+	}
5725
+
5726
+
5727
+
5728
+	/**
5729
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5730
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5731
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5732
+	 * array_keys() on $model_objects.
5733
+	 *
5734
+	 * @param \EE_Base_Class[] $model_objects
5735
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5736
+	 *                                               in the returned array
5737
+	 * @return array
5738
+	 * @throws EE_Error
5739
+	 */
5740
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5741
+	{
5742
+		if (! $this->has_primary_key_field()) {
5743
+			if (WP_DEBUG) {
5744
+				EE_Error::add_error(
5745
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5746
+					__FILE__,
5747
+					__FUNCTION__,
5748
+					__LINE__
5749
+				);
5750
+			}
5751
+		}
5752
+		$IDs = array();
5753
+		foreach ($model_objects as $model_object) {
5754
+			$id = $model_object->ID();
5755
+			if (! $id) {
5756
+				if ($filter_out_empty_ids) {
5757
+					continue;
5758
+				}
5759
+				if (WP_DEBUG) {
5760
+					EE_Error::add_error(
5761
+						__(
5762
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5763
+							'event_espresso'
5764
+						),
5765
+						__FILE__,
5766
+						__FUNCTION__,
5767
+						__LINE__
5768
+					);
5769
+				}
5770
+			}
5771
+			$IDs[] = $id;
5772
+		}
5773
+		return $IDs;
5774
+	}
5775
+
5776
+
5777
+
5778
+	/**
5779
+	 * Returns the string used in capabilities relating to this model. If there
5780
+	 * are no capabilities that relate to this model returns false
5781
+	 *
5782
+	 * @return string|false
5783
+	 */
5784
+	public function cap_slug()
5785
+	{
5786
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5787
+	}
5788
+
5789
+
5790
+
5791
+	/**
5792
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5793
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5794
+	 * only returns the cap restrictions array in that context (ie, the array
5795
+	 * at that key)
5796
+	 *
5797
+	 * @param string $context
5798
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5799
+	 * @throws EE_Error
5800
+	 */
5801
+	public function cap_restrictions($context = EEM_Base::caps_read)
5802
+	{
5803
+		EEM_Base::verify_is_valid_cap_context($context);
5804
+		//check if we ought to run the restriction generator first
5805
+		if (
5806
+			isset($this->_cap_restriction_generators[$context])
5807
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5808
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5809
+		) {
5810
+			$this->_cap_restrictions[$context] = array_merge(
5811
+				$this->_cap_restrictions[$context],
5812
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5813
+			);
5814
+		}
5815
+		//and make sure we've finalized the construction of each restriction
5816
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5817
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5818
+				$where_conditions_obj->_finalize_construct($this);
5819
+			}
5820
+		}
5821
+		return $this->_cap_restrictions[$context];
5822
+	}
5823
+
5824
+
5825
+
5826
+	/**
5827
+	 * Indicating whether or not this model thinks its a wp core model
5828
+	 *
5829
+	 * @return boolean
5830
+	 */
5831
+	public function is_wp_core_model()
5832
+	{
5833
+		return $this->_wp_core_model;
5834
+	}
5835
+
5836
+
5837
+
5838
+	/**
5839
+	 * Gets all the caps that are missing which impose a restriction on
5840
+	 * queries made in this context
5841
+	 *
5842
+	 * @param string $context one of EEM_Base::caps_ constants
5843
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5844
+	 * @throws EE_Error
5845
+	 */
5846
+	public function caps_missing($context = EEM_Base::caps_read)
5847
+	{
5848
+		$missing_caps = array();
5849
+		$cap_restrictions = $this->cap_restrictions($context);
5850
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5851
+			if (! EE_Capabilities::instance()
5852
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5853
+			) {
5854
+				$missing_caps[$cap] = $restriction_if_no_cap;
5855
+			}
5856
+		}
5857
+		return $missing_caps;
5858
+	}
5859
+
5860
+
5861
+
5862
+	/**
5863
+	 * Gets the mapping from capability contexts to action strings used in capability names
5864
+	 *
5865
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5866
+	 * one of 'read', 'edit', or 'delete'
5867
+	 */
5868
+	public function cap_contexts_to_cap_action_map()
5869
+	{
5870
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5871
+			$this);
5872
+	}
5873
+
5874
+
5875
+
5876
+	/**
5877
+	 * Gets the action string for the specified capability context
5878
+	 *
5879
+	 * @param string $context
5880
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5881
+	 * @throws EE_Error
5882
+	 */
5883
+	public function cap_action_for_context($context)
5884
+	{
5885
+		$mapping = $this->cap_contexts_to_cap_action_map();
5886
+		if (isset($mapping[$context])) {
5887
+			return $mapping[$context];
5888
+		}
5889
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5890
+			return $action;
5891
+		}
5892
+		throw new EE_Error(
5893
+			sprintf(
5894
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5895
+				$context,
5896
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5897
+			)
5898
+		);
5899
+	}
5900
+
5901
+
5902
+
5903
+	/**
5904
+	 * Returns all the capability contexts which are valid when querying models
5905
+	 *
5906
+	 * @return array
5907
+	 */
5908
+	public static function valid_cap_contexts()
5909
+	{
5910
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5911
+			self::caps_read,
5912
+			self::caps_read_admin,
5913
+			self::caps_edit,
5914
+			self::caps_delete,
5915
+		));
5916
+	}
5917
+
5918
+
5919
+
5920
+	/**
5921
+	 * Returns all valid options for 'default_where_conditions'
5922
+	 *
5923
+	 * @return array
5924
+	 */
5925
+	public static function valid_default_where_conditions()
5926
+	{
5927
+		return array(
5928
+			EEM_Base::default_where_conditions_all,
5929
+			EEM_Base::default_where_conditions_this_only,
5930
+			EEM_Base::default_where_conditions_others_only,
5931
+			EEM_Base::default_where_conditions_minimum_all,
5932
+			EEM_Base::default_where_conditions_minimum_others,
5933
+			EEM_Base::default_where_conditions_none
5934
+		);
5935
+	}
5936
+
5937
+	// public static function default_where_conditions_full
5938
+	/**
5939
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5940
+	 *
5941
+	 * @param string $context
5942
+	 * @return bool
5943
+	 * @throws EE_Error
5944
+	 */
5945
+	static public function verify_is_valid_cap_context($context)
5946
+	{
5947
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5948
+		if (in_array($context, $valid_cap_contexts)) {
5949
+			return true;
5950
+		}
5951
+		throw new EE_Error(
5952
+			sprintf(
5953
+				__(
5954
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5955
+					'event_espresso'
5956
+				),
5957
+				$context,
5958
+				'EEM_Base',
5959
+				implode(',', $valid_cap_contexts)
5960
+			)
5961
+		);
5962
+	}
5963
+
5964
+
5965
+
5966
+	/**
5967
+	 * Clears all the models field caches. This is only useful when a sub-class
5968
+	 * might have added a field or something and these caches might be invalidated
5969
+	 */
5970
+	protected function _invalidate_field_caches()
5971
+	{
5972
+		$this->_cache_foreign_key_to_fields = array();
5973
+		$this->_cached_fields = null;
5974
+		$this->_cached_fields_non_db_only = null;
5975
+	}
5976
+
5977
+
5978
+
5979
+	/**
5980
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5981
+	 * (eg "and", "or", "not").
5982
+	 *
5983
+	 * @return array
5984
+	 */
5985
+	public function logic_query_param_keys()
5986
+	{
5987
+		return $this->_logic_query_param_keys;
5988
+	}
5989
+
5990
+
5991
+
5992
+	/**
5993
+	 * Determines whether or not the where query param array key is for a logic query param.
5994
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
5995
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5996
+	 *
5997
+	 * @param $query_param_key
5998
+	 * @return bool
5999
+	 */
6000
+	public function is_logic_query_param_key($query_param_key)
6001
+	{
6002
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6003
+			if ($query_param_key === $logic_query_param_key
6004
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6005
+			) {
6006
+				return true;
6007
+			}
6008
+		}
6009
+		return false;
6010
+	}
6011 6011
 
6012 6012
 
6013 6013
 
Please login to merge, or discard this patch.
Spacing   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -519,8 +519,8 @@  discard block
 block discarded – undo
519 519
     protected function __construct($timezone = null)
520 520
     {
521 521
         // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
522
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+            throw new EE_Error(
524 524
                 sprintf(
525 525
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
526 526
                         'event_espresso'),
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
          *
541 541
          * @var EE_Table_Base[] $_tables
542 542
          */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
543
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
544 544
         foreach ($this->_tables as $table_alias => $table_obj) {
545 545
             /** @var $table_obj EE_Table_Base */
546 546
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -555,10 +555,10 @@  discard block
 block discarded – undo
555 555
          *
556 556
          * @param EE_Model_Field_Base[] $_fields
557 557
          */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
558
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
559 559
         $this->_invalidate_field_caches();
560 560
         foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
561
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
562 562
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563 563
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
564 564
             }
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
          *
587 587
          * @param EE_Model_Relation_Base[] $_model_relations
588 588
          */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
589
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
590 590
             $this->_model_relations);
591 591
         foreach ($this->_model_relations as $model_name => $relation_obj) {
592 592
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
         }
599 599
         $this->set_timezone($timezone);
600 600
         //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
601
+        if ( ! $this->_default_where_conditions_strategy) {
602 602
             //nothing was set during child constructor, so set default
603 603
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604 604
         }
605 605
         $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
606
+        if ( ! $this->_minimum_where_conditions_strategy) {
607 607
             //nothing was set during child constructor, so set default
608 608
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609 609
         }
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
         //initialize the standard cap restriction generators if none were specified by the child constructor
617 617
         if ($this->_cap_restriction_generators !== false) {
618 618
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
619
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
620 620
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
621 621
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622 622
                         new EE_Restriction_Generator_Protected(),
@@ -629,10 +629,10 @@  discard block
 block discarded – undo
629 629
         //if there are cap restriction generators, use them to make the default cap restrictions
630 630
         if ($this->_cap_restriction_generators !== false) {
631 631
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
632
+                if ( ! $generator_object) {
633 633
                     continue;
634 634
                 }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
635
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
636 636
                     throw new EE_Error(
637 637
                         sprintf(
638 638
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -643,12 +643,12 @@  discard block
 block discarded – undo
643 643
                     );
644 644
                 }
645 645
                 $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
646
+                if ( ! $generator_object->construction_finalized()) {
647 647
                     $generator_object->_construct_finalize($this, $action);
648 648
                 }
649 649
             }
650 650
         }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
651
+        do_action('AHEE__'.get_class($this).'__construct__end');
652 652
     }
653 653
 
654 654
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
      */
684 684
     public static function set_model_query_blog_id($blog_id = 0)
685 685
     {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
686
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
687 687
     }
688 688
 
689 689
 
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
     public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719 719
     {
720 720
         // check if instance of Espresso_model already exists
721
-        if (! static::$_instance instanceof static) {
721
+        if ( ! static::$_instance instanceof static) {
722 722
             $model_field_factory = self::getModelFieldFactory($model_field_factory);
723 723
             // instantiate Espresso_model
724 724
             static::$_instance = new static($timezone, $model_field_factory);
@@ -772,7 +772,7 @@  discard block
 block discarded – undo
772 772
             foreach ($r->getDefaultProperties() as $property => $value) {
773 773
                 //don't set instance to null like it was originally,
774 774
                 //but it's static anyways, and we're ignoring static properties (for now at least)
775
-                if (! isset($static_properties[$property])) {
775
+                if ( ! isset($static_properties[$property])) {
776 776
                     static::$_instance->{$property} = $value;
777 777
                 }
778 778
             }
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
      */
796 796
     public function status_array($translated = false)
797 797
     {
798
-        if (! array_key_exists('Status', $this->_model_relations)) {
798
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
799 799
             return array();
800 800
         }
801 801
         $model_name = $this->get_this_model_name();
@@ -998,17 +998,17 @@  discard block
 block discarded – undo
998 998
     public function wp_user_field_name()
999 999
     {
1000 1000
         try {
1001
-            if (! empty($this->_model_chain_to_wp_user)) {
1001
+            if ( ! empty($this->_model_chain_to_wp_user)) {
1002 1002
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003 1003
                 $last_model_name = end($models_to_follow_to_wp_users);
1004 1004
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1005
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
1006 1006
             } else {
1007 1007
                 $model_with_fk_to_wp_users = $this;
1008 1008
                 $model_chain_to_wp_user = '';
1009 1009
             }
1010 1010
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1011
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
1012 1012
         } catch (EE_Error $e) {
1013 1013
             return false;
1014 1014
         }
@@ -1079,12 +1079,12 @@  discard block
 block discarded – undo
1079 1079
         // remember the custom selections, if any, and type cast as array
1080 1080
         // (unless $columns_to_select is an object, then just set as an empty array)
1081 1081
         // Note: (array) 'some string' === array( 'some string' )
1082
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1082
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1083 1083
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1084 1084
         $select_expressions = $columns_to_select !== null
1085 1085
             ? $this->_construct_select_from_input($columns_to_select)
1086 1086
             : $this->_construct_default_select_sql($model_query_info);
1087
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1087
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1088 1088
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089 1089
     }
1090 1090
 
@@ -1129,7 +1129,7 @@  discard block
 block discarded – undo
1129 1129
         if (is_array($columns_to_select)) {
1130 1130
             $select_sql_array = array();
1131 1131
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133 1133
                     throw new EE_Error(
1134 1134
                         sprintf(
1135 1135
                             __(
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
                         )
1142 1142
                     );
1143 1143
                 }
1144
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1144
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145 1145
                     throw new EE_Error(
1146 1146
                         sprintf(
1147 1147
                             __(
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
      */
1214 1214
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215 1215
     {
1216
-        if (! isset($query_params[0])) {
1216
+        if ( ! isset($query_params[0])) {
1217 1217
             $query_params[0] = array();
1218 1218
         }
1219 1219
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1238,7 +1238,7 @@  discard block
 block discarded – undo
1238 1238
      */
1239 1239
     public function get_one($query_params = array())
1240 1240
     {
1241
-        if (! is_array($query_params)) {
1241
+        if ( ! is_array($query_params)) {
1242 1242
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1243 1243
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244 1244
                     gettype($query_params)), '4.6.0');
@@ -1429,7 +1429,7 @@  discard block
 block discarded – undo
1429 1429
                 return array();
1430 1430
             }
1431 1431
         }
1432
-        if (! is_array($query_params)) {
1432
+        if ( ! is_array($query_params)) {
1433 1433
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434 1434
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435 1435
                     gettype($query_params)), '4.6.0');
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440 1440
         $query_params['limit'] = $limit;
1441 1441
         //set direction
1442
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1442
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1443 1443
         $query_params['order_by'] = $operand === '>'
1444 1444
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1445 1445
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1517,7 +1517,7 @@  discard block
 block discarded – undo
1517 1517
     {
1518 1518
         $field_settings = $this->field_settings_for($field_name);
1519 1519
         //if not a valid EE_Datetime_Field then throw error
1520
-        if (! $field_settings instanceof EE_Datetime_Field) {
1520
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1521 1521
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1522 1522
                 'event_espresso'), $field_name));
1523 1523
         }
@@ -1596,7 +1596,7 @@  discard block
 block discarded – undo
1596 1596
         //load EEH_DTT_Helper
1597 1597
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598 1598
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1599
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1600 1600
     }
1601 1601
 
1602 1602
 
@@ -1664,7 +1664,7 @@  discard block
 block discarded – undo
1664 1664
      */
1665 1665
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666 1666
     {
1667
-        if (! is_array($query_params)) {
1667
+        if ( ! is_array($query_params)) {
1668 1668
             EE_Error::doing_it_wrong('EEM_Base::update',
1669 1669
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670 1670
                     gettype($query_params)), '4.6.0');
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
          * @param EEM_Base $model           the model being queried
1687 1687
          * @param array    $query_params    see EEM_Base::get_all()
1688 1688
          */
1689
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1689
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690 1690
             $query_params);
1691 1691
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1692 1692
         //to do that, for each table, verify that it's PK isn't null.
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701 1701
         foreach ($wpdb_select_results as $wpdb_result) {
1702 1702
             // type cast stdClass as array
1703
-            $wpdb_result = (array)$wpdb_result;
1703
+            $wpdb_result = (array) $wpdb_result;
1704 1704
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705 1705
             if ($this->has_primary_key_field()) {
1706 1706
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1717,13 +1717,13 @@  discard block
 block discarded – undo
1717 1717
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718 1718
                     //if there is no private key for this table on the results, it means there's no entry
1719 1719
                     //in this table, right? so insert a row in the current table, using any fields available
1720
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1720
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1721 1721
                            && $wpdb_result[$this_table_pk_column])
1722 1722
                     ) {
1723 1723
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724 1724
                             $main_table_pk_value);
1725 1725
                         //if we died here, report the error
1726
-                        if (! $success) {
1726
+                        if ( ! $success) {
1727 1727
                             return false;
1728 1728
                         }
1729 1729
                     }
@@ -1754,7 +1754,7 @@  discard block
 block discarded – undo
1754 1754
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755 1755
                 }
1756 1756
             }
1757
-            if (! $model_objs_affected_ids) {
1757
+            if ( ! $model_objs_affected_ids) {
1758 1758
                 //wait wait wait- if nothing was affected let's stop here
1759 1759
                 return 0;
1760 1760
             }
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
                . $model_query_info->get_full_join_sql()
1782 1782
                . " SET "
1783 1783
                . $this->_construct_update_sql($fields_n_values)
1784
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1784
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785 1785
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786 1786
         /**
1787 1787
          * Action called after a model update call has been made.
@@ -1792,7 +1792,7 @@  discard block
 block discarded – undo
1792 1792
          * @param int      $rows_affected
1793 1793
          */
1794 1794
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
-        return $rows_affected;//how many supposedly got updated
1795
+        return $rows_affected; //how many supposedly got updated
1796 1796
     }
1797 1797
 
1798 1798
 
@@ -1820,7 +1820,7 @@  discard block
 block discarded – undo
1820 1820
         }
1821 1821
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1822 1822
         $select_expressions = $field->get_qualified_column();
1823
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1823
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1824 1824
         return $this->_do_wpdb_query('get_col', array($SQL));
1825 1825
     }
1826 1826
 
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
     {
1839 1839
         $query_params['limit'] = 1;
1840 1840
         $col = $this->get_col($query_params, $field_to_select);
1841
-        if (! empty($col)) {
1841
+        if ( ! empty($col)) {
1842 1842
             return reset($col);
1843 1843
         }
1844 1844
         return null;
@@ -1869,7 +1869,7 @@  discard block
 block discarded – undo
1869 1869
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870 1870
             $value_sql = $prepared_value === null ? 'NULL'
1871 1871
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1872
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1873 1873
         }
1874 1874
         return implode(",", $cols_n_values);
1875 1875
     }
@@ -2047,7 +2047,7 @@  discard block
 block discarded – undo
2047 2047
          * @param int      $rows_deleted
2048 2048
          */
2049 2049
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
-        return $rows_deleted;//how many supposedly got deleted
2050
+        return $rows_deleted; //how many supposedly got deleted
2051 2051
     }
2052 2052
 
2053 2053
 
@@ -2196,7 +2196,7 @@  discard block
 block discarded – undo
2196 2196
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2197 2197
                 //make sure we have unique $ids
2198 2198
                 $ids = array_unique($ids);
2199
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2199
+                $query[] = $column.' IN('.implode(',', $ids).')';
2200 2200
             }
2201 2201
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2202 2202
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2204,9 +2204,9 @@  discard block
 block discarded – undo
2204 2204
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2205 2205
                 $values_for_each_combined_primary_key_for_a_row = array();
2206 2206
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2207
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2207
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2208 2208
                 }
2209
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2209
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2210 2210
             }
2211 2211
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2212 2212
         }
@@ -2252,9 +2252,9 @@  discard block
 block discarded – undo
2252 2252
                 $column_to_count = '*';
2253 2253
             }
2254 2254
         }
2255
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2256
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2257
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2255
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2256
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2257
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2258 2258
     }
2259 2259
 
2260 2260
 
@@ -2276,14 +2276,14 @@  discard block
 block discarded – undo
2276 2276
             $field_obj = $this->get_primary_key_field();
2277 2277
         }
2278 2278
         $column_to_count = $field_obj->get_qualified_column();
2279
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2279
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2280 2280
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2281 2281
         $data_type = $field_obj->get_wpdb_data_type();
2282 2282
         if ($data_type === '%d' || $data_type === '%s') {
2283
-            return (float)$return_value;
2283
+            return (float) $return_value;
2284 2284
         }
2285 2285
         //must be %f
2286
-        return (float)$return_value;
2286
+        return (float) $return_value;
2287 2287
     }
2288 2288
 
2289 2289
 
@@ -2303,13 +2303,13 @@  discard block
 block discarded – undo
2303 2303
         //if we're in maintenance mode level 2, DON'T run any queries
2304 2304
         //because level 2 indicates the database needs updating and
2305 2305
         //is probably out of sync with the code
2306
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2306
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2307 2307
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2308 2308
                 "event_espresso")));
2309 2309
         }
2310 2310
         /** @type WPDB $wpdb */
2311 2311
         global $wpdb;
2312
-        if (! method_exists($wpdb, $wpdb_method)) {
2312
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2313 2313
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2314 2314
                 'event_espresso'), $wpdb_method));
2315 2315
         }
@@ -2321,7 +2321,7 @@  discard block
 block discarded – undo
2321 2321
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2322 2322
         if (WP_DEBUG) {
2323 2323
             $wpdb->show_errors($old_show_errors_value);
2324
-            if (! empty($wpdb->last_error)) {
2324
+            if ( ! empty($wpdb->last_error)) {
2325 2325
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2326 2326
             }
2327 2327
             if ($result === false) {
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
                     return $result;
2383 2383
                     break;
2384 2384
             }
2385
-            if (! empty($error_message)) {
2385
+            if ( ! empty($error_message)) {
2386 2386
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2387 2387
                 trigger_error($error_message);
2388 2388
             }
@@ -2458,11 +2458,11 @@  discard block
 block discarded – undo
2458 2458
      */
2459 2459
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2460 2460
     {
2461
-        return " FROM " . $model_query_info->get_full_join_sql() .
2462
-               $model_query_info->get_where_sql() .
2463
-               $model_query_info->get_group_by_sql() .
2464
-               $model_query_info->get_having_sql() .
2465
-               $model_query_info->get_order_by_sql() .
2461
+        return " FROM ".$model_query_info->get_full_join_sql().
2462
+               $model_query_info->get_where_sql().
2463
+               $model_query_info->get_group_by_sql().
2464
+               $model_query_info->get_having_sql().
2465
+               $model_query_info->get_order_by_sql().
2466 2466
                $model_query_info->get_limit_sql();
2467 2467
     }
2468 2468
 
@@ -2658,12 +2658,12 @@  discard block
 block discarded – undo
2658 2658
         $related_model = $this->get_related_model_obj($model_name);
2659 2659
         //we're just going to use the query params on the related model's normal get_all query,
2660 2660
         //except add a condition to say to match the current mod
2661
-        if (! isset($query_params['default_where_conditions'])) {
2661
+        if ( ! isset($query_params['default_where_conditions'])) {
2662 2662
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2663 2663
         }
2664 2664
         $this_model_name = $this->get_this_model_name();
2665 2665
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2666
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2666
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2667 2667
         return $related_model->count($query_params, $field_to_count, $distinct);
2668 2668
     }
2669 2669
 
@@ -2683,7 +2683,7 @@  discard block
 block discarded – undo
2683 2683
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2684 2684
     {
2685 2685
         $related_model = $this->get_related_model_obj($model_name);
2686
-        if (! is_array($query_params)) {
2686
+        if ( ! is_array($query_params)) {
2687 2687
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2688 2688
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2689 2689
                     gettype($query_params)), '4.6.0');
@@ -2691,12 +2691,12 @@  discard block
 block discarded – undo
2691 2691
         }
2692 2692
         //we're just going to use the query params on the related model's normal get_all query,
2693 2693
         //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2694
+        if ( ! isset($query_params['default_where_conditions'])) {
2695 2695
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696 2696
         }
2697 2697
         $this_model_name = $this->get_this_model_name();
2698 2698
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2699
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2700 2700
         return $related_model->sum($query_params, $field_to_sum);
2701 2701
     }
2702 2702
 
@@ -2749,7 +2749,7 @@  discard block
 block discarded – undo
2749 2749
                 $field_with_model_name = $field;
2750 2750
             }
2751 2751
         }
2752
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2752
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2753 2753
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2754 2754
                 $this->get_this_model_name()));
2755 2755
         }
@@ -2782,7 +2782,7 @@  discard block
 block discarded – undo
2782 2782
          * @param array    $fields_n_values keys are the fields and values are their new values
2783 2783
          * @param EEM_Base $model           the model used
2784 2784
          */
2785
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2785
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2786 2786
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2787 2787
             $main_table = $this->_get_main_table();
2788 2788
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2889,7 +2889,7 @@  discard block
 block discarded – undo
2889 2889
         }
2890 2890
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2891 2891
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2892
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2892
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2893 2893
         }
2894 2894
         //if there is nothing to base this search on, then we shouldn't find anything
2895 2895
         if (empty($query_params)) {
@@ -2975,7 +2975,7 @@  discard block
 block discarded – undo
2975 2975
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2976 2976
             //so add the fk to the main table as a column
2977 2977
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2978
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2978
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2979 2979
         }
2980 2980
         //insert the new entry
2981 2981
         $result = $this->_do_wpdb_query('insert',
@@ -3179,7 +3179,7 @@  discard block
 block discarded – undo
3179 3179
                     $query_info_carrier,
3180 3180
                     'group_by'
3181 3181
                 );
3182
-            } elseif (! empty ($query_params['group_by'])) {
3182
+            } elseif ( ! empty ($query_params['group_by'])) {
3183 3183
                 $this->_extract_related_model_info_from_query_param(
3184 3184
                     $query_params['group_by'],
3185 3185
                     $query_info_carrier,
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
                     $query_info_carrier,
3202 3202
                     'order_by'
3203 3203
                 );
3204
-            } elseif (! empty($query_params['order_by'])) {
3204
+            } elseif ( ! empty($query_params['order_by'])) {
3205 3205
                 $this->_extract_related_model_info_from_query_param(
3206 3206
                     $query_params['order_by'],
3207 3207
                     $query_info_carrier,
@@ -3236,8 +3236,8 @@  discard block
 block discarded – undo
3236 3236
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3237 3237
         $query_param_type
3238 3238
     ) {
3239
-        if (! empty($sub_query_params)) {
3240
-            $sub_query_params = (array)$sub_query_params;
3239
+        if ( ! empty($sub_query_params)) {
3240
+            $sub_query_params = (array) $sub_query_params;
3241 3241
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3242 3242
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3243 3243
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3248,7 +3248,7 @@  discard block
 block discarded – undo
3248 3248
                 //of array('Registration.TXN_ID'=>23)
3249 3249
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3250 3250
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3251
-                    if (! is_array($possibly_array_of_params)) {
3251
+                    if ( ! is_array($possibly_array_of_params)) {
3252 3252
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3253 3253
                             "event_espresso"),
3254 3254
                             $param, $possibly_array_of_params));
@@ -3265,7 +3265,7 @@  discard block
 block discarded – undo
3265 3265
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3266 3266
                     //indicating that $possible_array_of_params[1] is actually a field name,
3267 3267
                     //from which we should extract query parameters!
3268
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3268
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3269 3269
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3270 3270
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3271 3271
                     }
@@ -3295,8 +3295,8 @@  discard block
 block discarded – undo
3295 3295
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3296 3296
         $query_param_type
3297 3297
     ) {
3298
-        if (! empty($sub_query_params)) {
3299
-            if (! is_array($sub_query_params)) {
3298
+        if ( ! empty($sub_query_params)) {
3299
+            if ( ! is_array($sub_query_params)) {
3300 3300
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3301 3301
                     $sub_query_params));
3302 3302
             }
@@ -3325,7 +3325,7 @@  discard block
 block discarded – undo
3325 3325
      */
3326 3326
     public function _create_model_query_info_carrier($query_params)
3327 3327
     {
3328
-        if (! is_array($query_params)) {
3328
+        if ( ! is_array($query_params)) {
3329 3329
             EE_Error::doing_it_wrong(
3330 3330
                 'EEM_Base::_create_model_query_info_carrier',
3331 3331
                 sprintf(
@@ -3401,7 +3401,7 @@  discard block
 block discarded – undo
3401 3401
         //set limit
3402 3402
         if (array_key_exists('limit', $query_params)) {
3403 3403
             if (is_array($query_params['limit'])) {
3404
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3404
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3405 3405
                     $e = sprintf(
3406 3406
                         __(
3407 3407
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3409,12 +3409,12 @@  discard block
 block discarded – undo
3409 3409
                         ),
3410 3410
                         http_build_query($query_params['limit'])
3411 3411
                     );
3412
-                    throw new EE_Error($e . "|" . $e);
3412
+                    throw new EE_Error($e."|".$e);
3413 3413
                 }
3414 3414
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3415
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3416
-            } elseif (! empty ($query_params['limit'])) {
3417
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3415
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3416
+            } elseif ( ! empty ($query_params['limit'])) {
3417
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3418 3418
             }
3419 3419
         }
3420 3420
         //set order by
@@ -3446,10 +3446,10 @@  discard block
 block discarded – undo
3446 3446
                 $order_array = array();
3447 3447
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3448 3448
                     $order = $this->_extract_order($order);
3449
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3449
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3450 3450
                 }
3451
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3452
-            } elseif (! empty ($query_params['order_by'])) {
3451
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3452
+            } elseif ( ! empty ($query_params['order_by'])) {
3453 3453
                 $this->_extract_related_model_info_from_query_param(
3454 3454
                     $query_params['order_by'],
3455 3455
                     $query_object,
@@ -3460,18 +3460,18 @@  discard block
 block discarded – undo
3460 3460
                     ? $this->_extract_order($query_params['order'])
3461 3461
                     : 'DESC';
3462 3462
                 $query_object->set_order_by_sql(
3463
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3463
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3464 3464
                 );
3465 3465
             }
3466 3466
         }
3467 3467
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3468
-        if (! array_key_exists('order_by', $query_params)
3468
+        if ( ! array_key_exists('order_by', $query_params)
3469 3469
             && array_key_exists('order', $query_params)
3470 3470
             && ! empty($query_params['order'])
3471 3471
         ) {
3472 3472
             $pk_field = $this->get_primary_key_field();
3473 3473
             $order = $this->_extract_order($query_params['order']);
3474
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3474
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3475 3475
         }
3476 3476
         //set group by
3477 3477
         if (array_key_exists('group_by', $query_params)) {
@@ -3481,10 +3481,10 @@  discard block
 block discarded – undo
3481 3481
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3482 3482
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3483 3483
                 }
3484
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3485
-            } elseif (! empty ($query_params['group_by'])) {
3484
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3485
+            } elseif ( ! empty ($query_params['group_by'])) {
3486 3486
                 $query_object->set_group_by_sql(
3487
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3487
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3488 3488
                 );
3489 3489
             }
3490 3490
         }
@@ -3494,7 +3494,7 @@  discard block
 block discarded – undo
3494 3494
         }
3495 3495
         //now, just verify they didn't pass anything wack
3496 3496
         foreach ($query_params as $query_key => $query_value) {
3497
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3497
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3498 3498
                 throw new EE_Error(
3499 3499
                     sprintf(
3500 3500
                         __(
@@ -3593,22 +3593,22 @@  discard block
 block discarded – undo
3593 3593
         $where_query_params = array()
3594 3594
     ) {
3595 3595
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3596
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3596
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3597 3597
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3598 3598
                 "event_espresso"), $use_default_where_conditions,
3599 3599
                 implode(", ", $allowed_used_default_where_conditions_values)));
3600 3600
         }
3601 3601
         $universal_query_params = array();
3602
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3602
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3603 3603
             $universal_query_params = $this->_get_default_where_conditions();
3604
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3604
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3605 3605
             $universal_query_params = $this->_get_minimum_where_conditions();
3606 3606
         }
3607 3607
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3608 3608
             $related_model = $this->get_related_model_obj($model_name);
3609
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3609
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3610 3610
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3611
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3611
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3612 3612
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3613 3613
             } else {
3614 3614
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3641,7 +3641,7 @@  discard block
 block discarded – undo
3641 3641
      * @param bool $for_this_model false means this is for OTHER related models
3642 3642
      * @return bool
3643 3643
      */
3644
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3644
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3645 3645
     {
3646 3646
         return (
3647 3647
                    $for_this_model
@@ -3720,7 +3720,7 @@  discard block
 block discarded – undo
3720 3720
     ) {
3721 3721
         $null_friendly_where_conditions = array();
3722 3722
         $none_overridden = true;
3723
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3723
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3724 3724
         foreach ($default_where_conditions as $key => $val) {
3725 3725
             if (isset($provided_where_conditions[$key])) {
3726 3726
                 $none_overridden = false;
@@ -3838,7 +3838,7 @@  discard block
 block discarded – undo
3838 3838
             foreach ($tables as $table_obj) {
3839 3839
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3840 3840
                                        . $table_obj->get_fully_qualified_pk_column();
3841
-                if (! in_array($qualified_pk_column, $selects)) {
3841
+                if ( ! in_array($qualified_pk_column, $selects)) {
3842 3842
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3843 3843
                 }
3844 3844
             }
@@ -3932,9 +3932,9 @@  discard block
 block discarded – undo
3932 3932
         //and
3933 3933
         //check if it's a field on a related model
3934 3934
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3935
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3935
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3936 3936
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3937
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3937
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3938 3938
                 if ($query_param === '') {
3939 3939
                     //nothing left to $query_param
3940 3940
                     //we should actually end in a field name, not a model like this!
@@ -4022,7 +4022,7 @@  discard block
 block discarded – undo
4022 4022
     {
4023 4023
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4024 4024
         if ($SQL) {
4025
-            return " WHERE " . $SQL;
4025
+            return " WHERE ".$SQL;
4026 4026
         }
4027 4027
         return '';
4028 4028
     }
@@ -4041,7 +4041,7 @@  discard block
 block discarded – undo
4041 4041
     {
4042 4042
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4043 4043
         if ($SQL) {
4044
-            return " HAVING " . $SQL;
4044
+            return " HAVING ".$SQL;
4045 4045
         }
4046 4046
         return '';
4047 4047
     }
@@ -4060,11 +4060,11 @@  discard block
 block discarded – undo
4060 4060
      */
4061 4061
     protected function _get_field_on_model($field_name, $model_name)
4062 4062
     {
4063
-        $model_class = 'EEM_' . $model_name;
4064
-        $model_filepath = $model_class . ".model.php";
4063
+        $model_class = 'EEM_'.$model_name;
4064
+        $model_filepath = $model_class.".model.php";
4065 4065
         if (is_readable($model_filepath)) {
4066 4066
             require_once($model_filepath);
4067
-            $model_instance = call_user_func($model_name . "::instance");
4067
+            $model_instance = call_user_func($model_name."::instance");
4068 4068
             /* @var $model_instance EEM_Base */
4069 4069
             return $model_instance->field_settings_for($field_name);
4070 4070
         }
@@ -4093,7 +4093,7 @@  discard block
 block discarded – undo
4093 4093
     {
4094 4094
         $where_clauses = array();
4095 4095
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4096
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4096
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4097 4097
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4098 4098
                 switch ($query_param) {
4099 4099
                     case 'not':
@@ -4121,7 +4121,7 @@  discard block
 block discarded – undo
4121 4121
             } else {
4122 4122
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4123 4123
                 //if it's not a normal field, maybe it's a custom selection?
4124
-                if (! $field_obj) {
4124
+                if ( ! $field_obj) {
4125 4125
                     if (isset($this->_custom_selections[$query_param][1])) {
4126 4126
                         $field_obj = $this->_custom_selections[$query_param][1];
4127 4127
                     } else {
@@ -4130,7 +4130,7 @@  discard block
 block discarded – undo
4130 4130
                     }
4131 4131
                 }
4132 4132
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4133
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4133
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4134 4134
             }
4135 4135
         }
4136 4136
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4151,7 +4151,7 @@  discard block
 block discarded – undo
4151 4151
         if ($field) {
4152 4152
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4153 4153
                 $query_param);
4154
-            return $table_alias_prefix . $field->get_qualified_column();
4154
+            return $table_alias_prefix.$field->get_qualified_column();
4155 4155
         }
4156 4156
         if (array_key_exists($query_param, $this->_custom_selections)) {
4157 4157
             //maybe it's custom selection item?
@@ -4203,7 +4203,7 @@  discard block
 block discarded – undo
4203 4203
     {
4204 4204
         if (is_array($op_and_value)) {
4205 4205
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4206
-            if (! $operator) {
4206
+            if ( ! $operator) {
4207 4207
                 $php_array_like_string = array();
4208 4208
                 foreach ($op_and_value as $key => $value) {
4209 4209
                     $php_array_like_string[] = "$key=>$value";
@@ -4225,14 +4225,14 @@  discard block
 block discarded – undo
4225 4225
         }
4226 4226
         //check to see if the value is actually another field
4227 4227
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4228
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4228
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4229 4229
         }
4230 4230
         if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4231 4231
             //in this case, the value should be an array, or at least a comma-separated list
4232 4232
             //it will need to handle a little differently
4233 4233
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4234 4234
             //note: $cleaned_value has already been run through $wpdb->prepare()
4235
-            return $operator . SP . $cleaned_value;
4235
+            return $operator.SP.$cleaned_value;
4236 4236
         }
4237 4237
         if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4238 4238
             //the value should be an array with count of two.
@@ -4248,7 +4248,7 @@  discard block
 block discarded – undo
4248 4248
                 );
4249 4249
             }
4250 4250
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4251
-            return $operator . SP . $cleaned_value;
4251
+            return $operator.SP.$cleaned_value;
4252 4252
         }
4253 4253
         if (in_array($operator, $this->_null_style_operators)) {
4254 4254
             if ($value !== null) {
@@ -4268,10 +4268,10 @@  discard block
 block discarded – undo
4268 4268
         if ($operator === 'LIKE' && ! is_array($value)) {
4269 4269
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4270 4270
             //remove other junk. So just treat it as a string.
4271
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4271
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4272 4272
         }
4273
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4274
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4273
+        if ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4274
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4275 4275
         }
4276 4276
         if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4277 4277
             throw new EE_Error(
@@ -4285,7 +4285,7 @@  discard block
 block discarded – undo
4285 4285
                 )
4286 4286
             );
4287 4287
         }
4288
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4288
+        if ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4289 4289
             throw new EE_Error(
4290 4290
                 sprintf(
4291 4291
                     __(
@@ -4325,7 +4325,7 @@  discard block
 block discarded – undo
4325 4325
         foreach ($values as $value) {
4326 4326
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4327 4327
         }
4328
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4328
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4329 4329
     }
4330 4330
 
4331 4331
 
@@ -4366,7 +4366,7 @@  discard block
 block discarded – undo
4366 4366
                                 . $main_table->get_table_name()
4367 4367
                                 . " WHERE FALSE";
4368 4368
         }
4369
-        return "(" . implode(",", $cleaned_values) . ")";
4369
+        return "(".implode(",", $cleaned_values).")";
4370 4370
     }
4371 4371
 
4372 4372
 
@@ -4385,7 +4385,7 @@  discard block
 block discarded – undo
4385 4385
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4386 4386
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4387 4387
         } //$field_obj should really just be a data type
4388
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4388
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4389 4389
             throw new EE_Error(
4390 4390
                 sprintf(
4391 4391
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4513,10 +4513,10 @@  discard block
 block discarded – undo
4513 4513
      */
4514 4514
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4515 4515
     {
4516
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4516
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4517 4517
         $qualified_columns = array();
4518 4518
         foreach ($this->field_settings() as $field_name => $field) {
4519
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4519
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4520 4520
         }
4521 4521
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4522 4522
     }
@@ -4540,11 +4540,11 @@  discard block
 block discarded – undo
4540 4540
             if ($table_obj instanceof EE_Primary_Table) {
4541 4541
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4542 4542
                     ? $table_obj->get_select_join_limit($limit)
4543
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4543
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4544 4544
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4545 4545
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4546 4546
                     ? $table_obj->get_select_join_limit_join($limit)
4547
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4547
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4548 4548
             }
4549 4549
         }
4550 4550
         return $SQL;
@@ -4632,12 +4632,12 @@  discard block
 block discarded – undo
4632 4632
      */
4633 4633
     public function get_related_model_obj($model_name)
4634 4634
     {
4635
-        $model_classname = "EEM_" . $model_name;
4636
-        if (! class_exists($model_classname)) {
4635
+        $model_classname = "EEM_".$model_name;
4636
+        if ( ! class_exists($model_classname)) {
4637 4637
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4638 4638
                 'event_espresso'), $model_name, $model_classname));
4639 4639
         }
4640
-        return call_user_func($model_classname . "::instance");
4640
+        return call_user_func($model_classname."::instance");
4641 4641
     }
4642 4642
 
4643 4643
 
@@ -4684,7 +4684,7 @@  discard block
 block discarded – undo
4684 4684
     public function related_settings_for($relation_name)
4685 4685
     {
4686 4686
         $relatedModels = $this->relation_settings();
4687
-        if (! array_key_exists($relation_name, $relatedModels)) {
4687
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4688 4688
             throw new EE_Error(
4689 4689
                 sprintf(
4690 4690
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4711,7 +4711,7 @@  discard block
 block discarded – undo
4711 4711
     public function field_settings_for($fieldName)
4712 4712
     {
4713 4713
         $fieldSettings = $this->field_settings(true);
4714
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4714
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4715 4715
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4716 4716
                 get_class($this)));
4717 4717
         }
@@ -4784,7 +4784,7 @@  discard block
 block discarded – undo
4784 4784
                     break;
4785 4785
                 }
4786 4786
             }
4787
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4787
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4788 4788
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4789 4789
                     get_class($this)));
4790 4790
             }
@@ -4843,7 +4843,7 @@  discard block
 block discarded – undo
4843 4843
      */
4844 4844
     public function get_foreign_key_to($model_name)
4845 4845
     {
4846
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4846
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4847 4847
             foreach ($this->field_settings() as $field) {
4848 4848
                 if (
4849 4849
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4853,7 +4853,7 @@  discard block
 block discarded – undo
4853 4853
                     break;
4854 4854
                 }
4855 4855
             }
4856
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4856
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4857 4857
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4858 4858
                     'event_espresso'), $model_name, get_class($this)));
4859 4859
             }
@@ -4904,7 +4904,7 @@  discard block
 block discarded – undo
4904 4904
             foreach ($this->_fields as $fields_corresponding_to_table) {
4905 4905
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4906 4906
                     /** @var $field_obj EE_Model_Field_Base */
4907
-                    if (! $field_obj->is_db_only_field()) {
4907
+                    if ( ! $field_obj->is_db_only_field()) {
4908 4908
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4909 4909
                     }
4910 4910
                 }
@@ -4933,7 +4933,7 @@  discard block
 block discarded – undo
4933 4933
         $count_if_model_has_no_primary_key = 0;
4934 4934
         $has_primary_key = $this->has_primary_key_field();
4935 4935
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4936
-        foreach ((array)$rows as $row) {
4936
+        foreach ((array) $rows as $row) {
4937 4937
             if (empty($row)) {
4938 4938
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4939 4939
                 return array();
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
                 }
4952 4952
             }
4953 4953
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4954
-            if (! $classInstance) {
4954
+            if ( ! $classInstance) {
4955 4955
                 throw new EE_Error(
4956 4956
                     sprintf(
4957 4957
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5020,7 +5020,7 @@  discard block
 block discarded – undo
5020 5020
      */
5021 5021
     public function instantiate_class_from_array_or_object($cols_n_values)
5022 5022
     {
5023
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5023
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5024 5024
             $cols_n_values = get_object_vars($cols_n_values);
5025 5025
         }
5026 5026
         $primary_key = null;
@@ -5045,7 +5045,7 @@  discard block
 block discarded – undo
5045 5045
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5046 5046
         if ($primary_key) {
5047 5047
             $classInstance = $this->get_from_entity_map($primary_key);
5048
-            if (! $classInstance) {
5048
+            if ( ! $classInstance) {
5049 5049
                 $classInstance = EE_Registry::instance()
5050 5050
                                             ->load_class($className,
5051 5051
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5096,12 +5096,12 @@  discard block
 block discarded – undo
5096 5096
     public function add_to_entity_map(EE_Base_Class $object)
5097 5097
     {
5098 5098
         $className = $this->_get_class_name();
5099
-        if (! $object instanceof $className) {
5099
+        if ( ! $object instanceof $className) {
5100 5100
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5101 5101
                 is_object($object) ? get_class($object) : $object, $className));
5102 5102
         }
5103 5103
         /** @var $object EE_Base_Class */
5104
-        if (! $object->ID()) {
5104
+        if ( ! $object->ID()) {
5105 5105
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5106 5106
                 "event_espresso"), get_class($this)));
5107 5107
         }
@@ -5170,7 +5170,7 @@  discard block
 block discarded – undo
5170 5170
             //there is a primary key on this table and its not set. Use defaults for all its columns
5171 5171
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5172 5172
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5173
-                    if (! $field_obj->is_db_only_field()) {
5173
+                    if ( ! $field_obj->is_db_only_field()) {
5174 5174
                         //prepare field as if its coming from db
5175 5175
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5176 5176
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5179,7 +5179,7 @@  discard block
 block discarded – undo
5179 5179
             } else {
5180 5180
                 //the table's rows existed. Use their values
5181 5181
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5182
-                    if (! $field_obj->is_db_only_field()) {
5182
+                    if ( ! $field_obj->is_db_only_field()) {
5183 5183
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5184 5184
                             $cols_n_values, $field_obj->get_qualified_column(),
5185 5185
                             $field_obj->get_table_column()
@@ -5294,7 +5294,7 @@  discard block
 block discarded – undo
5294 5294
      */
5295 5295
     private function _get_class_name()
5296 5296
     {
5297
-        return "EE_" . $this->get_this_model_name();
5297
+        return "EE_".$this->get_this_model_name();
5298 5298
     }
5299 5299
 
5300 5300
 
@@ -5309,7 +5309,7 @@  discard block
 block discarded – undo
5309 5309
      */
5310 5310
     public function item_name($quantity = 1)
5311 5311
     {
5312
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5312
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5313 5313
     }
5314 5314
 
5315 5315
 
@@ -5342,7 +5342,7 @@  discard block
 block discarded – undo
5342 5342
     {
5343 5343
         $className = get_class($this);
5344 5344
         $tagName = "FHEE__{$className}__{$methodName}";
5345
-        if (! has_filter($tagName)) {
5345
+        if ( ! has_filter($tagName)) {
5346 5346
             throw new EE_Error(
5347 5347
                 sprintf(
5348 5348
                     __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
@@ -5568,7 +5568,7 @@  discard block
 block discarded – undo
5568 5568
         $key_vals_in_combined_pk = array();
5569 5569
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5570 5570
         foreach ($key_fields as $key_field_name => $field_obj) {
5571
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5571
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5572 5572
                 return null;
5573 5573
             }
5574 5574
         }
@@ -5589,7 +5589,7 @@  discard block
 block discarded – undo
5589 5589
     {
5590 5590
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5591 5591
         foreach ($keys_it_should_have as $key) {
5592
-            if (! isset($key_vals[$key])) {
5592
+            if ( ! isset($key_vals[$key])) {
5593 5593
                 return false;
5594 5594
             }
5595 5595
         }
@@ -5643,7 +5643,7 @@  discard block
 block discarded – undo
5643 5643
      */
5644 5644
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5645 5645
     {
5646
-        if (! is_array($query_params)) {
5646
+        if ( ! is_array($query_params)) {
5647 5647
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5648 5648
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5649 5649
                     gettype($query_params)), '4.6.0');
@@ -5739,7 +5739,7 @@  discard block
 block discarded – undo
5739 5739
      */
5740 5740
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5741 5741
     {
5742
-        if (! $this->has_primary_key_field()) {
5742
+        if ( ! $this->has_primary_key_field()) {
5743 5743
             if (WP_DEBUG) {
5744 5744
                 EE_Error::add_error(
5745 5745
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5752,7 +5752,7 @@  discard block
 block discarded – undo
5752 5752
         $IDs = array();
5753 5753
         foreach ($model_objects as $model_object) {
5754 5754
             $id = $model_object->ID();
5755
-            if (! $id) {
5755
+            if ( ! $id) {
5756 5756
                 if ($filter_out_empty_ids) {
5757 5757
                     continue;
5758 5758
                 }
@@ -5848,8 +5848,8 @@  discard block
 block discarded – undo
5848 5848
         $missing_caps = array();
5849 5849
         $cap_restrictions = $this->cap_restrictions($context);
5850 5850
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5851
-            if (! EE_Capabilities::instance()
5852
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5851
+            if ( ! EE_Capabilities::instance()
5852
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5853 5853
             ) {
5854 5854
                 $missing_caps[$cap] = $restriction_if_no_cap;
5855 5855
             }
@@ -6001,7 +6001,7 @@  discard block
 block discarded – undo
6001 6001
     {
6002 6002
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6003 6003
             if ($query_param_key === $logic_query_param_key
6004
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6004
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6005 6005
             ) {
6006 6006
                 return true;
6007 6007
             }
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 1 patch
Indentation   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -17,413 +17,413 @@
 block discarded – undo
17 17
 class EEM_Attendee extends EEM_CPT_Base
18 18
 {
19 19
 
20
-    // private instance of the Attendee object
21
-    protected static $_instance = null;
20
+	// private instance of the Attendee object
21
+	protected static $_instance = null;
22 22
 
23
-    /**
24
-     * QST_system for questions are strings not integers now,
25
-     * so these constants are deprecated.
26
-     * Please instead use the EEM_Attendee::system_question_* constants
27
-     *
28
-     * @deprecated
29
-     */
30
-    const fname_question_id = 1;
23
+	/**
24
+	 * QST_system for questions are strings not integers now,
25
+	 * so these constants are deprecated.
26
+	 * Please instead use the EEM_Attendee::system_question_* constants
27
+	 *
28
+	 * @deprecated
29
+	 */
30
+	const fname_question_id = 1;
31 31
 
32
-    /**
33
-     * @deprecated
34
-     */
35
-    const lname_question_id = 2;
32
+	/**
33
+	 * @deprecated
34
+	 */
35
+	const lname_question_id = 2;
36 36
 
37 37
 
38
-    /**
39
-     * @deprecated
40
-     */
41
-    const email_question_id = 3;
38
+	/**
39
+	 * @deprecated
40
+	 */
41
+	const email_question_id = 3;
42 42
 
43 43
 
44
-    /**
45
-     * @deprecated
46
-     */
47
-    const address_question_id = 4;
44
+	/**
45
+	 * @deprecated
46
+	 */
47
+	const address_question_id = 4;
48 48
 
49 49
 
50
-    /**
51
-     * @deprecated
52
-     */
53
-    const address2_question_id = 5;
54
-
55
-
56
-    /**
57
-     * @deprecated
58
-     */
59
-    const city_question_id = 6;
60
-
61
-
62
-    /**
63
-     * @deprecated
64
-     */
65
-    const state_question_id = 7;
66
-
67
-
68
-    /**
69
-     * @deprecated
70
-     */
71
-    const country_question_id = 8;
72
-
73
-
74
-    /**
75
-     * @deprecated
76
-     */
77
-    const zip_question_id = 9;
78
-
79
-
80
-    /**
81
-     * @deprecated
82
-     */
83
-    const phone_question_id = 10;
84
-
85
-    /**
86
-     * When looking for questions that correspond to attendee fields,
87
-     * look for the question with this QST_system value.
88
-     * These replace the old constants like EEM_Attendee::*_question_id
89
-     */
90
-    const system_question_fname = 'fname';
91
-
92
-    const system_question_lname = 'lname';
93
-
94
-    const system_question_email = 'email';
95
-
96
-    const system_question_address = 'address';
97
-
98
-    const system_question_address2 = 'address2';
99
-
100
-    const system_question_city = 'city';
101
-
102
-    const system_question_state = 'state';
103
-
104
-    const system_question_country = 'country';
105
-
106
-    const system_question_zip = 'zip';
107
-
108
-    const system_question_phone = 'phone';
109
-
110
-    /**
111
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
112
-     * also all the values of QST_system in the questions table, and values
113
-     * are their corresponding Attendee field names
114
-     *
115
-     * @var array
116
-     */
117
-    protected $_system_question_to_attendee_field_name = array(
118
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
119
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
120
-        EEM_Attendee::system_question_email    => 'ATT_email',
121
-        EEM_Attendee::system_question_address  => 'ATT_address',
122
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
123
-        EEM_Attendee::system_question_city     => 'ATT_city',
124
-        EEM_Attendee::system_question_state    => 'STA_ID',
125
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
126
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
127
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
128
-    );
129
-
130
-
131
-
132
-    /**
133
-     * EEM_Attendee constructor.
134
-     *
135
-     * @param null              $timezone
136
-     * @param ModelFieldFactory $model_field_factory
137
-     * @throws EE_Error
138
-     * @throws InvalidArgumentException
139
-     */
140
-    protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
141
-    {
142
-        $this->singular_item = esc_html__('Attendee', 'event_espresso');
143
-        $this->plural_item = esc_html__('Attendees', 'event_espresso');
144
-        $this->_tables = array(
145
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
146
-            'Attendee_Meta' => new EE_Secondary_Table(
147
-                'esp_attendee_meta',
148
-                'ATTM_ID',
149
-                'ATT_ID'
150
-            ),
151
-        );
152
-        $this->_fields = array(
153
-            'Attendee_CPT'  => array(
154
-                'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
155
-                    'ID',
156
-                    esc_html__('Attendee ID', 'event_espresso')
157
-                ),
158
-                'ATT_full_name' => $model_field_factory->createPlainTextField(
159
-                    'post_title',
160
-                    esc_html__('Attendee Full Name', 'event_espresso'),
161
-                    false,
162
-                    esc_html__('Unknown', 'event_espresso')
163
-                ),
164
-                'ATT_bio'       => $model_field_factory->createPostContentField(
165
-                    'post_content',
166
-                    esc_html__('Attendee Biography', 'event_espresso'),
167
-                    false,
168
-                    esc_html__('No Biography Provided', 'event_espresso')
169
-                ),
170
-                'ATT_slug'      => $model_field_factory->createSlugField(
171
-                    'post_name',
172
-                    esc_html__('Attendee URL Slug', 'event_espresso')
173
-                ),
174
-                'ATT_created'   => $model_field_factory->createDatetimeField(
175
-                    'post_date',
176
-                    esc_html__('Time Attendee Created', 'event_espresso')
177
-                ),
178
-                'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
179
-                    'post_excerpt',
180
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
181
-                    true,
182
-                    esc_html__('No Biography Provided', 'event_espresso')
183
-                ),
184
-                'ATT_modified'  => $model_field_factory->createDatetimeField(
185
-                    'post_modified',
186
-                    esc_html__('Time Attendee Last Modified', 'event_espresso')
187
-                ),
188
-                'ATT_author'    => $model_field_factory->createWpUserField(
189
-                    'post_author',
190
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
191
-                    false
192
-                ),
193
-                'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
194
-                    'post_parent',
195
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
196
-                    false,
197
-                    0
198
-                ),
199
-                'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
200
-                'status'        => $model_field_factory->createWpPostStatusField(
201
-                    'post_status',
202
-                    esc_html__('Attendee Status', 'event_espresso'),
203
-                    false,
204
-                    'publish'
205
-                ),
206
-            ),
207
-            'Attendee_Meta' => array(
208
-                'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
209
-                    'ATTM_ID',
210
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
211
-                    false
212
-                ),
213
-                'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
214
-                    'ATT_ID',
215
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
216
-                    false
217
-                ),
218
-                'ATT_fname'    => $model_field_factory->createPlainTextField(
219
-                    'ATT_fname',
220
-                    esc_html__('First Name', 'event_espresso')
221
-                ),
222
-                'ATT_lname'    => $model_field_factory->createPlainTextField(
223
-                    'ATT_lname',
224
-                    esc_html__('Last Name', 'event_espresso')
225
-                ),
226
-                'ATT_address'  => $model_field_factory->createPlainTextField(
227
-                    'ATT_address',
228
-                    esc_html__('Address Part 1', 'event_espresso')
229
-                ),
230
-                'ATT_address2' => $model_field_factory->createPlainTextField(
231
-                    'ATT_address2',
232
-                    esc_html__('Address Part 2', 'event_espresso')
233
-                ),
234
-                'ATT_city'     => $model_field_factory->createPlainTextField(
235
-                    'ATT_city',
236
-                    esc_html__('City', 'event_espresso')
237
-                ),
238
-                'STA_ID'       => $model_field_factory->createForeignKeyIntField(
239
-                    'STA_ID',
240
-                    esc_html__('State', 'event_espresso'),
241
-                    true,
242
-                    0,
243
-                    'State'
244
-                ),
245
-                'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
246
-                    'CNT_ISO',
247
-                    esc_html__('Country', 'event_espresso'),
248
-                    true,
249
-                    '',
250
-                    'Country'
251
-                ),
252
-                'ATT_zip'      => $model_field_factory->createPlainTextField(
253
-                    'ATT_zip',
254
-                    esc_html__('ZIP/Postal Code', 'event_espresso')
255
-                ),
256
-                'ATT_email'    => $model_field_factory->createEmailField(
257
-                    'ATT_email',
258
-                    esc_html__('Email Address', 'event_espresso')
259
-                ),
260
-                'ATT_phone'    => $model_field_factory->createPlainTextField(
261
-                    'ATT_phone',
262
-                    esc_html__('Phone', 'event_espresso')
263
-                ),
264
-            ),
265
-        );
266
-        $this->_model_relations = array(
267
-            'Registration'      => new EE_Has_Many_Relation(),
268
-            'State'             => new EE_Belongs_To_Relation(),
269
-            'Country'           => new EE_Belongs_To_Relation(),
270
-            'Event'             => new EE_HABTM_Relation('Registration', false),
271
-            'WP_User'           => new EE_Belongs_To_Relation(),
272
-            'Message'           => new EE_Has_Many_Any_Relation(false),
273
-            //allow deletion of attendees even if they have messages in the queue for them.
274
-            'Term_Relationship' => new EE_Has_Many_Relation(),
275
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
276
-        );
277
-        $this->_caps_slug = 'contacts';
278
-        parent::__construct($timezone);
279
-    }
280
-
281
-
282
-
283
-    /**
284
-     * Gets the name of the field on the attendee model corresponding to the system question string
285
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
286
-     *
287
-     * @param string $system_question_string
288
-     * @return string|null if not found
289
-     */
290
-    public function get_attendee_field_for_system_question($system_question_string)
291
-    {
292
-        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
293
-            ? $this->_system_question_to_attendee_field_name[$system_question_string]
294
-            : null;
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
301
-     *
302
-     * @return array
303
-     */
304
-    public function system_question_to_attendee_field_mapping()
305
-    {
306
-        return $this->_system_question_to_attendee_field_name;
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
313
-     *
314
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
315
-     * @return EE_Attendee[]|EE_Base_Class[]
316
-     * @throws EE_Error
317
-     */
318
-    public function get_attendees_for_transaction($transaction_id_or_obj)
319
-    {
320
-        return $this->get_all(
321
-            array(
322
-                array(
323
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
324
-                        ? $transaction_id_or_obj->ID()
325
-                        : $transaction_id_or_obj,
326
-                ),
327
-            )
328
-        );
329
-    }
330
-
331
-
332
-
333
-    /**
334
-     * retrieve  a single attendee from db via their ID
335
-     *
336
-     * @param $ATT_ID
337
-     * @return mixed array on success, FALSE on fail
338
-     * @deprecated
339
-     */
340
-    public function get_attendee_by_ID($ATT_ID = false)
341
-    {
342
-        // retrieve a particular EE_Attendee
343
-        return $this->get_one_by_ID($ATT_ID);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * retrieve  a single attendee from db via their ID
350
-     *
351
-     * @param array $where_cols_n_values
352
-     * @return mixed array on success, FALSE on fail
353
-     * @throws EE_Error
354
-     */
355
-    public function get_attendee($where_cols_n_values = array())
356
-    {
357
-        if (empty($where_cols_n_values)) {
358
-            return false;
359
-        }
360
-        $attendee = $this->get_all(array($where_cols_n_values));
361
-        if (! empty($attendee)) {
362
-            return array_shift($attendee);
363
-        }
364
-        return false;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * Search for an existing Attendee record in the DB
371
-     *
372
-     * @param array $where_cols_n_values
373
-     * @return bool|mixed
374
-     * @throws EE_Error
375
-     */
376
-    public function find_existing_attendee($where_cols_n_values = null)
377
-    {
378
-        // search by combo of first and last names plus the email address
379
-        $attendee_data_keys = array(
380
-            'ATT_fname' => $this->_ATT_fname,
381
-            'ATT_lname' => $this->_ATT_lname,
382
-            'ATT_email' => $this->_ATT_email,
383
-        );
384
-        // no search params means attendee object already exists.
385
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
386
-            ? $where_cols_n_values
387
-            : $attendee_data_keys;
388
-        $valid_data = true;
389
-        // check for required values
390
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
391
-            ? $valid_data
392
-            : false;
393
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
394
-            ? $valid_data
395
-            : false;
396
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
397
-            ? $valid_data
398
-            : false;
399
-        if ($valid_data) {
400
-            $attendee = $this->get_attendee($where_cols_n_values);
401
-            if ($attendee instanceof EE_Attendee) {
402
-                return $attendee;
403
-            }
404
-        }
405
-        return false;
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Takes an incoming array of EE_Registration ids
412
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
413
-     *
414
-     * @since  4.3.0
415
-     * @param  array $ids array of EE_Registration ids
416
-     * @return EE_Attendee[]|EE_Base_Class[]
417
-     * @throws EE_Error
418
-     */
419
-    public function get_array_of_contacts_from_reg_ids($ids)
420
-    {
421
-        $ids = (array)$ids;
422
-        $_where = array(
423
-            'Registration.REG_ID' => array('in', $ids),
424
-        );
425
-        return $this->get_all(array($_where));
426
-    }
50
+	/**
51
+	 * @deprecated
52
+	 */
53
+	const address2_question_id = 5;
54
+
55
+
56
+	/**
57
+	 * @deprecated
58
+	 */
59
+	const city_question_id = 6;
60
+
61
+
62
+	/**
63
+	 * @deprecated
64
+	 */
65
+	const state_question_id = 7;
66
+
67
+
68
+	/**
69
+	 * @deprecated
70
+	 */
71
+	const country_question_id = 8;
72
+
73
+
74
+	/**
75
+	 * @deprecated
76
+	 */
77
+	const zip_question_id = 9;
78
+
79
+
80
+	/**
81
+	 * @deprecated
82
+	 */
83
+	const phone_question_id = 10;
84
+
85
+	/**
86
+	 * When looking for questions that correspond to attendee fields,
87
+	 * look for the question with this QST_system value.
88
+	 * These replace the old constants like EEM_Attendee::*_question_id
89
+	 */
90
+	const system_question_fname = 'fname';
91
+
92
+	const system_question_lname = 'lname';
93
+
94
+	const system_question_email = 'email';
95
+
96
+	const system_question_address = 'address';
97
+
98
+	const system_question_address2 = 'address2';
99
+
100
+	const system_question_city = 'city';
101
+
102
+	const system_question_state = 'state';
103
+
104
+	const system_question_country = 'country';
105
+
106
+	const system_question_zip = 'zip';
107
+
108
+	const system_question_phone = 'phone';
109
+
110
+	/**
111
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
112
+	 * also all the values of QST_system in the questions table, and values
113
+	 * are their corresponding Attendee field names
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $_system_question_to_attendee_field_name = array(
118
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
119
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
120
+		EEM_Attendee::system_question_email    => 'ATT_email',
121
+		EEM_Attendee::system_question_address  => 'ATT_address',
122
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
123
+		EEM_Attendee::system_question_city     => 'ATT_city',
124
+		EEM_Attendee::system_question_state    => 'STA_ID',
125
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
126
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
127
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
128
+	);
129
+
130
+
131
+
132
+	/**
133
+	 * EEM_Attendee constructor.
134
+	 *
135
+	 * @param null              $timezone
136
+	 * @param ModelFieldFactory $model_field_factory
137
+	 * @throws EE_Error
138
+	 * @throws InvalidArgumentException
139
+	 */
140
+	protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
141
+	{
142
+		$this->singular_item = esc_html__('Attendee', 'event_espresso');
143
+		$this->plural_item = esc_html__('Attendees', 'event_espresso');
144
+		$this->_tables = array(
145
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
146
+			'Attendee_Meta' => new EE_Secondary_Table(
147
+				'esp_attendee_meta',
148
+				'ATTM_ID',
149
+				'ATT_ID'
150
+			),
151
+		);
152
+		$this->_fields = array(
153
+			'Attendee_CPT'  => array(
154
+				'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
155
+					'ID',
156
+					esc_html__('Attendee ID', 'event_espresso')
157
+				),
158
+				'ATT_full_name' => $model_field_factory->createPlainTextField(
159
+					'post_title',
160
+					esc_html__('Attendee Full Name', 'event_espresso'),
161
+					false,
162
+					esc_html__('Unknown', 'event_espresso')
163
+				),
164
+				'ATT_bio'       => $model_field_factory->createPostContentField(
165
+					'post_content',
166
+					esc_html__('Attendee Biography', 'event_espresso'),
167
+					false,
168
+					esc_html__('No Biography Provided', 'event_espresso')
169
+				),
170
+				'ATT_slug'      => $model_field_factory->createSlugField(
171
+					'post_name',
172
+					esc_html__('Attendee URL Slug', 'event_espresso')
173
+				),
174
+				'ATT_created'   => $model_field_factory->createDatetimeField(
175
+					'post_date',
176
+					esc_html__('Time Attendee Created', 'event_espresso')
177
+				),
178
+				'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
179
+					'post_excerpt',
180
+					esc_html__('Attendee Short Biography', 'event_espresso'),
181
+					true,
182
+					esc_html__('No Biography Provided', 'event_espresso')
183
+				),
184
+				'ATT_modified'  => $model_field_factory->createDatetimeField(
185
+					'post_modified',
186
+					esc_html__('Time Attendee Last Modified', 'event_espresso')
187
+				),
188
+				'ATT_author'    => $model_field_factory->createWpUserField(
189
+					'post_author',
190
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
191
+					false
192
+				),
193
+				'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
194
+					'post_parent',
195
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
196
+					false,
197
+					0
198
+				),
199
+				'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
200
+				'status'        => $model_field_factory->createWpPostStatusField(
201
+					'post_status',
202
+					esc_html__('Attendee Status', 'event_espresso'),
203
+					false,
204
+					'publish'
205
+				),
206
+			),
207
+			'Attendee_Meta' => array(
208
+				'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
209
+					'ATTM_ID',
210
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
211
+					false
212
+				),
213
+				'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
214
+					'ATT_ID',
215
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
216
+					false
217
+				),
218
+				'ATT_fname'    => $model_field_factory->createPlainTextField(
219
+					'ATT_fname',
220
+					esc_html__('First Name', 'event_espresso')
221
+				),
222
+				'ATT_lname'    => $model_field_factory->createPlainTextField(
223
+					'ATT_lname',
224
+					esc_html__('Last Name', 'event_espresso')
225
+				),
226
+				'ATT_address'  => $model_field_factory->createPlainTextField(
227
+					'ATT_address',
228
+					esc_html__('Address Part 1', 'event_espresso')
229
+				),
230
+				'ATT_address2' => $model_field_factory->createPlainTextField(
231
+					'ATT_address2',
232
+					esc_html__('Address Part 2', 'event_espresso')
233
+				),
234
+				'ATT_city'     => $model_field_factory->createPlainTextField(
235
+					'ATT_city',
236
+					esc_html__('City', 'event_espresso')
237
+				),
238
+				'STA_ID'       => $model_field_factory->createForeignKeyIntField(
239
+					'STA_ID',
240
+					esc_html__('State', 'event_espresso'),
241
+					true,
242
+					0,
243
+					'State'
244
+				),
245
+				'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
246
+					'CNT_ISO',
247
+					esc_html__('Country', 'event_espresso'),
248
+					true,
249
+					'',
250
+					'Country'
251
+				),
252
+				'ATT_zip'      => $model_field_factory->createPlainTextField(
253
+					'ATT_zip',
254
+					esc_html__('ZIP/Postal Code', 'event_espresso')
255
+				),
256
+				'ATT_email'    => $model_field_factory->createEmailField(
257
+					'ATT_email',
258
+					esc_html__('Email Address', 'event_espresso')
259
+				),
260
+				'ATT_phone'    => $model_field_factory->createPlainTextField(
261
+					'ATT_phone',
262
+					esc_html__('Phone', 'event_espresso')
263
+				),
264
+			),
265
+		);
266
+		$this->_model_relations = array(
267
+			'Registration'      => new EE_Has_Many_Relation(),
268
+			'State'             => new EE_Belongs_To_Relation(),
269
+			'Country'           => new EE_Belongs_To_Relation(),
270
+			'Event'             => new EE_HABTM_Relation('Registration', false),
271
+			'WP_User'           => new EE_Belongs_To_Relation(),
272
+			'Message'           => new EE_Has_Many_Any_Relation(false),
273
+			//allow deletion of attendees even if they have messages in the queue for them.
274
+			'Term_Relationship' => new EE_Has_Many_Relation(),
275
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
276
+		);
277
+		$this->_caps_slug = 'contacts';
278
+		parent::__construct($timezone);
279
+	}
280
+
281
+
282
+
283
+	/**
284
+	 * Gets the name of the field on the attendee model corresponding to the system question string
285
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
286
+	 *
287
+	 * @param string $system_question_string
288
+	 * @return string|null if not found
289
+	 */
290
+	public function get_attendee_field_for_system_question($system_question_string)
291
+	{
292
+		return isset($this->_system_question_to_attendee_field_name[$system_question_string])
293
+			? $this->_system_question_to_attendee_field_name[$system_question_string]
294
+			: null;
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
301
+	 *
302
+	 * @return array
303
+	 */
304
+	public function system_question_to_attendee_field_mapping()
305
+	{
306
+		return $this->_system_question_to_attendee_field_name;
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
313
+	 *
314
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
315
+	 * @return EE_Attendee[]|EE_Base_Class[]
316
+	 * @throws EE_Error
317
+	 */
318
+	public function get_attendees_for_transaction($transaction_id_or_obj)
319
+	{
320
+		return $this->get_all(
321
+			array(
322
+				array(
323
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
324
+						? $transaction_id_or_obj->ID()
325
+						: $transaction_id_or_obj,
326
+				),
327
+			)
328
+		);
329
+	}
330
+
331
+
332
+
333
+	/**
334
+	 * retrieve  a single attendee from db via their ID
335
+	 *
336
+	 * @param $ATT_ID
337
+	 * @return mixed array on success, FALSE on fail
338
+	 * @deprecated
339
+	 */
340
+	public function get_attendee_by_ID($ATT_ID = false)
341
+	{
342
+		// retrieve a particular EE_Attendee
343
+		return $this->get_one_by_ID($ATT_ID);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * retrieve  a single attendee from db via their ID
350
+	 *
351
+	 * @param array $where_cols_n_values
352
+	 * @return mixed array on success, FALSE on fail
353
+	 * @throws EE_Error
354
+	 */
355
+	public function get_attendee($where_cols_n_values = array())
356
+	{
357
+		if (empty($where_cols_n_values)) {
358
+			return false;
359
+		}
360
+		$attendee = $this->get_all(array($where_cols_n_values));
361
+		if (! empty($attendee)) {
362
+			return array_shift($attendee);
363
+		}
364
+		return false;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * Search for an existing Attendee record in the DB
371
+	 *
372
+	 * @param array $where_cols_n_values
373
+	 * @return bool|mixed
374
+	 * @throws EE_Error
375
+	 */
376
+	public function find_existing_attendee($where_cols_n_values = null)
377
+	{
378
+		// search by combo of first and last names plus the email address
379
+		$attendee_data_keys = array(
380
+			'ATT_fname' => $this->_ATT_fname,
381
+			'ATT_lname' => $this->_ATT_lname,
382
+			'ATT_email' => $this->_ATT_email,
383
+		);
384
+		// no search params means attendee object already exists.
385
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
386
+			? $where_cols_n_values
387
+			: $attendee_data_keys;
388
+		$valid_data = true;
389
+		// check for required values
390
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
391
+			? $valid_data
392
+			: false;
393
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
394
+			? $valid_data
395
+			: false;
396
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
397
+			? $valid_data
398
+			: false;
399
+		if ($valid_data) {
400
+			$attendee = $this->get_attendee($where_cols_n_values);
401
+			if ($attendee instanceof EE_Attendee) {
402
+				return $attendee;
403
+			}
404
+		}
405
+		return false;
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Takes an incoming array of EE_Registration ids
412
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
413
+	 *
414
+	 * @since  4.3.0
415
+	 * @param  array $ids array of EE_Registration ids
416
+	 * @return EE_Attendee[]|EE_Base_Class[]
417
+	 * @throws EE_Error
418
+	 */
419
+	public function get_array_of_contacts_from_reg_ids($ids)
420
+	{
421
+		$ids = (array)$ids;
422
+		$_where = array(
423
+			'Registration.REG_ID' => array('in', $ids),
424
+		);
425
+		return $this->get_all(array($_where));
426
+	}
427 427
 
428 428
 
429 429
 }
Please login to merge, or discard this patch.
core/libraries/payment_methods/EEI_Payment_Method_Interfaces.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -99,34 +99,34 @@  discard block
 block discarded – undo
99 99
 	 */
100 100
 	public function set_extra_accntng($extra_accounting_info);
101 101
 
102
-    /**
103
-     * Gets the first event for this payment (it's possible that it could be for multiple)
104
-     *
105
-     * @param EE_Payment $payment
106
-     * @return EE_Event|null
107
-     */
108
-    public function get_first_event();
109
-
110
-    /**
111
-     * Gets the name of the first event for which is being paid
112
-     *
113
-     * @param EE_Payment $payment
114
-     * @return string
115
-     */
116
-    public function get_first_event_name();
117
-
118
-    /**
119
-     * Returns the payment's transaction's primary registration
120
-     *
121
-     * @return EE_Registration|null
122
-     */
123
-    public function get_primary_registration();
124
-
125
-    /**
126
-     * Gets the payment's transaction's primary registration's attendee, or null
127
-     * @return EE_Attendee|null
128
-     */
129
-    public function get_primary_attendee();
102
+	/**
103
+	 * Gets the first event for this payment (it's possible that it could be for multiple)
104
+	 *
105
+	 * @param EE_Payment $payment
106
+	 * @return EE_Event|null
107
+	 */
108
+	public function get_first_event();
109
+
110
+	/**
111
+	 * Gets the name of the first event for which is being paid
112
+	 *
113
+	 * @param EE_Payment $payment
114
+	 * @return string
115
+	 */
116
+	public function get_first_event_name();
117
+
118
+	/**
119
+	 * Returns the payment's transaction's primary registration
120
+	 *
121
+	 * @return EE_Registration|null
122
+	 */
123
+	public function get_primary_registration();
124
+
125
+	/**
126
+	 * Gets the payment's transaction's primary registration's attendee, or null
127
+	 * @return EE_Attendee|null
128
+	 */
129
+	public function get_primary_attendee();
130 130
 }
131 131
 
132 132
 
@@ -164,13 +164,13 @@  discard block
 block discarded – undo
164 164
 
165 165
 
166 166
 
167
-    /**
168
-     * Function that returns an instance of this class.
169
-     *
170
-     * @param null              $timezone
171
-     * @param ModelFieldFactory $model_field_factory If not provided, this class needs to find it itself
172
-     * @return EEMI_Payment
173
-     */
167
+	/**
168
+	 * Function that returns an instance of this class.
169
+	 *
170
+	 * @param null              $timezone
171
+	 * @param ModelFieldFactory $model_field_factory If not provided, this class needs to find it itself
172
+	 * @return EEMI_Payment
173
+	 */
174 174
 	public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null);
175 175
 
176 176
 	/**
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_List_Table.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -152,7 +152,7 @@
 block discarded – undo
152 152
 
153 153
     /**
154 154
      * @param EE_Event $item
155
-     * @return mixed|string
155
+     * @return string
156 156
      * @throws EE_Error
157 157
      */
158 158
     public function column_id(EE_Event $item)
Please login to merge, or discard this patch.
Indentation   +541 added lines, -541 removed lines patch added patch discarded remove patch
@@ -18,545 +18,545 @@
 block discarded – undo
18 18
 class Events_Admin_List_Table extends EE_Admin_List_Table
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Datetime
23
-     */
24
-    private $_dtt;
25
-
26
-
27
-
28
-    /**
29
-     * Initial setup of data properties for the list table.
30
-     */
31
-    protected function _setup_data()
32
-    {
33
-        $this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
34
-        $this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
35
-    }
36
-
37
-
38
-
39
-    /**
40
-     * Set up of additional properties for the list table.
41
-     */
42
-    protected function _set_properties()
43
-    {
44
-        $this->_wp_list_args = array(
45
-            'singular' => esc_html__('event', 'event_espresso'),
46
-            'plural'   => esc_html__('events', 'event_espresso'),
47
-            'ajax'     => true, //for now
48
-            'screen'   => $this->_admin_page->get_current_screen()->id,
49
-        );
50
-        $this->_columns = array(
51
-            'cb'              => '<input type="checkbox" />',
52
-            'id'              => esc_html__('ID', 'event_espresso'),
53
-            'name'            => esc_html__('Name', 'event_espresso'),
54
-            'author'          => esc_html__('Author', 'event_espresso'),
55
-            'venue'           => esc_html__('Venue', 'event_espresso'),
56
-            'start_date_time' => esc_html__('Event Start', 'event_espresso'),
57
-            'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
58
-            'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
59
-                                 . '</span>',
60
-            //'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
61
-            'actions'         => esc_html__('Actions', 'event_espresso'),
62
-        );
63
-        $this->_sortable_columns = array(
64
-            'id'              => array('EVT_ID' => true),
65
-            'name'            => array('EVT_name' => false),
66
-            'author'          => array('EVT_wp_user' => false),
67
-            'venue'           => array('Venue.VNU_name' => false),
68
-            'start_date_time' => array('Datetime.DTT_EVT_start' => false),
69
-            'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
70
-        );
71
-        $this->_primary_column = 'id';
72
-        $this->_hidden_columns = array('author');
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     * @return array
79
-     */
80
-    protected function _get_table_filters()
81
-    {
82
-        return array(); //no filters with decaf
83
-    }
84
-
85
-
86
-
87
-    /**
88
-     * Setup of views properties.
89
-     *
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws InvalidArgumentException
93
-     */
94
-    protected function _add_view_counts()
95
-    {
96
-        $this->_views['all']['count'] = $this->_admin_page->total_events();
97
-        $this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
98
-        if (EE_Registry::instance()->CAP->current_user_can(
99
-            'ee_delete_events',
100
-            'espresso_events_trash_events'
101
-        )) {
102
-            $this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
103
-        }
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     * @param EE_Event $item
110
-     * @return string
111
-     * @throws EE_Error
112
-     */
113
-    protected function _get_row_class($item)
114
-    {
115
-        $class = parent::_get_row_class($item);
116
-        //add status class
117
-        $class .= $item instanceof EE_Event
118
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
119
-            : '';
120
-        if ($this->_has_checkbox_column) {
121
-            $class .= ' has-checkbox-column';
122
-        }
123
-        return $class;
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * @param EE_Event $item
130
-     * @return string
131
-     * @throws EE_Error
132
-     */
133
-    public function column_status(EE_Event $item)
134
-    {
135
-        return '<span class="ee-status-strip ee-status-strip-td event-status-'
136
-               . $item->get_active_status()
137
-               . '"></span>';
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @param  EE_Event $item
144
-     * @return string
145
-     * @throws EE_Error
146
-     */
147
-    public function column_cb($item)
148
-    {
149
-        if (! $item instanceof EE_Event) {
150
-            return '';
151
-        }
152
-        $this->_dtt = $item->primary_datetime(); //set this for use in other columns
153
-        //does event have any attached registrations?
154
-        $regs = $item->count_related('Registration');
155
-        return $regs > 0 && $this->_view === 'trash'
156
-            ? '<span class="ee-lock-icon"></span>'
157
-            : sprintf(
158
-                '<input type="checkbox" name="EVT_IDs[]" value="%s" />',
159
-                $item->ID()
160
-            );
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     * @param EE_Event $item
167
-     * @return mixed|string
168
-     * @throws EE_Error
169
-     */
170
-    public function column_id(EE_Event $item)
171
-    {
172
-        $content = $item->ID();
173
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
174
-        return $content;
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * @param EE_Event $item
181
-     * @return string
182
-     * @throws EE_Error
183
-     * @throws InvalidArgumentException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public function column_name(EE_Event $item)
188
-    {
189
-        $edit_query_args = array(
190
-            'action' => 'edit',
191
-            'post'   => $item->ID(),
192
-        );
193
-        $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
194
-        $actions = $this->_column_name_action_setup($item);
195
-        $status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196
-        $content = '<strong><a class="row-title" href="'
197
-                   . $edit_link . '">'
198
-                   . $item->name()
199
-                   . '</a></strong>'
200
-                   . $status;
201
-        $content .= '<br><span class="ee-status-text-small">'
202
-                    . EEH_Template::pretty_status(
203
-                $item->get_active_status(),
204
-                false,
205
-                'sentence'
206
-            )
207
-                    . '</span>';
208
-        $content .= $this->row_actions($actions);
209
-        return $content;
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * Just a method for setting up the actions for the name column
216
-     *
217
-     * @param EE_Event $item
218
-     * @return array array of actions
219
-     * @throws EE_Error
220
-     * @throws InvalidArgumentException
221
-     * @throws InvalidDataTypeException
222
-     * @throws InvalidInterfaceException
223
-     */
224
-    protected function _column_name_action_setup(EE_Event $item)
225
-    {
226
-        //todo: remove when attendees is active
227
-        if (! defined('REG_ADMIN_URL')) {
228
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229
-        }
230
-        $actions = array();
231
-        $restore_event_link = '';
232
-        $delete_event_link = '';
233
-        $trash_event_link = '';
234
-        if (EE_Registry::instance()->CAP->current_user_can(
235
-            'ee_edit_event',
236
-            'espresso_events_edit',
237
-            $item->ID()
238
-        )) {
239
-            $edit_query_args = array(
240
-                'action' => 'edit',
241
-                'post'   => $item->ID(),
242
-            );
243
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
-            $actions['edit'] = '<a href="' . $edit_link . '"'
245
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
246
-                               . esc_html__('Edit', 'event_espresso')
247
-                               . '</a>';
248
-        }
249
-        if (
250
-            EE_Registry::instance()->CAP->current_user_can(
251
-                'ee_read_registrations',
252
-                'espresso_registrations_view_registration'
253
-            )
254
-            && EE_Registry::instance()->CAP->current_user_can(
255
-                'ee_read_event',
256
-                'espresso_registrations_view_registration',
257
-                $item->ID()
258
-            )
259
-        ) {
260
-            $attendees_query_args = array(
261
-                'action'   => 'default',
262
-                'event_id' => $item->ID(),
263
-            );
264
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
266
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
267
-                                    . esc_html__('Registrations', 'event_espresso')
268
-                                    . '</a>';
269
-        }
270
-        if (
271
-        EE_Registry::instance()->CAP->current_user_can(
272
-            'ee_delete_event',
273
-            'espresso_events_trash_event',
274
-            $item->ID()
275
-        )
276
-        ) {
277
-            $trash_event_query_args = array(
278
-                'action' => 'trash_event',
279
-                'EVT_ID' => $item->ID(),
280
-            );
281
-            $trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
282
-                $trash_event_query_args,
283
-                EVENTS_ADMIN_URL
284
-            );
285
-        }
286
-        if (
287
-        EE_Registry::instance()->CAP->current_user_can(
288
-            'ee_delete_event',
289
-            'espresso_events_restore_event',
290
-            $item->ID()
291
-        )
292
-        ) {
293
-            $restore_event_query_args = array(
294
-                'action' => 'restore_event',
295
-                'EVT_ID' => $item->ID(),
296
-            );
297
-            $restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
298
-                $restore_event_query_args,
299
-                EVENTS_ADMIN_URL
300
-            );
301
-        }
302
-        if (
303
-        EE_Registry::instance()->CAP->current_user_can(
304
-            'ee_delete_event',
305
-            'espresso_events_delete_event',
306
-            $item->ID()
307
-        )
308
-        ) {
309
-            $delete_event_query_args = array(
310
-                'action' => 'delete_event',
311
-                'EVT_ID' => $item->ID(),
312
-            );
313
-            $delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
314
-                $delete_event_query_args,
315
-                EVENTS_ADMIN_URL
316
-            );
317
-        }
318
-        $view_link = get_permalink($item->ID());
319
-        $actions['view'] = '<a href="' . $view_link . '"'
320
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
321
-                           . esc_html__('View', 'event_espresso')
322
-                           . '</a>';
323
-        if ($item->get('status') === 'trash') {
324
-            if (EE_Registry::instance()->CAP->current_user_can(
325
-                'ee_delete_event',
326
-                'espresso_events_restore_event',
327
-                $item->ID()
328
-            )) {
329
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
331
-                                                 . '">'
332
-                                                 . esc_html__('Restore from Trash', 'event_espresso')
333
-                                                 . '</a>';
334
-            }
335
-            if (
336
-                $item->count_related('Registration') === 0
337
-                && EE_Registry::instance()->CAP->current_user_can(
338
-                    'ee_delete_event',
339
-                    'espresso_events_delete_event',
340
-                    $item->ID()
341
-                )
342
-            ) {
343
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
344
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
345
-                                     . esc_html__('Delete Permanently', 'event_espresso')
346
-                                     . '</a>';
347
-            }
348
-        } else {
349
-            if (
350
-                EE_Registry::instance()->CAP->current_user_can(
351
-                    'ee_delete_event',
352
-                    'espresso_events_trash_event',
353
-                    $item->ID()
354
-                )
355
-            ) {
356
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
358
-                                            . esc_html__('Trash', 'event_espresso')
359
-                                            . '</a>';
360
-            }
361
-        }
362
-        return $actions;
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * @param EE_Event $item
369
-     * @return string
370
-     * @throws EE_Error
371
-     */
372
-    public function column_author(EE_Event $item)
373
-    {
374
-        //user author info
375
-        $event_author = get_userdata($item->wp_user());
376
-        $gravatar = get_avatar($item->wp_user(), '15');
377
-        //filter link
378
-        $query_args = array(
379
-            'action'      => 'default',
380
-            'EVT_wp_user' => $item->wp_user(),
381
-        );
382
-        $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
-        return $gravatar . '  <a href="' . $filter_url . '"'
384
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
385
-               . $event_author->display_name
386
-               . '</a>';
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * @param EE_Event $item
393
-     * @return string
394
-     * @throws EE_Error
395
-     */
396
-    public function column_venue(EE_Event $item)
397
-    {
398
-        $venue = $item->get_first_related('Venue');
399
-        return ! empty($venue)
400
-            ? $venue->name()
401
-            : '';
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * @param EE_Event $item
408
-     * @throws EE_Error
409
-     */
410
-    public function column_start_date_time(EE_Event $item)
411
-    {
412
-        echo ! empty($this->_dtt)
413
-            ? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
414
-            : esc_html__('No Date was saved for this Event', 'event_espresso');
415
-        //display in user's timezone?
416
-        echo ! empty($this->_dtt)
417
-            ? $this->_dtt->display_in_my_timezone(
418
-                'DTT_EVT_start',
419
-                'get_i18n_datetime',
420
-                '',
421
-                'My Timezone: '
422
-            )
423
-            : '';
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * @param EE_Event $item
430
-     * @throws EE_Error
431
-     */
432
-    public function column_reg_begins(EE_Event $item)
433
-    {
434
-        $reg_start = $item->get_ticket_with_earliest_start_time();
435
-        echo ! empty($reg_start)
436
-            ? $reg_start->get_i18n_datetime('TKT_start_date')
437
-            : esc_html__('No Tickets have been setup for this Event', 'event_espresso');
438
-        //display in user's timezone?
439
-        echo ! empty($reg_start)
440
-            ? $reg_start->display_in_my_timezone(
441
-                'TKT_start_date',
442
-                'get_i18n_datetime',
443
-                '',
444
-                'My Timezone: '
445
-            )
446
-            : '';
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * @param EE_Event $item
453
-     * @return int|string
454
-     * @throws EE_Error
455
-     * @throws InvalidArgumentException
456
-     * @throws InvalidDataTypeException
457
-     * @throws InvalidInterfaceException
458
-     */
459
-    public function column_attendees(EE_Event $item)
460
-    {
461
-        $attendees_query_args = array(
462
-            'action'   => 'default',
463
-            'event_id' => $item->ID(),
464
-        );
465
-        $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
466
-        $registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
467
-        return EE_Registry::instance()->CAP->current_user_can(
468
-            'ee_read_event',
469
-            'espresso_registrations_view_registration',
470
-            $item->ID()
471
-        )
472
-               && EE_Registry::instance()->CAP->current_user_can(
473
-            'ee_read_registrations',
474
-            'espresso_registrations_view_registration'
475
-        )
476
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
477
-            : $registered_attendees;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * @param EE_Event $item
484
-     * @return float
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     */
490
-    public function column_tkts_sold(EE_Event $item)
491
-    {
492
-        return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
493
-    }
494
-
495
-
496
-
497
-    /**
498
-     * @param EE_Event $item
499
-     * @return string
500
-     * @throws EE_Error
501
-     * @throws InvalidArgumentException
502
-     * @throws InvalidDataTypeException
503
-     * @throws InvalidInterfaceException
504
-     */
505
-    public function column_actions(EE_Event $item)
506
-    {
507
-        //todo: remove when attendees is active
508
-        if (! defined('REG_ADMIN_URL')) {
509
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510
-        }
511
-        $action_links = array();
512
-        $view_link = get_permalink($item->ID());
513
-        $action_links[] = '<a href="' . $view_link . '"'
514
-                         . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
515
-        $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516
-        if (EE_Registry::instance()->CAP->current_user_can(
517
-            'ee_edit_event',
518
-            'espresso_events_edit',
519
-            $item->ID()
520
-        )) {
521
-            $edit_query_args = array(
522
-                'action' => 'edit',
523
-                'post'   => $item->ID(),
524
-            );
525
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
-            $action_links[] = '<a href="' . $edit_link . '"'
527
-                             . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
528
-                             . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529
-                             . '</a>';
530
-        }
531
-        if (
532
-            EE_Registry::instance()->CAP->current_user_can(
533
-                'ee_read_registrations',
534
-                'espresso_registrations_view_registration'
535
-            ) && EE_Registry::instance()->CAP->current_user_can(
536
-                'ee_read_event',
537
-                'espresso_registrations_view_registration',
538
-                $item->ID()
539
-            )
540
-        ) {
541
-            $attendees_query_args = array(
542
-                'action'   => 'default',
543
-                'event_id' => $item->ID(),
544
-            );
545
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
-            $action_links[] = '<a href="' . $attendees_link . '"'
547
-                             . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
548
-                             . '<div class="dashicons dashicons-groups"></div>'
549
-                             . '</a>';
550
-        }
551
-        $action_links = apply_filters(
552
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
553
-            $action_links,
554
-            $item
555
-        );
556
-        return $this->_action_string(
557
-            implode("\n\t", $action_links),
558
-            $item,
559
-            'div'
560
-        );
561
-    }
21
+	/**
22
+	 * @var EE_Datetime
23
+	 */
24
+	private $_dtt;
25
+
26
+
27
+
28
+	/**
29
+	 * Initial setup of data properties for the list table.
30
+	 */
31
+	protected function _setup_data()
32
+	{
33
+		$this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
34
+		$this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
35
+	}
36
+
37
+
38
+
39
+	/**
40
+	 * Set up of additional properties for the list table.
41
+	 */
42
+	protected function _set_properties()
43
+	{
44
+		$this->_wp_list_args = array(
45
+			'singular' => esc_html__('event', 'event_espresso'),
46
+			'plural'   => esc_html__('events', 'event_espresso'),
47
+			'ajax'     => true, //for now
48
+			'screen'   => $this->_admin_page->get_current_screen()->id,
49
+		);
50
+		$this->_columns = array(
51
+			'cb'              => '<input type="checkbox" />',
52
+			'id'              => esc_html__('ID', 'event_espresso'),
53
+			'name'            => esc_html__('Name', 'event_espresso'),
54
+			'author'          => esc_html__('Author', 'event_espresso'),
55
+			'venue'           => esc_html__('Venue', 'event_espresso'),
56
+			'start_date_time' => esc_html__('Event Start', 'event_espresso'),
57
+			'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
58
+			'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
59
+								 . '</span>',
60
+			//'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
61
+			'actions'         => esc_html__('Actions', 'event_espresso'),
62
+		);
63
+		$this->_sortable_columns = array(
64
+			'id'              => array('EVT_ID' => true),
65
+			'name'            => array('EVT_name' => false),
66
+			'author'          => array('EVT_wp_user' => false),
67
+			'venue'           => array('Venue.VNU_name' => false),
68
+			'start_date_time' => array('Datetime.DTT_EVT_start' => false),
69
+			'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
70
+		);
71
+		$this->_primary_column = 'id';
72
+		$this->_hidden_columns = array('author');
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 * @return array
79
+	 */
80
+	protected function _get_table_filters()
81
+	{
82
+		return array(); //no filters with decaf
83
+	}
84
+
85
+
86
+
87
+	/**
88
+	 * Setup of views properties.
89
+	 *
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws InvalidArgumentException
93
+	 */
94
+	protected function _add_view_counts()
95
+	{
96
+		$this->_views['all']['count'] = $this->_admin_page->total_events();
97
+		$this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
98
+		if (EE_Registry::instance()->CAP->current_user_can(
99
+			'ee_delete_events',
100
+			'espresso_events_trash_events'
101
+		)) {
102
+			$this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
103
+		}
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 * @param EE_Event $item
110
+	 * @return string
111
+	 * @throws EE_Error
112
+	 */
113
+	protected function _get_row_class($item)
114
+	{
115
+		$class = parent::_get_row_class($item);
116
+		//add status class
117
+		$class .= $item instanceof EE_Event
118
+			? ' ee-status-strip event-status-' . $item->get_active_status()
119
+			: '';
120
+		if ($this->_has_checkbox_column) {
121
+			$class .= ' has-checkbox-column';
122
+		}
123
+		return $class;
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * @param EE_Event $item
130
+	 * @return string
131
+	 * @throws EE_Error
132
+	 */
133
+	public function column_status(EE_Event $item)
134
+	{
135
+		return '<span class="ee-status-strip ee-status-strip-td event-status-'
136
+			   . $item->get_active_status()
137
+			   . '"></span>';
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @param  EE_Event $item
144
+	 * @return string
145
+	 * @throws EE_Error
146
+	 */
147
+	public function column_cb($item)
148
+	{
149
+		if (! $item instanceof EE_Event) {
150
+			return '';
151
+		}
152
+		$this->_dtt = $item->primary_datetime(); //set this for use in other columns
153
+		//does event have any attached registrations?
154
+		$regs = $item->count_related('Registration');
155
+		return $regs > 0 && $this->_view === 'trash'
156
+			? '<span class="ee-lock-icon"></span>'
157
+			: sprintf(
158
+				'<input type="checkbox" name="EVT_IDs[]" value="%s" />',
159
+				$item->ID()
160
+			);
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 * @param EE_Event $item
167
+	 * @return mixed|string
168
+	 * @throws EE_Error
169
+	 */
170
+	public function column_id(EE_Event $item)
171
+	{
172
+		$content = $item->ID();
173
+		$content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
174
+		return $content;
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * @param EE_Event $item
181
+	 * @return string
182
+	 * @throws EE_Error
183
+	 * @throws InvalidArgumentException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public function column_name(EE_Event $item)
188
+	{
189
+		$edit_query_args = array(
190
+			'action' => 'edit',
191
+			'post'   => $item->ID(),
192
+		);
193
+		$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
194
+		$actions = $this->_column_name_action_setup($item);
195
+		$status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196
+		$content = '<strong><a class="row-title" href="'
197
+				   . $edit_link . '">'
198
+				   . $item->name()
199
+				   . '</a></strong>'
200
+				   . $status;
201
+		$content .= '<br><span class="ee-status-text-small">'
202
+					. EEH_Template::pretty_status(
203
+				$item->get_active_status(),
204
+				false,
205
+				'sentence'
206
+			)
207
+					. '</span>';
208
+		$content .= $this->row_actions($actions);
209
+		return $content;
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * Just a method for setting up the actions for the name column
216
+	 *
217
+	 * @param EE_Event $item
218
+	 * @return array array of actions
219
+	 * @throws EE_Error
220
+	 * @throws InvalidArgumentException
221
+	 * @throws InvalidDataTypeException
222
+	 * @throws InvalidInterfaceException
223
+	 */
224
+	protected function _column_name_action_setup(EE_Event $item)
225
+	{
226
+		//todo: remove when attendees is active
227
+		if (! defined('REG_ADMIN_URL')) {
228
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229
+		}
230
+		$actions = array();
231
+		$restore_event_link = '';
232
+		$delete_event_link = '';
233
+		$trash_event_link = '';
234
+		if (EE_Registry::instance()->CAP->current_user_can(
235
+			'ee_edit_event',
236
+			'espresso_events_edit',
237
+			$item->ID()
238
+		)) {
239
+			$edit_query_args = array(
240
+				'action' => 'edit',
241
+				'post'   => $item->ID(),
242
+			);
243
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
+			$actions['edit'] = '<a href="' . $edit_link . '"'
245
+							   . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
246
+							   . esc_html__('Edit', 'event_espresso')
247
+							   . '</a>';
248
+		}
249
+		if (
250
+			EE_Registry::instance()->CAP->current_user_can(
251
+				'ee_read_registrations',
252
+				'espresso_registrations_view_registration'
253
+			)
254
+			&& EE_Registry::instance()->CAP->current_user_can(
255
+				'ee_read_event',
256
+				'espresso_registrations_view_registration',
257
+				$item->ID()
258
+			)
259
+		) {
260
+			$attendees_query_args = array(
261
+				'action'   => 'default',
262
+				'event_id' => $item->ID(),
263
+			);
264
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
+			$actions['attendees'] = '<a href="' . $attendees_link . '"'
266
+									. ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
267
+									. esc_html__('Registrations', 'event_espresso')
268
+									. '</a>';
269
+		}
270
+		if (
271
+		EE_Registry::instance()->CAP->current_user_can(
272
+			'ee_delete_event',
273
+			'espresso_events_trash_event',
274
+			$item->ID()
275
+		)
276
+		) {
277
+			$trash_event_query_args = array(
278
+				'action' => 'trash_event',
279
+				'EVT_ID' => $item->ID(),
280
+			);
281
+			$trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
282
+				$trash_event_query_args,
283
+				EVENTS_ADMIN_URL
284
+			);
285
+		}
286
+		if (
287
+		EE_Registry::instance()->CAP->current_user_can(
288
+			'ee_delete_event',
289
+			'espresso_events_restore_event',
290
+			$item->ID()
291
+		)
292
+		) {
293
+			$restore_event_query_args = array(
294
+				'action' => 'restore_event',
295
+				'EVT_ID' => $item->ID(),
296
+			);
297
+			$restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
298
+				$restore_event_query_args,
299
+				EVENTS_ADMIN_URL
300
+			);
301
+		}
302
+		if (
303
+		EE_Registry::instance()->CAP->current_user_can(
304
+			'ee_delete_event',
305
+			'espresso_events_delete_event',
306
+			$item->ID()
307
+		)
308
+		) {
309
+			$delete_event_query_args = array(
310
+				'action' => 'delete_event',
311
+				'EVT_ID' => $item->ID(),
312
+			);
313
+			$delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
314
+				$delete_event_query_args,
315
+				EVENTS_ADMIN_URL
316
+			);
317
+		}
318
+		$view_link = get_permalink($item->ID());
319
+		$actions['view'] = '<a href="' . $view_link . '"'
320
+						   . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
321
+						   . esc_html__('View', 'event_espresso')
322
+						   . '</a>';
323
+		if ($item->get('status') === 'trash') {
324
+			if (EE_Registry::instance()->CAP->current_user_can(
325
+				'ee_delete_event',
326
+				'espresso_events_restore_event',
327
+				$item->ID()
328
+			)) {
329
+				$actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
+												 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
331
+												 . '">'
332
+												 . esc_html__('Restore from Trash', 'event_espresso')
333
+												 . '</a>';
334
+			}
335
+			if (
336
+				$item->count_related('Registration') === 0
337
+				&& EE_Registry::instance()->CAP->current_user_can(
338
+					'ee_delete_event',
339
+					'espresso_events_delete_event',
340
+					$item->ID()
341
+				)
342
+			) {
343
+				$actions['delete'] = '<a href="' . $delete_event_link . '"'
344
+									 . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
345
+									 . esc_html__('Delete Permanently', 'event_espresso')
346
+									 . '</a>';
347
+			}
348
+		} else {
349
+			if (
350
+				EE_Registry::instance()->CAP->current_user_can(
351
+					'ee_delete_event',
352
+					'espresso_events_trash_event',
353
+					$item->ID()
354
+				)
355
+			) {
356
+				$actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
+											. ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
358
+											. esc_html__('Trash', 'event_espresso')
359
+											. '</a>';
360
+			}
361
+		}
362
+		return $actions;
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * @param EE_Event $item
369
+	 * @return string
370
+	 * @throws EE_Error
371
+	 */
372
+	public function column_author(EE_Event $item)
373
+	{
374
+		//user author info
375
+		$event_author = get_userdata($item->wp_user());
376
+		$gravatar = get_avatar($item->wp_user(), '15');
377
+		//filter link
378
+		$query_args = array(
379
+			'action'      => 'default',
380
+			'EVT_wp_user' => $item->wp_user(),
381
+		);
382
+		$filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
+		return $gravatar . '  <a href="' . $filter_url . '"'
384
+			   . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
385
+			   . $event_author->display_name
386
+			   . '</a>';
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * @param EE_Event $item
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 */
396
+	public function column_venue(EE_Event $item)
397
+	{
398
+		$venue = $item->get_first_related('Venue');
399
+		return ! empty($venue)
400
+			? $venue->name()
401
+			: '';
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * @param EE_Event $item
408
+	 * @throws EE_Error
409
+	 */
410
+	public function column_start_date_time(EE_Event $item)
411
+	{
412
+		echo ! empty($this->_dtt)
413
+			? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
414
+			: esc_html__('No Date was saved for this Event', 'event_espresso');
415
+		//display in user's timezone?
416
+		echo ! empty($this->_dtt)
417
+			? $this->_dtt->display_in_my_timezone(
418
+				'DTT_EVT_start',
419
+				'get_i18n_datetime',
420
+				'',
421
+				'My Timezone: '
422
+			)
423
+			: '';
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * @param EE_Event $item
430
+	 * @throws EE_Error
431
+	 */
432
+	public function column_reg_begins(EE_Event $item)
433
+	{
434
+		$reg_start = $item->get_ticket_with_earliest_start_time();
435
+		echo ! empty($reg_start)
436
+			? $reg_start->get_i18n_datetime('TKT_start_date')
437
+			: esc_html__('No Tickets have been setup for this Event', 'event_espresso');
438
+		//display in user's timezone?
439
+		echo ! empty($reg_start)
440
+			? $reg_start->display_in_my_timezone(
441
+				'TKT_start_date',
442
+				'get_i18n_datetime',
443
+				'',
444
+				'My Timezone: '
445
+			)
446
+			: '';
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * @param EE_Event $item
453
+	 * @return int|string
454
+	 * @throws EE_Error
455
+	 * @throws InvalidArgumentException
456
+	 * @throws InvalidDataTypeException
457
+	 * @throws InvalidInterfaceException
458
+	 */
459
+	public function column_attendees(EE_Event $item)
460
+	{
461
+		$attendees_query_args = array(
462
+			'action'   => 'default',
463
+			'event_id' => $item->ID(),
464
+		);
465
+		$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
466
+		$registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
467
+		return EE_Registry::instance()->CAP->current_user_can(
468
+			'ee_read_event',
469
+			'espresso_registrations_view_registration',
470
+			$item->ID()
471
+		)
472
+			   && EE_Registry::instance()->CAP->current_user_can(
473
+			'ee_read_registrations',
474
+			'espresso_registrations_view_registration'
475
+		)
476
+			? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
477
+			: $registered_attendees;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * @param EE_Event $item
484
+	 * @return float
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 */
490
+	public function column_tkts_sold(EE_Event $item)
491
+	{
492
+		return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
493
+	}
494
+
495
+
496
+
497
+	/**
498
+	 * @param EE_Event $item
499
+	 * @return string
500
+	 * @throws EE_Error
501
+	 * @throws InvalidArgumentException
502
+	 * @throws InvalidDataTypeException
503
+	 * @throws InvalidInterfaceException
504
+	 */
505
+	public function column_actions(EE_Event $item)
506
+	{
507
+		//todo: remove when attendees is active
508
+		if (! defined('REG_ADMIN_URL')) {
509
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510
+		}
511
+		$action_links = array();
512
+		$view_link = get_permalink($item->ID());
513
+		$action_links[] = '<a href="' . $view_link . '"'
514
+						 . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
515
+		$action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516
+		if (EE_Registry::instance()->CAP->current_user_can(
517
+			'ee_edit_event',
518
+			'espresso_events_edit',
519
+			$item->ID()
520
+		)) {
521
+			$edit_query_args = array(
522
+				'action' => 'edit',
523
+				'post'   => $item->ID(),
524
+			);
525
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
+			$action_links[] = '<a href="' . $edit_link . '"'
527
+							 . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
528
+							 . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529
+							 . '</a>';
530
+		}
531
+		if (
532
+			EE_Registry::instance()->CAP->current_user_can(
533
+				'ee_read_registrations',
534
+				'espresso_registrations_view_registration'
535
+			) && EE_Registry::instance()->CAP->current_user_can(
536
+				'ee_read_event',
537
+				'espresso_registrations_view_registration',
538
+				$item->ID()
539
+			)
540
+		) {
541
+			$attendees_query_args = array(
542
+				'action'   => 'default',
543
+				'event_id' => $item->ID(),
544
+			);
545
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
+			$action_links[] = '<a href="' . $attendees_link . '"'
547
+							 . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
548
+							 . '<div class="dashicons dashicons-groups"></div>'
549
+							 . '</a>';
550
+		}
551
+		$action_links = apply_filters(
552
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
553
+			$action_links,
554
+			$item
555
+		);
556
+		return $this->_action_string(
557
+			implode("\n\t", $action_links),
558
+			$item,
559
+			'div'
560
+		);
561
+	}
562 562
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
         $class = parent::_get_row_class($item);
116 116
         //add status class
117 117
         $class .= $item instanceof EE_Event
118
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
118
+            ? ' ee-status-strip event-status-'.$item->get_active_status()
119 119
             : '';
120 120
         if ($this->_has_checkbox_column) {
121 121
             $class .= ' has-checkbox-column';
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
      */
147 147
     public function column_cb($item)
148 148
     {
149
-        if (! $item instanceof EE_Event) {
149
+        if ( ! $item instanceof EE_Event) {
150 150
             return '';
151 151
         }
152 152
         $this->_dtt = $item->primary_datetime(); //set this for use in other columns
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
     public function column_id(EE_Event $item)
171 171
     {
172 172
         $content = $item->ID();
173
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
173
+        $content .= '  <span class="show-on-mobile-view-only">'.$item->name().'</span>';
174 174
         return $content;
175 175
     }
176 176
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
         $actions = $this->_column_name_action_setup($item);
195 195
         $status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196 196
         $content = '<strong><a class="row-title" href="'
197
-                   . $edit_link . '">'
197
+                   . $edit_link.'">'
198 198
                    . $item->name()
199 199
                    . '</a></strong>'
200 200
                    . $status;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
     protected function _column_name_action_setup(EE_Event $item)
225 225
     {
226 226
         //todo: remove when attendees is active
227
-        if (! defined('REG_ADMIN_URL')) {
227
+        if ( ! defined('REG_ADMIN_URL')) {
228 228
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229 229
         }
230 230
         $actions = array();
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
                 'post'   => $item->ID(),
242 242
             );
243 243
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
-            $actions['edit'] = '<a href="' . $edit_link . '"'
245
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
244
+            $actions['edit'] = '<a href="'.$edit_link.'"'
245
+                               . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
246 246
                                . esc_html__('Edit', 'event_espresso')
247 247
                                . '</a>';
248 248
         }
@@ -262,8 +262,8 @@  discard block
 block discarded – undo
262 262
                 'event_id' => $item->ID(),
263 263
             );
264 264
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
266
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
265
+            $actions['attendees'] = '<a href="'.$attendees_link.'"'
266
+                                    . ' title="'.esc_attr__('View Registrations', 'event_espresso').'">'
267 267
                                     . esc_html__('Registrations', 'event_espresso')
268 268
                                     . '</a>';
269 269
         }
@@ -316,8 +316,8 @@  discard block
 block discarded – undo
316 316
             );
317 317
         }
318 318
         $view_link = get_permalink($item->ID());
319
-        $actions['view'] = '<a href="' . $view_link . '"'
320
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
319
+        $actions['view'] = '<a href="'.$view_link.'"'
320
+                           . ' title="'.esc_attr__('View Event', 'event_espresso').'">'
321 321
                            . esc_html__('View', 'event_espresso')
322 322
                            . '</a>';
323 323
         if ($item->get('status') === 'trash') {
@@ -326,8 +326,8 @@  discard block
 block discarded – undo
326 326
                 'espresso_events_restore_event',
327 327
                 $item->ID()
328 328
             )) {
329
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
329
+                $actions['restore_from_trash'] = '<a href="'.$restore_event_link.'"'
330
+                                                 . ' title="'.esc_attr__('Restore from Trash', 'event_espresso')
331 331
                                                  . '">'
332 332
                                                  . esc_html__('Restore from Trash', 'event_espresso')
333 333
                                                  . '</a>';
@@ -340,8 +340,8 @@  discard block
 block discarded – undo
340 340
                     $item->ID()
341 341
                 )
342 342
             ) {
343
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
344
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
343
+                $actions['delete'] = '<a href="'.$delete_event_link.'"'
344
+                                     . ' title="'.esc_attr__('Delete Permanently', 'event_espresso').'">'
345 345
                                      . esc_html__('Delete Permanently', 'event_espresso')
346 346
                                      . '</a>';
347 347
             }
@@ -353,8 +353,8 @@  discard block
 block discarded – undo
353 353
                     $item->ID()
354 354
                 )
355 355
             ) {
356
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
356
+                $actions['move to trash'] = '<a href="'.$trash_event_link.'"'
357
+                                            . ' title="'.esc_attr__('Trash Event', 'event_espresso').'">'
358 358
                                             . esc_html__('Trash', 'event_espresso')
359 359
                                             . '</a>';
360 360
             }
@@ -380,8 +380,8 @@  discard block
 block discarded – undo
380 380
             'EVT_wp_user' => $item->wp_user(),
381 381
         );
382 382
         $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
-        return $gravatar . '  <a href="' . $filter_url . '"'
384
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
383
+        return $gravatar.'  <a href="'.$filter_url.'"'
384
+               . ' title="'.esc_attr__('Click to filter events by this author.', 'event_espresso').'">'
385 385
                . $event_author->display_name
386 386
                . '</a>';
387 387
     }
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
             'ee_read_registrations',
474 474
             'espresso_registrations_view_registration'
475 475
         )
476
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
476
+            ? '<a href="'.$attendees_link.'">'.$registered_attendees.'</a>'
477 477
             : $registered_attendees;
478 478
     }
479 479
 
@@ -505,13 +505,13 @@  discard block
 block discarded – undo
505 505
     public function column_actions(EE_Event $item)
506 506
     {
507 507
         //todo: remove when attendees is active
508
-        if (! defined('REG_ADMIN_URL')) {
508
+        if ( ! defined('REG_ADMIN_URL')) {
509 509
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510 510
         }
511 511
         $action_links = array();
512 512
         $view_link = get_permalink($item->ID());
513
-        $action_links[] = '<a href="' . $view_link . '"'
514
-                         . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
513
+        $action_links[] = '<a href="'.$view_link.'"'
514
+                         . ' title="'.esc_attr__('View Event', 'event_espresso').'" target="_blank">';
515 515
         $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516 516
         if (EE_Registry::instance()->CAP->current_user_can(
517 517
             'ee_edit_event',
@@ -523,8 +523,8 @@  discard block
 block discarded – undo
523 523
                 'post'   => $item->ID(),
524 524
             );
525 525
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
-            $action_links[] = '<a href="' . $edit_link . '"'
527
-                             . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
526
+            $action_links[] = '<a href="'.$edit_link.'"'
527
+                             . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
528 528
                              . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529 529
                              . '</a>';
530 530
         }
@@ -543,8 +543,8 @@  discard block
 block discarded – undo
543 543
                 'event_id' => $item->ID(),
544 544
             );
545 545
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
-            $action_links[] = '<a href="' . $attendees_link . '"'
547
-                             . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
546
+            $action_links[] = '<a href="'.$attendees_link.'"'
547
+                             . ' title="'.esc_attr__('View Registrants', 'event_espresso').'">'
548 548
                              . '<div class="dashicons dashicons-groups"></div>'
549 549
                              . '</a>';
550 550
         }
Please login to merge, or discard this patch.
core/EE_Capabilities.core.php 2 patches
Indentation   +1368 added lines, -1368 removed lines patch added patch discarded remove patch
@@ -18,980 +18,980 @@  discard block
 block discarded – undo
18 18
 final class EE_Capabilities extends EE_Base
19 19
 {
20 20
 
21
-    /**
22
-     * the name of the wp option used to store caps previously initialized
23
-     */
24
-    const option_name = 'ee_caps_initialized';
25
-
26
-    /**
27
-     * instance of EE_Capabilities object
28
-     *
29
-     * @var EE_Capabilities
30
-     */
31
-    private static $_instance;
32
-
33
-
34
-    /**
35
-     * This is a map of caps that correspond to a default WP_Role.
36
-     * Array is indexed by Role and values are ee capabilities.
37
-     *
38
-     * @since 4.5.0
39
-     *
40
-     * @var array
41
-     */
42
-    private $capabilities_map = array();
43
-
44
-    /**
45
-     * This used to hold an array of EE_Meta_Capability_Map objects
46
-     * that define the granular capabilities mapped to for a user depending on context.
47
-     *
48
-     * @var EE_Meta_Capability_Map[]
49
-     */
50
-    private $_meta_caps = array();
51
-
52
-    /**
53
-     * The internal $capabilities_map needs to be initialized before it can be used.
54
-     * This flag tracks whether that has happened or not.
55
-     * But for this to work, we need three states to indicate:
56
-     *      initialization has not occurred at all
57
-     *      initialization has started but is not complete
58
-     *      initialization is complete
59
-     * The reason this is needed is because the addCaps() method
60
-     * normally requires the $capabilities_map to be initialized,
61
-     * but is also used during the initialization process.
62
-     * So:
63
-     *      If initialized === null, init_caps() will be called before any other methods will run.
64
-     *      If initialized === false, then init_caps() is in the process of running it's logic.
65
-     *      If initialized === true, then init_caps() has completed the initialization process.
66
-     *
67
-     * @var boolean|null $initialized
68
-     */
69
-    private $initialized;
70
-
71
-    /**
72
-     * @var boolean $reset
73
-     */
74
-    private $reset = false;
75
-
76
-
77
-
78
-    /**
79
-     * singleton method used to instantiate class object
80
-     *
81
-     * @since 4.5.0
82
-     *
83
-     * @return EE_Capabilities
84
-     */
85
-    public static function instance()
86
-    {
87
-        //check if instantiated, and if not do so.
88
-        if (! self::$_instance instanceof EE_Capabilities) {
89
-            self::$_instance = new self();
90
-        }
91
-        return self::$_instance;
92
-    }
93
-
94
-
95
-
96
-    /**
97
-     * private constructor
98
-     *
99
-     * @since 4.5.0
100
-     */
101
-    private function __construct()
102
-    {
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
109
-     *
110
-     * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
111
-     *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
112
-     *                    ensures that they are up to date.
113
-     *
114
-     * @since 4.5.0
115
-     * @return bool
116
-     * @throws EE_Error
117
-     */
118
-    public function init_caps($reset = false)
119
-    {
120
-        if(! EE_Maintenance_Mode::instance()->models_can_query()){
121
-            return false;
122
-        }
123
-        $this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
124
-        // if reset, then completely delete the cache option and clear the $capabilities_map property.
125
-        if ($this->reset) {
126
-            $this->initialized = null;
127
-            $this->capabilities_map = array();
128
-            delete_option(self::option_name);
129
-        }
130
-        if ($this->initialized === null) {
131
-            $this->initialized = false;
132
-            do_action(
133
-                'AHEE__EE_Capabilities__init_caps__before_initialization',
134
-                $this->reset
135
-            );
136
-            $this->addCaps($this->_init_caps_map());
137
-            $this->_set_meta_caps();
138
-            do_action(
139
-                'AHEE__EE_Capabilities__init_caps__after_initialization',
140
-                $this->capabilities_map
141
-            );
142
-            $this->initialized = true;
143
-        }
144
-        // reset $this->reset so that it's not stuck on true if init_caps() gets called again
145
-        $this->reset = false;
146
-        return true;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * This sets the meta caps property.
153
-     *
154
-     * @since 4.5.0
155
-     * @return void
156
-     * @throws EE_Error
157
-     */
158
-    private function _set_meta_caps()
159
-    {
160
-        // get default meta caps and filter the returned array
161
-        $this->_meta_caps = apply_filters(
162
-            'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
163
-            $this->_get_default_meta_caps_array()
164
-        );
165
-        //add filter for map_meta_caps but only if models can query.
166
-        if (! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
167
-            add_filter('map_meta_cap', array($this, 'map_meta_caps'), 10, 4);
168
-        }
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * This builds and returns the default meta_caps array only once.
175
-     *
176
-     * @since  4.8.28.rc.012
177
-     * @return array
178
-     * @throws EE_Error
179
-     */
180
-    private function _get_default_meta_caps_array()
181
-    {
182
-        static $default_meta_caps = array();
183
-        // make sure we're only ever initializing the default _meta_caps array once if it's empty.
184
-        if (empty($default_meta_caps)) {
185
-            $default_meta_caps = array(
186
-                //edits
187
-                new EE_Meta_Capability_Map_Edit(
188
-                    'ee_edit_event',
189
-                    array('Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events')
190
-                ),
191
-                new EE_Meta_Capability_Map_Edit(
192
-                    'ee_edit_venue',
193
-                    array('Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues')
194
-                ),
195
-                new EE_Meta_Capability_Map_Edit(
196
-                    'ee_edit_registration',
197
-                    array('Registration', '', 'ee_edit_others_registrations', '')
198
-                ),
199
-                new EE_Meta_Capability_Map_Edit(
200
-                    'ee_edit_checkin',
201
-                    array('Registration', '', 'ee_edit_others_checkins', '')
202
-                ),
203
-                new EE_Meta_Capability_Map_Messages_Cap(
204
-                    'ee_edit_message',
205
-                    array('Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages')
206
-                ),
207
-                new EE_Meta_Capability_Map_Edit(
208
-                    'ee_edit_default_ticket',
209
-                    array('Ticket', '', 'ee_edit_others_default_tickets', '')
210
-                ),
211
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
212
-                    'ee_edit_question',
213
-                    array('Question', '', '', 'ee_edit_system_questions')
214
-                ),
215
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
216
-                    'ee_edit_question_group',
217
-                    array('Question_Group', '', '', 'ee_edit_system_question_groups')
218
-                ),
219
-                new EE_Meta_Capability_Map_Edit(
220
-                    'ee_edit_payment_method',
221
-                    array('Payment_Method', '', 'ee_edit_others_payment_methods', '')
222
-                ),
223
-                //reads
224
-                new EE_Meta_Capability_Map_Read(
225
-                    'ee_read_event',
226
-                    array('Event', '', 'ee_read_others_events', 'ee_read_private_events')
227
-                ),
228
-                new EE_Meta_Capability_Map_Read(
229
-                    'ee_read_venue',
230
-                    array('Venue', '', 'ee_read_others_venues', 'ee_read_private_venues')
231
-                ),
232
-                new EE_Meta_Capability_Map_Read(
233
-                    'ee_read_registration',
234
-                    array('Registration', '', 'ee_read_others_registrations', '')
235
-                ),
236
-                new EE_Meta_Capability_Map_Read(
237
-                    'ee_read_checkin',
238
-                    array('Registration', '', 'ee_read_others_checkins', '')
239
-                ),
240
-                new EE_Meta_Capability_Map_Messages_Cap(
241
-                    'ee_read_message',
242
-                    array('Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages')
243
-                ),
244
-                new EE_Meta_Capability_Map_Read(
245
-                    'ee_read_default_ticket',
246
-                    array('Ticket', '', 'ee_read_others_default_tickets', '')
247
-                ),
248
-                new EE_Meta_Capability_Map_Read(
249
-                    'ee_read_payment_method',
250
-                    array('Payment_Method', '', 'ee_read_others_payment_methods', '')
251
-                ),
252
-                //deletes
253
-                new EE_Meta_Capability_Map_Delete(
254
-                    'ee_delete_event',
255
-                    array(
256
-                        'Event',
257
-                        'ee_delete_published_events',
258
-                        'ee_delete_others_events',
259
-                        'ee_delete_private_events',
260
-                    )
261
-                ),
262
-                new EE_Meta_Capability_Map_Delete(
263
-                    'ee_delete_venue',
264
-                    array(
265
-                        'Venue',
266
-                        'ee_delete_published_venues',
267
-                        'ee_delete_others_venues',
268
-                        'ee_delete_private_venues',
269
-                    )
270
-                ),
271
-                new EE_Meta_Capability_Map_Delete(
272
-                    'ee_delete_registration',
273
-                    array('Registration', '', 'ee_delete_others_registrations', '')
274
-                ),
275
-                new EE_Meta_Capability_Map_Delete(
276
-                    'ee_delete_checkin',
277
-                    array('Registration', '', 'ee_delete_others_checkins', '')
278
-                ),
279
-                new EE_Meta_Capability_Map_Messages_Cap(
280
-                    'ee_delete_message',
281
-                    array('Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages')
282
-                ),
283
-                new EE_Meta_Capability_Map_Delete(
284
-                    'ee_delete_default_ticket',
285
-                    array('Ticket', '', 'ee_delete_others_default_tickets', '')
286
-                ),
287
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
288
-                    'ee_delete_question',
289
-                    array('Question', '', '', 'delete_system_questions')
290
-                ),
291
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
292
-                    'ee_delete_question_group',
293
-                    array('Question_Group', '', '', 'delete_system_question_groups')
294
-                ),
295
-                new EE_Meta_Capability_Map_Delete(
296
-                    'ee_delete_payment_method',
297
-                    array('Payment_Method', '', 'ee_delete_others_payment_methods', '')
298
-                ),
299
-            );
300
-        }
301
-        return $default_meta_caps;
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
308
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
309
-     *
310
-     * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
311
-     *
312
-     * @since 4.5.0
313
-     * @see   wp-includes/capabilities.php
314
-     *
315
-     * @param array  $caps    actual users capabilities
316
-     * @param string $cap     initial capability name that is being checked (the "map" key)
317
-     * @param int    $user_id The user id
318
-     * @param array  $args    Adds context to the cap. Typically the object ID.
319
-     * @return array actual users capabilities
320
-     * @throws EE_Error
321
-     */
322
-    public function map_meta_caps($caps, $cap, $user_id, $args)
323
-    {
324
-        if (did_action('AHEE__EE_System__load_espresso_addons__complete')) {
325
-            //loop through our _meta_caps array
326
-            foreach ($this->_meta_caps as $meta_map) {
327
-                if (! $meta_map instanceof EE_Meta_Capability_Map) {
328
-                    continue;
329
-                }
330
-                // don't load models if there is no object ID in the args
331
-                if (! empty($args[0])) {
332
-                    $meta_map->ensure_is_model();
333
-                }
334
-                $caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
335
-            }
336
-        }
337
-        return $caps;
338
-    }
339
-
340
-
341
-
342
-    /**
343
-     * This sets up and returns the initial capabilities map for Event Espresso
344
-     * Note this array is filtered.
345
-     * It is assumed that all available EE capabilities are assigned to the administrator role.
346
-     *
347
-     * @since 4.5.0
348
-     *
349
-     * @return array
350
-     */
351
-    private function _init_caps_map()
352
-    {
353
-        return apply_filters(
354
-            'FHEE__EE_Capabilities__init_caps_map__caps',
355
-            array(
356
-                'administrator'           => array(
357
-                    //basic access
358
-                    'ee_read_ee',
359
-                    //gateways
360
-                    /**
361
-                     * note that with payment method capabilities, although we've implemented
362
-                     * capability mapping which will be used for accessing payment methods owned by
363
-                     * other users.  This is not fully implemented yet in the payment method ui.
364
-                     * Currently only the "plural" caps are in active use.
365
-                     * (Specific payment method caps are in use as well).
366
-                     **/
367
-                    'ee_manage_gateways',
368
-                    'ee_read_payment_methods',
369
-                    'ee_read_others_payment_methods',
370
-                    'ee_edit_payment_methods',
371
-                    'ee_edit_others_payment_methods',
372
-                    'ee_delete_payment_methods',
373
-                    //events
374
-                    'ee_publish_events',
375
-                    'ee_read_private_events',
376
-                    'ee_read_others_events',
377
-                    'ee_read_events',
378
-                    'ee_edit_events',
379
-                    'ee_edit_published_events',
380
-                    'ee_edit_others_events',
381
-                    'ee_edit_private_events',
382
-                    'ee_delete_published_events',
383
-                    'ee_delete_private_events',
384
-                    'ee_delete_events',
385
-                    'ee_delete_others_events',
386
-                    //event categories
387
-                    'ee_manage_event_categories',
388
-                    'ee_edit_event_category',
389
-                    'ee_delete_event_category',
390
-                    'ee_assign_event_category',
391
-                    //venues
392
-                    'ee_publish_venues',
393
-                    'ee_read_venues',
394
-                    'ee_read_others_venues',
395
-                    'ee_read_private_venues',
396
-                    'ee_edit_venues',
397
-                    'ee_edit_others_venues',
398
-                    'ee_edit_published_venues',
399
-                    'ee_edit_private_venues',
400
-                    'ee_delete_venues',
401
-                    'ee_delete_others_venues',
402
-                    'ee_delete_private_venues',
403
-                    'ee_delete_published_venues',
404
-                    //venue categories
405
-                    'ee_manage_venue_categories',
406
-                    'ee_edit_venue_category',
407
-                    'ee_delete_venue_category',
408
-                    'ee_assign_venue_category',
409
-                    //contacts
410
-                    'ee_read_contacts',
411
-                    'ee_edit_contacts',
412
-                    'ee_delete_contacts',
413
-                    //registrations
414
-                    'ee_read_registrations',
415
-                    'ee_read_others_registrations',
416
-                    'ee_edit_registrations',
417
-                    'ee_edit_others_registrations',
418
-                    'ee_delete_registrations',
419
-                    //checkins
420
-                    'ee_read_others_checkins',
421
-                    'ee_read_checkins',
422
-                    'ee_edit_checkins',
423
-                    'ee_edit_others_checkins',
424
-                    'ee_delete_checkins',
425
-                    'ee_delete_others_checkins',
426
-                    //transactions && payments
427
-                    'ee_read_transaction',
428
-                    'ee_read_transactions',
429
-                    'ee_edit_payments',
430
-                    'ee_delete_payments',
431
-                    //messages
432
-                    'ee_read_messages',
433
-                    'ee_read_others_messages',
434
-                    'ee_read_global_messages',
435
-                    'ee_edit_global_messages',
436
-                    'ee_edit_messages',
437
-                    'ee_edit_others_messages',
438
-                    'ee_delete_messages',
439
-                    'ee_delete_others_messages',
440
-                    'ee_delete_global_messages',
441
-                    'ee_send_message',
442
-                    //tickets
443
-                    'ee_read_default_tickets',
444
-                    'ee_read_others_default_tickets',
445
-                    'ee_edit_default_tickets',
446
-                    'ee_edit_others_default_tickets',
447
-                    'ee_delete_default_tickets',
448
-                    'ee_delete_others_default_tickets',
449
-                    //prices
450
-                    'ee_edit_default_price',
451
-                    'ee_edit_default_prices',
452
-                    'ee_delete_default_price',
453
-                    'ee_delete_default_prices',
454
-                    'ee_edit_default_price_type',
455
-                    'ee_edit_default_price_types',
456
-                    'ee_delete_default_price_type',
457
-                    'ee_delete_default_price_types',
458
-                    'ee_read_default_prices',
459
-                    'ee_read_default_price_types',
460
-                    //registration form
461
-                    'ee_edit_questions',
462
-                    'ee_edit_system_questions',
463
-                    'ee_read_questions',
464
-                    'ee_delete_questions',
465
-                    'ee_edit_question_groups',
466
-                    'ee_read_question_groups',
467
-                    'ee_edit_system_question_groups',
468
-                    'ee_delete_question_groups',
469
-                    //event_type taxonomy
470
-                    'ee_assign_event_type',
471
-                    'ee_manage_event_types',
472
-                    'ee_edit_event_type',
473
-                    'ee_delete_event_type',
474
-                ),
475
-                'ee_events_administrator' => array(
476
-                    //core wp caps
477
-                    'read',
478
-                    'read_private_pages',
479
-                    'read_private_posts',
480
-                    'edit_users',
481
-                    'edit_posts',
482
-                    'edit_pages',
483
-                    'edit_published_posts',
484
-                    'edit_published_pages',
485
-                    'edit_private_pages',
486
-                    'edit_private_posts',
487
-                    'edit_others_posts',
488
-                    'edit_others_pages',
489
-                    'publish_posts',
490
-                    'publish_pages',
491
-                    'delete_posts',
492
-                    'delete_pages',
493
-                    'delete_private_pages',
494
-                    'delete_private_posts',
495
-                    'delete_published_pages',
496
-                    'delete_published_posts',
497
-                    'delete_others_posts',
498
-                    'delete_others_pages',
499
-                    'manage_categories',
500
-                    'manage_links',
501
-                    'moderate_comments',
502
-                    'unfiltered_html',
503
-                    'upload_files',
504
-                    'export',
505
-                    'import',
506
-                    'list_users',
507
-                    'level_1', //required if user with this role shows up in author dropdowns
508
-                    //basic ee access
509
-                    'ee_read_ee',
510
-                    //events
511
-                    'ee_publish_events',
512
-                    'ee_read_private_events',
513
-                    'ee_read_others_events',
514
-                    'ee_read_event',
515
-                    'ee_read_events',
516
-                    'ee_edit_event',
517
-                    'ee_edit_events',
518
-                    'ee_edit_published_events',
519
-                    'ee_edit_others_events',
520
-                    'ee_edit_private_events',
521
-                    'ee_delete_published_events',
522
-                    'ee_delete_private_events',
523
-                    'ee_delete_event',
524
-                    'ee_delete_events',
525
-                    'ee_delete_others_events',
526
-                    //event categories
527
-                    'ee_manage_event_categories',
528
-                    'ee_edit_event_category',
529
-                    'ee_delete_event_category',
530
-                    'ee_assign_event_category',
531
-                    //venues
532
-                    'ee_publish_venues',
533
-                    'ee_read_venue',
534
-                    'ee_read_venues',
535
-                    'ee_read_others_venues',
536
-                    'ee_read_private_venues',
537
-                    'ee_edit_venue',
538
-                    'ee_edit_venues',
539
-                    'ee_edit_others_venues',
540
-                    'ee_edit_published_venues',
541
-                    'ee_edit_private_venues',
542
-                    'ee_delete_venue',
543
-                    'ee_delete_venues',
544
-                    'ee_delete_others_venues',
545
-                    'ee_delete_private_venues',
546
-                    'ee_delete_published_venues',
547
-                    //venue categories
548
-                    'ee_manage_venue_categories',
549
-                    'ee_edit_venue_category',
550
-                    'ee_delete_venue_category',
551
-                    'ee_assign_venue_category',
552
-                    //contacts
553
-                    'ee_read_contacts',
554
-                    'ee_edit_contacts',
555
-                    'ee_delete_contacts',
556
-                    //registrations
557
-                    'ee_read_registrations',
558
-                    'ee_read_others_registrations',
559
-                    'ee_edit_registration',
560
-                    'ee_edit_registrations',
561
-                    'ee_edit_others_registrations',
562
-                    'ee_delete_registration',
563
-                    'ee_delete_registrations',
564
-                    //checkins
565
-                    'ee_read_others_checkins',
566
-                    'ee_read_checkins',
567
-                    'ee_edit_checkins',
568
-                    'ee_edit_others_checkins',
569
-                    'ee_delete_checkins',
570
-                    'ee_delete_others_checkins',
571
-                    //transactions && payments
572
-                    'ee_read_transaction',
573
-                    'ee_read_transactions',
574
-                    'ee_edit_payments',
575
-                    'ee_delete_payments',
576
-                    //messages
577
-                    'ee_read_messages',
578
-                    'ee_read_others_messages',
579
-                    'ee_read_global_messages',
580
-                    'ee_edit_global_messages',
581
-                    'ee_edit_messages',
582
-                    'ee_edit_others_messages',
583
-                    'ee_delete_messages',
584
-                    'ee_delete_others_messages',
585
-                    'ee_delete_global_messages',
586
-                    'ee_send_message',
587
-                    //tickets
588
-                    'ee_read_default_tickets',
589
-                    'ee_read_others_default_tickets',
590
-                    'ee_edit_default_tickets',
591
-                    'ee_edit_others_default_tickets',
592
-                    'ee_delete_default_tickets',
593
-                    'ee_delete_others_default_tickets',
594
-                    //prices
595
-                    'ee_edit_default_price',
596
-                    'ee_edit_default_prices',
597
-                    'ee_delete_default_price',
598
-                    'ee_delete_default_prices',
599
-                    'ee_edit_default_price_type',
600
-                    'ee_edit_default_price_types',
601
-                    'ee_delete_default_price_type',
602
-                    'ee_delete_default_price_types',
603
-                    'ee_read_default_prices',
604
-                    'ee_read_default_price_types',
605
-                    //registration form
606
-                    'ee_edit_questions',
607
-                    'ee_edit_system_questions',
608
-                    'ee_read_questions',
609
-                    'ee_delete_questions',
610
-                    'ee_edit_question_groups',
611
-                    'ee_read_question_groups',
612
-                    'ee_edit_system_question_groups',
613
-                    'ee_delete_question_groups',
614
-                    //event_type taxonomy
615
-                    'ee_assign_event_type',
616
-                    'ee_manage_event_types',
617
-                    'ee_edit_event_type',
618
-                    'ee_delete_event_type',
619
-                )
620
-            )
621
-        );
622
-    }
623
-
624
-
625
-
626
-    /**
627
-     * @return bool
628
-     * @throws EE_Error
629
-     */
630
-    private function setupCapabilitiesMap()
631
-    {
632
-        // if the initialization process hasn't even started, then we need to call init_caps()
633
-        if($this->initialized === null) {
634
-            return $this->init_caps();
635
-        }
636
-        // unless resetting, get caps from db if we haven't already
637
-        $this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
638
-            ? $this->capabilities_map
639
-            : get_option(self::option_name, array());
640
-        return true;
641
-    }
642
-
643
-
644
-
645
-    /**
646
-     * @param bool $update
647
-     * @return bool
648
-     */
649
-    private function updateCapabilitiesMap($update = true)
650
-    {
651
-        return $update ? update_option(self::option_name, $this->capabilities_map) : false;
652
-    }
653
-
654
-
655
-
656
-    /**
657
-     * Adds capabilities to roles.
658
-     *
659
-     * @since 4.9.42
660
-     * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
661
-     *                                   Note that this should ONLY be called on activation hook
662
-     *                                   otherwise the caps will be added on every request.
663
-     * @return bool
664
-     * @throws \EE_Error
665
-     */
666
-    public function addCaps(array $capabilities_to_add)
667
-    {
668
-        // don't do anything if the capabilities map can not be initialized
669
-        if (! $this->setupCapabilitiesMap()) {
670
-            return false;
671
-        }
672
-        // and filter the array so others can get in on the fun during resets
673
-        $capabilities_to_add = apply_filters(
674
-            'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
675
-            $capabilities_to_add,
676
-            $this->reset,
677
-            $this->capabilities_map
678
-        );
679
-        $update_capabilities_map = false;
680
-        // if not reset, see what caps are new for each role. if they're new, add them.
681
-        foreach ($capabilities_to_add as $role => $caps_for_role) {
682
-            if (is_array($caps_for_role)) {
683
-                foreach ($caps_for_role as $cap) {
684
-                    if (
685
-                        ! $this->capHasBeenAddedToRole($role, $cap)
686
-                        && $this->add_cap_to_role($role, $cap, true, false)
687
-                    ) {
688
-                        $update_capabilities_map = true;
689
-                    }
690
-                }
691
-            }
692
-        }
693
-        // now let's just save the cap that has been set but only if there's been a change.
694
-        $updated = $this->updateCapabilitiesMap($update_capabilities_map);
695
-        do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
696
-        return $updated;
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * Loops through the capabilities map and removes the role caps specified by the incoming array
703
-     *
704
-     * @param array $caps_map map of capabilities to be removed (indexed by roles)
705
-     * @return bool
706
-     * @throws \EE_Error
707
-     */
708
-    public function removeCaps($caps_map)
709
-    {
710
-        // don't do anything if the capabilities map can not be initialized
711
-        if (! $this->setupCapabilitiesMap()) {
712
-            return false;
713
-        }
714
-        $update_capabilities_map = false;
715
-        foreach ($caps_map as $role => $caps_for_role) {
716
-            if (is_array($caps_for_role)) {
717
-                foreach ($caps_for_role as $cap) {
718
-                    if (
719
-                        $this->capHasBeenAddedToRole($role, $cap)
720
-                        && $this->remove_cap_from_role($role, $cap, false)
721
-                    ) {
722
-                        $update_capabilities_map = true;
723
-                    }
724
-                }
725
-            }
726
-        }
727
-        // maybe resave the caps
728
-        return $this->updateCapabilitiesMap($update_capabilities_map);
729
-    }
730
-
731
-
732
-
733
-    /**
734
-     * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
735
-     * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
736
-     * this is a wrapper for $wp_role->add_cap()
737
-     *
738
-     * @see   wp-includes/capabilities.php
739
-     * @since 4.5.0
740
-     * @param string|WP_Role $role  A WordPress role the capability is being added to
741
-     * @param string         $cap   The capability being added to the role
742
-     * @param bool           $grant Whether to grant access to this cap on this role.
743
-     * @param bool           $update_capabilities_map
744
-     * @return bool
745
-     * @throws \EE_Error
746
-     */
747
-    public function add_cap_to_role($role, $cap, $grant = true, $update_capabilities_map = true)
748
-    {
749
-        // capture incoming value for $role because we may need it to create a new WP_Role
750
-        $orig_role = $role;
751
-        $role = $role instanceof WP_Role ? $role : get_role($role);
752
-        //if the role isn't available then we create it.
753
-        if (! $role instanceof WP_Role) {
754
-            // if a plugin wants to create a specific role name then they should create the role before
755
-            // EE_Capabilities does.  Otherwise this function will create the role name from the slug:
756
-            // - removes any `ee_` namespacing from the start of the slug.
757
-            // - replaces `_` with ` ` (empty space).
758
-            // - sentence case on the resulting string.
759
-            $role_label = ucwords(str_replace(array('ee_', '_'), array('', ' '), $orig_role));
760
-            $role = add_role($orig_role, $role_label);
761
-        }
762
-        if ($role instanceof WP_Role) {
763
-            // don't do anything if the capabilities map can not be initialized
764
-            if (! $this->setupCapabilitiesMap()) {
765
-                return false;
766
-            }
767
-            if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
768
-                $role->add_cap($cap, $grant);
769
-                $this->capabilities_map[ $role->name ][] = $cap;
770
-                $this->updateCapabilitiesMap($update_capabilities_map);
771
-                return true;
772
-            }
773
-        }
774
-        return false;
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * Functions similarly to add_cap_to_role except removes cap from given role.
781
-     * Wrapper for $wp_role->remove_cap()
782
-     *
783
-     * @see   wp-includes/capabilities.php
784
-     * @since 4.5.0
785
-     * @param string|WP_Role $role A WordPress role the capability is being removed from.
786
-     * @param string         $cap  The capability being removed
787
-     * @param bool           $update_capabilities_map
788
-     * @return bool
789
-     * @throws \EE_Error
790
-     */
791
-    public function remove_cap_from_role($role, $cap, $update_capabilities_map = true)
792
-    {
793
-        // don't do anything if the capabilities map can not be initialized
794
-        if (! $this->setupCapabilitiesMap()) {
795
-            return false;
796
-        }
797
-        $role = $role instanceof WP_Role ? $role :get_role($role);
798
-        if ($index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
799
-            $role->remove_cap($cap);
800
-            unset($this->capabilities_map[ $role->name ][ $index ]);
801
-            $this->updateCapabilitiesMap($update_capabilities_map);
802
-            return true;
803
-        }
804
-        return false;
805
-    }
806
-
807
-
808
-
809
-    /**
810
-     * @param string $role_name
811
-     * @param string $cap
812
-     * @param bool   $get_index
813
-     * @return bool|mixed
814
-     */
815
-    private function capHasBeenAddedToRole($role_name='', $cap='', $get_index = false)
816
-    {
817
-        if (
818
-            isset($this->capabilities_map[$role_name])
819
-            && ($index = array_search($cap, $this->capabilities_map[$role_name], true)) !== false
820
-        ) {
821
-            return $get_index ? $index : true;
822
-        }
823
-        return false;
824
-    }
825
-
826
-
827
-
828
-    /**
829
-     * Wrapper for the native WP current_user_can() method.
830
-     * This is provided as a handy method for a couple things:
831
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
832
-     * write those filters wherever current_user_can is called).
833
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
834
-     *
835
-     * @since 4.5.0
836
-     *
837
-     * @param string $cap     The cap being checked.
838
-     * @param string $context The context where the current_user_can is being called from.
839
-     * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
840
-     *                        filters.
841
-     *
842
-     * @return bool  Whether user can or not.
843
-     */
844
-    public function current_user_can($cap, $context, $id = 0)
845
-    {
846
-        //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
847
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id);
848
-        $filtered_cap = apply_filters(
849
-            'FHEE__EE_Capabilities__current_user_can__cap',
850
-            $filtered_cap,
851
-            $context,
852
-            $cap,
853
-            $id
854
-        );
855
-        return ! empty($id)
856
-            ? current_user_can($filtered_cap, $id)
857
-            : current_user_can($filtered_cap);
858
-    }
859
-
860
-
861
-
862
-    /**
863
-     * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
864
-     *
865
-     * @param int|WP_User $user    Either the user_id or a WP_User object
866
-     * @param string      $cap     The capability string being checked
867
-     * @param string      $context The context where the user_can is being called from (used in filters).
868
-     * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
869
-     *                             filters)
870
-     *
871
-     * @return bool Whether user can or not.
872
-     */
873
-    public function user_can($user, $cap, $context, $id = 0)
874
-    {
875
-        //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
876
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
877
-        $filtered_cap = apply_filters(
878
-            'FHEE__EE_Capabilities__user_can__cap',
879
-            $filtered_cap,
880
-            $context,
881
-            $cap,
882
-            $user,
883
-            $id
884
-        );
885
-        return ! empty($id)
886
-            ? user_can($user, $filtered_cap, $id)
887
-            : user_can($user, $filtered_cap);
888
-    }
889
-
890
-
891
-
892
-    /**
893
-     * Wrapper for the native WP current_user_can_for_blog() method.
894
-     * This is provided as a handy method for a couple things:
895
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
896
-     * write those filters wherever current_user_can is called).
897
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
898
-     *
899
-     * @since 4.5.0
900
-     *
901
-     * @param int    $blog_id The blog id that is being checked for.
902
-     * @param string $cap     The cap being checked.
903
-     * @param string $context The context where the current_user_can is being called from.
904
-     * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
905
-     *                        filters.
906
-     *
907
-     * @return bool  Whether user can or not.
908
-     */
909
-    public function current_user_can_for_blog($blog_id, $cap, $context, $id = 0)
910
-    {
911
-        $user_can = ! empty($id)
912
-            ? current_user_can_for_blog($blog_id, $cap, $id)
913
-            : current_user_can($blog_id, $cap);
914
-        //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
915
-        $user_can = apply_filters(
916
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
917
-            $user_can,
918
-            $blog_id,
919
-            $cap,
920
-            $id
921
-        );
922
-        $user_can = apply_filters(
923
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
924
-            $user_can,
925
-            $context,
926
-            $blog_id,
927
-            $cap,
928
-            $id
929
-        );
930
-        return $user_can;
931
-    }
932
-
933
-
934
-
935
-    /**
936
-     * This helper method just returns an array of registered EE capabilities.
937
-     *
938
-     * @since 4.5.0
939
-     * @param string $role If empty then the entire role/capability map is returned.
940
-     *                     Otherwise just the capabilities for the given role are returned.
941
-     * @return array
942
-     * @throws EE_Error
943
-     */
944
-    public function get_ee_capabilities($role = 'administrator')
945
-    {
946
-        if (! $this->initialized) {
947
-            $this->init_caps();
948
-        }
949
-        if (empty($role)) {
950
-            return $this->capabilities_map;
951
-        }
952
-        return isset($this->capabilities_map[ $role ])
953
-            ? $this->capabilities_map[ $role ]
954
-            : array();
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * @deprecated 4.9.42
961
-     * @param bool  $reset      If you need to reset Event Espresso's capabilities,
962
-     *                          then please use the init_caps() method with the "$reset" parameter set to "true"
963
-     * @param array $caps_map   Optional.
964
-     *                          Can be used to send a custom map of roles and capabilities for setting them up.
965
-     *                          Note that this should ONLY be called on activation hook or some other one-time
966
-     *                          task otherwise the caps will be added on every request.
967
-     * @return void
968
-     * @throws EE_Error
969
-     */
970
-    public function init_role_caps($reset = false, $caps_map = array())
971
-    {
972
-        // If this method is called directly and reset is set as 'true',
973
-        // then display a doing it wrong notice, because we want resets to go through init_caps()
974
-        // to guarantee that everything is set up correctly.
975
-        // This prevents the capabilities map getting reset incorrectly by direct calls to this method.
976
-        if ($reset) {
977
-            EE_Error::doing_it_wrong(
978
-                __METHOD__,
979
-                sprintf(
980
-                    esc_html__(
981
-                        'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
982
-                        'event_espresso'
983
-                    ),
984
-                    '$reset',
985
-                    __METHOD__ . '()',
986
-                    'EE_Capabilities::init_caps()',
987
-                    'true'
988
-                ),
989
-                '4.9.42',
990
-                '5.0.0'
991
-            );
992
-        }
993
-        $this->addCaps($caps_map);
994
-    }
21
+	/**
22
+	 * the name of the wp option used to store caps previously initialized
23
+	 */
24
+	const option_name = 'ee_caps_initialized';
25
+
26
+	/**
27
+	 * instance of EE_Capabilities object
28
+	 *
29
+	 * @var EE_Capabilities
30
+	 */
31
+	private static $_instance;
32
+
33
+
34
+	/**
35
+	 * This is a map of caps that correspond to a default WP_Role.
36
+	 * Array is indexed by Role and values are ee capabilities.
37
+	 *
38
+	 * @since 4.5.0
39
+	 *
40
+	 * @var array
41
+	 */
42
+	private $capabilities_map = array();
43
+
44
+	/**
45
+	 * This used to hold an array of EE_Meta_Capability_Map objects
46
+	 * that define the granular capabilities mapped to for a user depending on context.
47
+	 *
48
+	 * @var EE_Meta_Capability_Map[]
49
+	 */
50
+	private $_meta_caps = array();
51
+
52
+	/**
53
+	 * The internal $capabilities_map needs to be initialized before it can be used.
54
+	 * This flag tracks whether that has happened or not.
55
+	 * But for this to work, we need three states to indicate:
56
+	 *      initialization has not occurred at all
57
+	 *      initialization has started but is not complete
58
+	 *      initialization is complete
59
+	 * The reason this is needed is because the addCaps() method
60
+	 * normally requires the $capabilities_map to be initialized,
61
+	 * but is also used during the initialization process.
62
+	 * So:
63
+	 *      If initialized === null, init_caps() will be called before any other methods will run.
64
+	 *      If initialized === false, then init_caps() is in the process of running it's logic.
65
+	 *      If initialized === true, then init_caps() has completed the initialization process.
66
+	 *
67
+	 * @var boolean|null $initialized
68
+	 */
69
+	private $initialized;
70
+
71
+	/**
72
+	 * @var boolean $reset
73
+	 */
74
+	private $reset = false;
75
+
76
+
77
+
78
+	/**
79
+	 * singleton method used to instantiate class object
80
+	 *
81
+	 * @since 4.5.0
82
+	 *
83
+	 * @return EE_Capabilities
84
+	 */
85
+	public static function instance()
86
+	{
87
+		//check if instantiated, and if not do so.
88
+		if (! self::$_instance instanceof EE_Capabilities) {
89
+			self::$_instance = new self();
90
+		}
91
+		return self::$_instance;
92
+	}
93
+
94
+
95
+
96
+	/**
97
+	 * private constructor
98
+	 *
99
+	 * @since 4.5.0
100
+	 */
101
+	private function __construct()
102
+	{
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
109
+	 *
110
+	 * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
111
+	 *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
112
+	 *                    ensures that they are up to date.
113
+	 *
114
+	 * @since 4.5.0
115
+	 * @return bool
116
+	 * @throws EE_Error
117
+	 */
118
+	public function init_caps($reset = false)
119
+	{
120
+		if(! EE_Maintenance_Mode::instance()->models_can_query()){
121
+			return false;
122
+		}
123
+		$this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
124
+		// if reset, then completely delete the cache option and clear the $capabilities_map property.
125
+		if ($this->reset) {
126
+			$this->initialized = null;
127
+			$this->capabilities_map = array();
128
+			delete_option(self::option_name);
129
+		}
130
+		if ($this->initialized === null) {
131
+			$this->initialized = false;
132
+			do_action(
133
+				'AHEE__EE_Capabilities__init_caps__before_initialization',
134
+				$this->reset
135
+			);
136
+			$this->addCaps($this->_init_caps_map());
137
+			$this->_set_meta_caps();
138
+			do_action(
139
+				'AHEE__EE_Capabilities__init_caps__after_initialization',
140
+				$this->capabilities_map
141
+			);
142
+			$this->initialized = true;
143
+		}
144
+		// reset $this->reset so that it's not stuck on true if init_caps() gets called again
145
+		$this->reset = false;
146
+		return true;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * This sets the meta caps property.
153
+	 *
154
+	 * @since 4.5.0
155
+	 * @return void
156
+	 * @throws EE_Error
157
+	 */
158
+	private function _set_meta_caps()
159
+	{
160
+		// get default meta caps and filter the returned array
161
+		$this->_meta_caps = apply_filters(
162
+			'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
163
+			$this->_get_default_meta_caps_array()
164
+		);
165
+		//add filter for map_meta_caps but only if models can query.
166
+		if (! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
167
+			add_filter('map_meta_cap', array($this, 'map_meta_caps'), 10, 4);
168
+		}
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * This builds and returns the default meta_caps array only once.
175
+	 *
176
+	 * @since  4.8.28.rc.012
177
+	 * @return array
178
+	 * @throws EE_Error
179
+	 */
180
+	private function _get_default_meta_caps_array()
181
+	{
182
+		static $default_meta_caps = array();
183
+		// make sure we're only ever initializing the default _meta_caps array once if it's empty.
184
+		if (empty($default_meta_caps)) {
185
+			$default_meta_caps = array(
186
+				//edits
187
+				new EE_Meta_Capability_Map_Edit(
188
+					'ee_edit_event',
189
+					array('Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events')
190
+				),
191
+				new EE_Meta_Capability_Map_Edit(
192
+					'ee_edit_venue',
193
+					array('Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues')
194
+				),
195
+				new EE_Meta_Capability_Map_Edit(
196
+					'ee_edit_registration',
197
+					array('Registration', '', 'ee_edit_others_registrations', '')
198
+				),
199
+				new EE_Meta_Capability_Map_Edit(
200
+					'ee_edit_checkin',
201
+					array('Registration', '', 'ee_edit_others_checkins', '')
202
+				),
203
+				new EE_Meta_Capability_Map_Messages_Cap(
204
+					'ee_edit_message',
205
+					array('Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages')
206
+				),
207
+				new EE_Meta_Capability_Map_Edit(
208
+					'ee_edit_default_ticket',
209
+					array('Ticket', '', 'ee_edit_others_default_tickets', '')
210
+				),
211
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
212
+					'ee_edit_question',
213
+					array('Question', '', '', 'ee_edit_system_questions')
214
+				),
215
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
216
+					'ee_edit_question_group',
217
+					array('Question_Group', '', '', 'ee_edit_system_question_groups')
218
+				),
219
+				new EE_Meta_Capability_Map_Edit(
220
+					'ee_edit_payment_method',
221
+					array('Payment_Method', '', 'ee_edit_others_payment_methods', '')
222
+				),
223
+				//reads
224
+				new EE_Meta_Capability_Map_Read(
225
+					'ee_read_event',
226
+					array('Event', '', 'ee_read_others_events', 'ee_read_private_events')
227
+				),
228
+				new EE_Meta_Capability_Map_Read(
229
+					'ee_read_venue',
230
+					array('Venue', '', 'ee_read_others_venues', 'ee_read_private_venues')
231
+				),
232
+				new EE_Meta_Capability_Map_Read(
233
+					'ee_read_registration',
234
+					array('Registration', '', 'ee_read_others_registrations', '')
235
+				),
236
+				new EE_Meta_Capability_Map_Read(
237
+					'ee_read_checkin',
238
+					array('Registration', '', 'ee_read_others_checkins', '')
239
+				),
240
+				new EE_Meta_Capability_Map_Messages_Cap(
241
+					'ee_read_message',
242
+					array('Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages')
243
+				),
244
+				new EE_Meta_Capability_Map_Read(
245
+					'ee_read_default_ticket',
246
+					array('Ticket', '', 'ee_read_others_default_tickets', '')
247
+				),
248
+				new EE_Meta_Capability_Map_Read(
249
+					'ee_read_payment_method',
250
+					array('Payment_Method', '', 'ee_read_others_payment_methods', '')
251
+				),
252
+				//deletes
253
+				new EE_Meta_Capability_Map_Delete(
254
+					'ee_delete_event',
255
+					array(
256
+						'Event',
257
+						'ee_delete_published_events',
258
+						'ee_delete_others_events',
259
+						'ee_delete_private_events',
260
+					)
261
+				),
262
+				new EE_Meta_Capability_Map_Delete(
263
+					'ee_delete_venue',
264
+					array(
265
+						'Venue',
266
+						'ee_delete_published_venues',
267
+						'ee_delete_others_venues',
268
+						'ee_delete_private_venues',
269
+					)
270
+				),
271
+				new EE_Meta_Capability_Map_Delete(
272
+					'ee_delete_registration',
273
+					array('Registration', '', 'ee_delete_others_registrations', '')
274
+				),
275
+				new EE_Meta_Capability_Map_Delete(
276
+					'ee_delete_checkin',
277
+					array('Registration', '', 'ee_delete_others_checkins', '')
278
+				),
279
+				new EE_Meta_Capability_Map_Messages_Cap(
280
+					'ee_delete_message',
281
+					array('Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages')
282
+				),
283
+				new EE_Meta_Capability_Map_Delete(
284
+					'ee_delete_default_ticket',
285
+					array('Ticket', '', 'ee_delete_others_default_tickets', '')
286
+				),
287
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
288
+					'ee_delete_question',
289
+					array('Question', '', '', 'delete_system_questions')
290
+				),
291
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
292
+					'ee_delete_question_group',
293
+					array('Question_Group', '', '', 'delete_system_question_groups')
294
+				),
295
+				new EE_Meta_Capability_Map_Delete(
296
+					'ee_delete_payment_method',
297
+					array('Payment_Method', '', 'ee_delete_others_payment_methods', '')
298
+				),
299
+			);
300
+		}
301
+		return $default_meta_caps;
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
308
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
309
+	 *
310
+	 * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
311
+	 *
312
+	 * @since 4.5.0
313
+	 * @see   wp-includes/capabilities.php
314
+	 *
315
+	 * @param array  $caps    actual users capabilities
316
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
317
+	 * @param int    $user_id The user id
318
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
319
+	 * @return array actual users capabilities
320
+	 * @throws EE_Error
321
+	 */
322
+	public function map_meta_caps($caps, $cap, $user_id, $args)
323
+	{
324
+		if (did_action('AHEE__EE_System__load_espresso_addons__complete')) {
325
+			//loop through our _meta_caps array
326
+			foreach ($this->_meta_caps as $meta_map) {
327
+				if (! $meta_map instanceof EE_Meta_Capability_Map) {
328
+					continue;
329
+				}
330
+				// don't load models if there is no object ID in the args
331
+				if (! empty($args[0])) {
332
+					$meta_map->ensure_is_model();
333
+				}
334
+				$caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
335
+			}
336
+		}
337
+		return $caps;
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * This sets up and returns the initial capabilities map for Event Espresso
344
+	 * Note this array is filtered.
345
+	 * It is assumed that all available EE capabilities are assigned to the administrator role.
346
+	 *
347
+	 * @since 4.5.0
348
+	 *
349
+	 * @return array
350
+	 */
351
+	private function _init_caps_map()
352
+	{
353
+		return apply_filters(
354
+			'FHEE__EE_Capabilities__init_caps_map__caps',
355
+			array(
356
+				'administrator'           => array(
357
+					//basic access
358
+					'ee_read_ee',
359
+					//gateways
360
+					/**
361
+					 * note that with payment method capabilities, although we've implemented
362
+					 * capability mapping which will be used for accessing payment methods owned by
363
+					 * other users.  This is not fully implemented yet in the payment method ui.
364
+					 * Currently only the "plural" caps are in active use.
365
+					 * (Specific payment method caps are in use as well).
366
+					 **/
367
+					'ee_manage_gateways',
368
+					'ee_read_payment_methods',
369
+					'ee_read_others_payment_methods',
370
+					'ee_edit_payment_methods',
371
+					'ee_edit_others_payment_methods',
372
+					'ee_delete_payment_methods',
373
+					//events
374
+					'ee_publish_events',
375
+					'ee_read_private_events',
376
+					'ee_read_others_events',
377
+					'ee_read_events',
378
+					'ee_edit_events',
379
+					'ee_edit_published_events',
380
+					'ee_edit_others_events',
381
+					'ee_edit_private_events',
382
+					'ee_delete_published_events',
383
+					'ee_delete_private_events',
384
+					'ee_delete_events',
385
+					'ee_delete_others_events',
386
+					//event categories
387
+					'ee_manage_event_categories',
388
+					'ee_edit_event_category',
389
+					'ee_delete_event_category',
390
+					'ee_assign_event_category',
391
+					//venues
392
+					'ee_publish_venues',
393
+					'ee_read_venues',
394
+					'ee_read_others_venues',
395
+					'ee_read_private_venues',
396
+					'ee_edit_venues',
397
+					'ee_edit_others_venues',
398
+					'ee_edit_published_venues',
399
+					'ee_edit_private_venues',
400
+					'ee_delete_venues',
401
+					'ee_delete_others_venues',
402
+					'ee_delete_private_venues',
403
+					'ee_delete_published_venues',
404
+					//venue categories
405
+					'ee_manage_venue_categories',
406
+					'ee_edit_venue_category',
407
+					'ee_delete_venue_category',
408
+					'ee_assign_venue_category',
409
+					//contacts
410
+					'ee_read_contacts',
411
+					'ee_edit_contacts',
412
+					'ee_delete_contacts',
413
+					//registrations
414
+					'ee_read_registrations',
415
+					'ee_read_others_registrations',
416
+					'ee_edit_registrations',
417
+					'ee_edit_others_registrations',
418
+					'ee_delete_registrations',
419
+					//checkins
420
+					'ee_read_others_checkins',
421
+					'ee_read_checkins',
422
+					'ee_edit_checkins',
423
+					'ee_edit_others_checkins',
424
+					'ee_delete_checkins',
425
+					'ee_delete_others_checkins',
426
+					//transactions && payments
427
+					'ee_read_transaction',
428
+					'ee_read_transactions',
429
+					'ee_edit_payments',
430
+					'ee_delete_payments',
431
+					//messages
432
+					'ee_read_messages',
433
+					'ee_read_others_messages',
434
+					'ee_read_global_messages',
435
+					'ee_edit_global_messages',
436
+					'ee_edit_messages',
437
+					'ee_edit_others_messages',
438
+					'ee_delete_messages',
439
+					'ee_delete_others_messages',
440
+					'ee_delete_global_messages',
441
+					'ee_send_message',
442
+					//tickets
443
+					'ee_read_default_tickets',
444
+					'ee_read_others_default_tickets',
445
+					'ee_edit_default_tickets',
446
+					'ee_edit_others_default_tickets',
447
+					'ee_delete_default_tickets',
448
+					'ee_delete_others_default_tickets',
449
+					//prices
450
+					'ee_edit_default_price',
451
+					'ee_edit_default_prices',
452
+					'ee_delete_default_price',
453
+					'ee_delete_default_prices',
454
+					'ee_edit_default_price_type',
455
+					'ee_edit_default_price_types',
456
+					'ee_delete_default_price_type',
457
+					'ee_delete_default_price_types',
458
+					'ee_read_default_prices',
459
+					'ee_read_default_price_types',
460
+					//registration form
461
+					'ee_edit_questions',
462
+					'ee_edit_system_questions',
463
+					'ee_read_questions',
464
+					'ee_delete_questions',
465
+					'ee_edit_question_groups',
466
+					'ee_read_question_groups',
467
+					'ee_edit_system_question_groups',
468
+					'ee_delete_question_groups',
469
+					//event_type taxonomy
470
+					'ee_assign_event_type',
471
+					'ee_manage_event_types',
472
+					'ee_edit_event_type',
473
+					'ee_delete_event_type',
474
+				),
475
+				'ee_events_administrator' => array(
476
+					//core wp caps
477
+					'read',
478
+					'read_private_pages',
479
+					'read_private_posts',
480
+					'edit_users',
481
+					'edit_posts',
482
+					'edit_pages',
483
+					'edit_published_posts',
484
+					'edit_published_pages',
485
+					'edit_private_pages',
486
+					'edit_private_posts',
487
+					'edit_others_posts',
488
+					'edit_others_pages',
489
+					'publish_posts',
490
+					'publish_pages',
491
+					'delete_posts',
492
+					'delete_pages',
493
+					'delete_private_pages',
494
+					'delete_private_posts',
495
+					'delete_published_pages',
496
+					'delete_published_posts',
497
+					'delete_others_posts',
498
+					'delete_others_pages',
499
+					'manage_categories',
500
+					'manage_links',
501
+					'moderate_comments',
502
+					'unfiltered_html',
503
+					'upload_files',
504
+					'export',
505
+					'import',
506
+					'list_users',
507
+					'level_1', //required if user with this role shows up in author dropdowns
508
+					//basic ee access
509
+					'ee_read_ee',
510
+					//events
511
+					'ee_publish_events',
512
+					'ee_read_private_events',
513
+					'ee_read_others_events',
514
+					'ee_read_event',
515
+					'ee_read_events',
516
+					'ee_edit_event',
517
+					'ee_edit_events',
518
+					'ee_edit_published_events',
519
+					'ee_edit_others_events',
520
+					'ee_edit_private_events',
521
+					'ee_delete_published_events',
522
+					'ee_delete_private_events',
523
+					'ee_delete_event',
524
+					'ee_delete_events',
525
+					'ee_delete_others_events',
526
+					//event categories
527
+					'ee_manage_event_categories',
528
+					'ee_edit_event_category',
529
+					'ee_delete_event_category',
530
+					'ee_assign_event_category',
531
+					//venues
532
+					'ee_publish_venues',
533
+					'ee_read_venue',
534
+					'ee_read_venues',
535
+					'ee_read_others_venues',
536
+					'ee_read_private_venues',
537
+					'ee_edit_venue',
538
+					'ee_edit_venues',
539
+					'ee_edit_others_venues',
540
+					'ee_edit_published_venues',
541
+					'ee_edit_private_venues',
542
+					'ee_delete_venue',
543
+					'ee_delete_venues',
544
+					'ee_delete_others_venues',
545
+					'ee_delete_private_venues',
546
+					'ee_delete_published_venues',
547
+					//venue categories
548
+					'ee_manage_venue_categories',
549
+					'ee_edit_venue_category',
550
+					'ee_delete_venue_category',
551
+					'ee_assign_venue_category',
552
+					//contacts
553
+					'ee_read_contacts',
554
+					'ee_edit_contacts',
555
+					'ee_delete_contacts',
556
+					//registrations
557
+					'ee_read_registrations',
558
+					'ee_read_others_registrations',
559
+					'ee_edit_registration',
560
+					'ee_edit_registrations',
561
+					'ee_edit_others_registrations',
562
+					'ee_delete_registration',
563
+					'ee_delete_registrations',
564
+					//checkins
565
+					'ee_read_others_checkins',
566
+					'ee_read_checkins',
567
+					'ee_edit_checkins',
568
+					'ee_edit_others_checkins',
569
+					'ee_delete_checkins',
570
+					'ee_delete_others_checkins',
571
+					//transactions && payments
572
+					'ee_read_transaction',
573
+					'ee_read_transactions',
574
+					'ee_edit_payments',
575
+					'ee_delete_payments',
576
+					//messages
577
+					'ee_read_messages',
578
+					'ee_read_others_messages',
579
+					'ee_read_global_messages',
580
+					'ee_edit_global_messages',
581
+					'ee_edit_messages',
582
+					'ee_edit_others_messages',
583
+					'ee_delete_messages',
584
+					'ee_delete_others_messages',
585
+					'ee_delete_global_messages',
586
+					'ee_send_message',
587
+					//tickets
588
+					'ee_read_default_tickets',
589
+					'ee_read_others_default_tickets',
590
+					'ee_edit_default_tickets',
591
+					'ee_edit_others_default_tickets',
592
+					'ee_delete_default_tickets',
593
+					'ee_delete_others_default_tickets',
594
+					//prices
595
+					'ee_edit_default_price',
596
+					'ee_edit_default_prices',
597
+					'ee_delete_default_price',
598
+					'ee_delete_default_prices',
599
+					'ee_edit_default_price_type',
600
+					'ee_edit_default_price_types',
601
+					'ee_delete_default_price_type',
602
+					'ee_delete_default_price_types',
603
+					'ee_read_default_prices',
604
+					'ee_read_default_price_types',
605
+					//registration form
606
+					'ee_edit_questions',
607
+					'ee_edit_system_questions',
608
+					'ee_read_questions',
609
+					'ee_delete_questions',
610
+					'ee_edit_question_groups',
611
+					'ee_read_question_groups',
612
+					'ee_edit_system_question_groups',
613
+					'ee_delete_question_groups',
614
+					//event_type taxonomy
615
+					'ee_assign_event_type',
616
+					'ee_manage_event_types',
617
+					'ee_edit_event_type',
618
+					'ee_delete_event_type',
619
+				)
620
+			)
621
+		);
622
+	}
623
+
624
+
625
+
626
+	/**
627
+	 * @return bool
628
+	 * @throws EE_Error
629
+	 */
630
+	private function setupCapabilitiesMap()
631
+	{
632
+		// if the initialization process hasn't even started, then we need to call init_caps()
633
+		if($this->initialized === null) {
634
+			return $this->init_caps();
635
+		}
636
+		// unless resetting, get caps from db if we haven't already
637
+		$this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
638
+			? $this->capabilities_map
639
+			: get_option(self::option_name, array());
640
+		return true;
641
+	}
642
+
643
+
644
+
645
+	/**
646
+	 * @param bool $update
647
+	 * @return bool
648
+	 */
649
+	private function updateCapabilitiesMap($update = true)
650
+	{
651
+		return $update ? update_option(self::option_name, $this->capabilities_map) : false;
652
+	}
653
+
654
+
655
+
656
+	/**
657
+	 * Adds capabilities to roles.
658
+	 *
659
+	 * @since 4.9.42
660
+	 * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
661
+	 *                                   Note that this should ONLY be called on activation hook
662
+	 *                                   otherwise the caps will be added on every request.
663
+	 * @return bool
664
+	 * @throws \EE_Error
665
+	 */
666
+	public function addCaps(array $capabilities_to_add)
667
+	{
668
+		// don't do anything if the capabilities map can not be initialized
669
+		if (! $this->setupCapabilitiesMap()) {
670
+			return false;
671
+		}
672
+		// and filter the array so others can get in on the fun during resets
673
+		$capabilities_to_add = apply_filters(
674
+			'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
675
+			$capabilities_to_add,
676
+			$this->reset,
677
+			$this->capabilities_map
678
+		);
679
+		$update_capabilities_map = false;
680
+		// if not reset, see what caps are new for each role. if they're new, add them.
681
+		foreach ($capabilities_to_add as $role => $caps_for_role) {
682
+			if (is_array($caps_for_role)) {
683
+				foreach ($caps_for_role as $cap) {
684
+					if (
685
+						! $this->capHasBeenAddedToRole($role, $cap)
686
+						&& $this->add_cap_to_role($role, $cap, true, false)
687
+					) {
688
+						$update_capabilities_map = true;
689
+					}
690
+				}
691
+			}
692
+		}
693
+		// now let's just save the cap that has been set but only if there's been a change.
694
+		$updated = $this->updateCapabilitiesMap($update_capabilities_map);
695
+		do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
696
+		return $updated;
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * Loops through the capabilities map and removes the role caps specified by the incoming array
703
+	 *
704
+	 * @param array $caps_map map of capabilities to be removed (indexed by roles)
705
+	 * @return bool
706
+	 * @throws \EE_Error
707
+	 */
708
+	public function removeCaps($caps_map)
709
+	{
710
+		// don't do anything if the capabilities map can not be initialized
711
+		if (! $this->setupCapabilitiesMap()) {
712
+			return false;
713
+		}
714
+		$update_capabilities_map = false;
715
+		foreach ($caps_map as $role => $caps_for_role) {
716
+			if (is_array($caps_for_role)) {
717
+				foreach ($caps_for_role as $cap) {
718
+					if (
719
+						$this->capHasBeenAddedToRole($role, $cap)
720
+						&& $this->remove_cap_from_role($role, $cap, false)
721
+					) {
722
+						$update_capabilities_map = true;
723
+					}
724
+				}
725
+			}
726
+		}
727
+		// maybe resave the caps
728
+		return $this->updateCapabilitiesMap($update_capabilities_map);
729
+	}
730
+
731
+
732
+
733
+	/**
734
+	 * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
735
+	 * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
736
+	 * this is a wrapper for $wp_role->add_cap()
737
+	 *
738
+	 * @see   wp-includes/capabilities.php
739
+	 * @since 4.5.0
740
+	 * @param string|WP_Role $role  A WordPress role the capability is being added to
741
+	 * @param string         $cap   The capability being added to the role
742
+	 * @param bool           $grant Whether to grant access to this cap on this role.
743
+	 * @param bool           $update_capabilities_map
744
+	 * @return bool
745
+	 * @throws \EE_Error
746
+	 */
747
+	public function add_cap_to_role($role, $cap, $grant = true, $update_capabilities_map = true)
748
+	{
749
+		// capture incoming value for $role because we may need it to create a new WP_Role
750
+		$orig_role = $role;
751
+		$role = $role instanceof WP_Role ? $role : get_role($role);
752
+		//if the role isn't available then we create it.
753
+		if (! $role instanceof WP_Role) {
754
+			// if a plugin wants to create a specific role name then they should create the role before
755
+			// EE_Capabilities does.  Otherwise this function will create the role name from the slug:
756
+			// - removes any `ee_` namespacing from the start of the slug.
757
+			// - replaces `_` with ` ` (empty space).
758
+			// - sentence case on the resulting string.
759
+			$role_label = ucwords(str_replace(array('ee_', '_'), array('', ' '), $orig_role));
760
+			$role = add_role($orig_role, $role_label);
761
+		}
762
+		if ($role instanceof WP_Role) {
763
+			// don't do anything if the capabilities map can not be initialized
764
+			if (! $this->setupCapabilitiesMap()) {
765
+				return false;
766
+			}
767
+			if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
768
+				$role->add_cap($cap, $grant);
769
+				$this->capabilities_map[ $role->name ][] = $cap;
770
+				$this->updateCapabilitiesMap($update_capabilities_map);
771
+				return true;
772
+			}
773
+		}
774
+		return false;
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * Functions similarly to add_cap_to_role except removes cap from given role.
781
+	 * Wrapper for $wp_role->remove_cap()
782
+	 *
783
+	 * @see   wp-includes/capabilities.php
784
+	 * @since 4.5.0
785
+	 * @param string|WP_Role $role A WordPress role the capability is being removed from.
786
+	 * @param string         $cap  The capability being removed
787
+	 * @param bool           $update_capabilities_map
788
+	 * @return bool
789
+	 * @throws \EE_Error
790
+	 */
791
+	public function remove_cap_from_role($role, $cap, $update_capabilities_map = true)
792
+	{
793
+		// don't do anything if the capabilities map can not be initialized
794
+		if (! $this->setupCapabilitiesMap()) {
795
+			return false;
796
+		}
797
+		$role = $role instanceof WP_Role ? $role :get_role($role);
798
+		if ($index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
799
+			$role->remove_cap($cap);
800
+			unset($this->capabilities_map[ $role->name ][ $index ]);
801
+			$this->updateCapabilitiesMap($update_capabilities_map);
802
+			return true;
803
+		}
804
+		return false;
805
+	}
806
+
807
+
808
+
809
+	/**
810
+	 * @param string $role_name
811
+	 * @param string $cap
812
+	 * @param bool   $get_index
813
+	 * @return bool|mixed
814
+	 */
815
+	private function capHasBeenAddedToRole($role_name='', $cap='', $get_index = false)
816
+	{
817
+		if (
818
+			isset($this->capabilities_map[$role_name])
819
+			&& ($index = array_search($cap, $this->capabilities_map[$role_name], true)) !== false
820
+		) {
821
+			return $get_index ? $index : true;
822
+		}
823
+		return false;
824
+	}
825
+
826
+
827
+
828
+	/**
829
+	 * Wrapper for the native WP current_user_can() method.
830
+	 * This is provided as a handy method for a couple things:
831
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
832
+	 * write those filters wherever current_user_can is called).
833
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
834
+	 *
835
+	 * @since 4.5.0
836
+	 *
837
+	 * @param string $cap     The cap being checked.
838
+	 * @param string $context The context where the current_user_can is being called from.
839
+	 * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
840
+	 *                        filters.
841
+	 *
842
+	 * @return bool  Whether user can or not.
843
+	 */
844
+	public function current_user_can($cap, $context, $id = 0)
845
+	{
846
+		//apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
847
+		$filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id);
848
+		$filtered_cap = apply_filters(
849
+			'FHEE__EE_Capabilities__current_user_can__cap',
850
+			$filtered_cap,
851
+			$context,
852
+			$cap,
853
+			$id
854
+		);
855
+		return ! empty($id)
856
+			? current_user_can($filtered_cap, $id)
857
+			: current_user_can($filtered_cap);
858
+	}
859
+
860
+
861
+
862
+	/**
863
+	 * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
864
+	 *
865
+	 * @param int|WP_User $user    Either the user_id or a WP_User object
866
+	 * @param string      $cap     The capability string being checked
867
+	 * @param string      $context The context where the user_can is being called from (used in filters).
868
+	 * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
869
+	 *                             filters)
870
+	 *
871
+	 * @return bool Whether user can or not.
872
+	 */
873
+	public function user_can($user, $cap, $context, $id = 0)
874
+	{
875
+		//apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
876
+		$filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
877
+		$filtered_cap = apply_filters(
878
+			'FHEE__EE_Capabilities__user_can__cap',
879
+			$filtered_cap,
880
+			$context,
881
+			$cap,
882
+			$user,
883
+			$id
884
+		);
885
+		return ! empty($id)
886
+			? user_can($user, $filtered_cap, $id)
887
+			: user_can($user, $filtered_cap);
888
+	}
889
+
890
+
891
+
892
+	/**
893
+	 * Wrapper for the native WP current_user_can_for_blog() method.
894
+	 * This is provided as a handy method for a couple things:
895
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
896
+	 * write those filters wherever current_user_can is called).
897
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
898
+	 *
899
+	 * @since 4.5.0
900
+	 *
901
+	 * @param int    $blog_id The blog id that is being checked for.
902
+	 * @param string $cap     The cap being checked.
903
+	 * @param string $context The context where the current_user_can is being called from.
904
+	 * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
905
+	 *                        filters.
906
+	 *
907
+	 * @return bool  Whether user can or not.
908
+	 */
909
+	public function current_user_can_for_blog($blog_id, $cap, $context, $id = 0)
910
+	{
911
+		$user_can = ! empty($id)
912
+			? current_user_can_for_blog($blog_id, $cap, $id)
913
+			: current_user_can($blog_id, $cap);
914
+		//apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
915
+		$user_can = apply_filters(
916
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
917
+			$user_can,
918
+			$blog_id,
919
+			$cap,
920
+			$id
921
+		);
922
+		$user_can = apply_filters(
923
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
924
+			$user_can,
925
+			$context,
926
+			$blog_id,
927
+			$cap,
928
+			$id
929
+		);
930
+		return $user_can;
931
+	}
932
+
933
+
934
+
935
+	/**
936
+	 * This helper method just returns an array of registered EE capabilities.
937
+	 *
938
+	 * @since 4.5.0
939
+	 * @param string $role If empty then the entire role/capability map is returned.
940
+	 *                     Otherwise just the capabilities for the given role are returned.
941
+	 * @return array
942
+	 * @throws EE_Error
943
+	 */
944
+	public function get_ee_capabilities($role = 'administrator')
945
+	{
946
+		if (! $this->initialized) {
947
+			$this->init_caps();
948
+		}
949
+		if (empty($role)) {
950
+			return $this->capabilities_map;
951
+		}
952
+		return isset($this->capabilities_map[ $role ])
953
+			? $this->capabilities_map[ $role ]
954
+			: array();
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * @deprecated 4.9.42
961
+	 * @param bool  $reset      If you need to reset Event Espresso's capabilities,
962
+	 *                          then please use the init_caps() method with the "$reset" parameter set to "true"
963
+	 * @param array $caps_map   Optional.
964
+	 *                          Can be used to send a custom map of roles and capabilities for setting them up.
965
+	 *                          Note that this should ONLY be called on activation hook or some other one-time
966
+	 *                          task otherwise the caps will be added on every request.
967
+	 * @return void
968
+	 * @throws EE_Error
969
+	 */
970
+	public function init_role_caps($reset = false, $caps_map = array())
971
+	{
972
+		// If this method is called directly and reset is set as 'true',
973
+		// then display a doing it wrong notice, because we want resets to go through init_caps()
974
+		// to guarantee that everything is set up correctly.
975
+		// This prevents the capabilities map getting reset incorrectly by direct calls to this method.
976
+		if ($reset) {
977
+			EE_Error::doing_it_wrong(
978
+				__METHOD__,
979
+				sprintf(
980
+					esc_html__(
981
+						'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
982
+						'event_espresso'
983
+					),
984
+					'$reset',
985
+					__METHOD__ . '()',
986
+					'EE_Capabilities::init_caps()',
987
+					'true'
988
+				),
989
+				'4.9.42',
990
+				'5.0.0'
991
+			);
992
+		}
993
+		$this->addCaps($caps_map);
994
+	}
995 995
 
996 996
 
997 997
 
@@ -1012,142 +1012,142 @@  discard block
 block discarded – undo
1012 1012
 abstract class EE_Meta_Capability_Map
1013 1013
 {
1014 1014
 
1015
-    public $meta_cap;
1016
-
1017
-    /**
1018
-     * @var EEM_Base
1019
-     */
1020
-    protected $_model;
1021
-
1022
-    protected $_model_name;
1023
-
1024
-    public $published_cap = '';
1025
-
1026
-    public $others_cap = '';
1027
-
1028
-    public $private_cap = '';
1029
-
1030
-
1031
-    /**
1032
-     * constructor.
1033
-     * Receives the setup arguments for the map.
1034
-     *
1035
-     * @since                        4.5.0
1036
-     *
1037
-     * @param string $meta_cap   What meta capability is this mapping.
1038
-     * @param array  $map_values array {
1039
-     *                           //array of values that MUST match a count of 4.  It's okay to send an empty string for
1040
-     *                           capabilities that don't get mapped to.
1041
-     *
1042
-     * @type         $map_values [0] string A string representing the model name. Required.  String's
1043
-     *                               should always be used when Menu Maps are registered via the
1044
-     *                               plugin API as models are not allowed to be instantiated when
1045
-     *                               in maintenance mode 2 (migrations).
1046
-     * @type         $map_values [1] string represents the capability used for published. Optional.
1047
-     * @type         $map_values [2] string represents the capability used for "others". Optional.
1048
-     * @type         $map_values [3] string represents the capability used for private. Optional.
1049
-     *                               }
1050
-     * @throws EE_Error
1051
-     */
1052
-    public function __construct($meta_cap, $map_values)
1053
-    {
1054
-        $this->meta_cap = $meta_cap;
1055
-        //verify there are four args in the $map_values array;
1056
-        if (count($map_values) !== 4) {
1057
-            throw new EE_Error(
1058
-                sprintf(
1059
-                    __(
1060
-                        'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1061
-                        'event_espresso'
1062
-                    ),
1063
-                    '<br>' . print_r($map_values, true)
1064
-                )
1065
-            );
1066
-        }
1067
-        //set properties
1068
-        $this->_model = null;
1069
-        $this->_model_name = $map_values[0];
1070
-        $this->published_cap = (string)$map_values[1];
1071
-        $this->others_cap = (string)$map_values[2];
1072
-        $this->private_cap = (string)$map_values[3];
1073
-    }
1074
-
1075
-    /**
1076
-     * Makes it so this object stops filtering caps
1077
-     */
1078
-    public function remove_filters()
1079
-    {
1080
-        remove_filter('map_meta_cap', array($this, 'map_meta_caps'), 10);
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1086
-     *
1087
-     * @since 4.5.0
1088
-     * @throws EE_Error
1089
-     *
1090
-     * @return void
1091
-     */
1092
-    public function ensure_is_model()
1093
-    {
1094
-        //is it already instantiated?
1095
-        if ($this->_model instanceof EEM_Base) {
1096
-            return;
1097
-        }
1098
-        //ensure model name is string
1099
-        $this->_model_name = (string)$this->_model_name;
1100
-        //error proof if the name has EEM in it
1101
-        $this->_model_name = str_replace('EEM', '', $this->_model_name);
1102
-        $this->_model = EE_Registry::instance()->load_model($this->_model_name);
1103
-        if (! $this->_model instanceof EEM_Base) {
1104
-            throw new EE_Error(
1105
-                sprintf(
1106
-                    __(
1107
-                        'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1108
-                        'event_espresso'
1109
-                    ),
1110
-                    get_class($this),
1111
-                    $this->_model
1112
-                )
1113
-            );
1114
-        }
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     *
1120
-     * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1121
-     * @since 4.6.x
1122
-     *
1123
-     * @param $caps
1124
-     * @param $cap
1125
-     * @param $user_id
1126
-     * @param $args
1127
-     *
1128
-     * @return array
1129
-     */
1130
-    public function map_meta_caps($caps, $cap, $user_id, $args)
1131
-    {
1132
-        return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1138
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1139
-     *
1140
-     * @since 4.5.0
1141
-     * @see   wp-includes/capabilities.php
1142
-     *
1143
-     * @param array  $caps    actual users capabilities
1144
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1145
-     * @param int    $user_id The user id
1146
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1147
-     *
1148
-     * @return array   actual users capabilities
1149
-     */
1150
-    abstract protected function _map_meta_caps($caps, $cap, $user_id, $args);
1015
+	public $meta_cap;
1016
+
1017
+	/**
1018
+	 * @var EEM_Base
1019
+	 */
1020
+	protected $_model;
1021
+
1022
+	protected $_model_name;
1023
+
1024
+	public $published_cap = '';
1025
+
1026
+	public $others_cap = '';
1027
+
1028
+	public $private_cap = '';
1029
+
1030
+
1031
+	/**
1032
+	 * constructor.
1033
+	 * Receives the setup arguments for the map.
1034
+	 *
1035
+	 * @since                        4.5.0
1036
+	 *
1037
+	 * @param string $meta_cap   What meta capability is this mapping.
1038
+	 * @param array  $map_values array {
1039
+	 *                           //array of values that MUST match a count of 4.  It's okay to send an empty string for
1040
+	 *                           capabilities that don't get mapped to.
1041
+	 *
1042
+	 * @type         $map_values [0] string A string representing the model name. Required.  String's
1043
+	 *                               should always be used when Menu Maps are registered via the
1044
+	 *                               plugin API as models are not allowed to be instantiated when
1045
+	 *                               in maintenance mode 2 (migrations).
1046
+	 * @type         $map_values [1] string represents the capability used for published. Optional.
1047
+	 * @type         $map_values [2] string represents the capability used for "others". Optional.
1048
+	 * @type         $map_values [3] string represents the capability used for private. Optional.
1049
+	 *                               }
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	public function __construct($meta_cap, $map_values)
1053
+	{
1054
+		$this->meta_cap = $meta_cap;
1055
+		//verify there are four args in the $map_values array;
1056
+		if (count($map_values) !== 4) {
1057
+			throw new EE_Error(
1058
+				sprintf(
1059
+					__(
1060
+						'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1061
+						'event_espresso'
1062
+					),
1063
+					'<br>' . print_r($map_values, true)
1064
+				)
1065
+			);
1066
+		}
1067
+		//set properties
1068
+		$this->_model = null;
1069
+		$this->_model_name = $map_values[0];
1070
+		$this->published_cap = (string)$map_values[1];
1071
+		$this->others_cap = (string)$map_values[2];
1072
+		$this->private_cap = (string)$map_values[3];
1073
+	}
1074
+
1075
+	/**
1076
+	 * Makes it so this object stops filtering caps
1077
+	 */
1078
+	public function remove_filters()
1079
+	{
1080
+		remove_filter('map_meta_cap', array($this, 'map_meta_caps'), 10);
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1086
+	 *
1087
+	 * @since 4.5.0
1088
+	 * @throws EE_Error
1089
+	 *
1090
+	 * @return void
1091
+	 */
1092
+	public function ensure_is_model()
1093
+	{
1094
+		//is it already instantiated?
1095
+		if ($this->_model instanceof EEM_Base) {
1096
+			return;
1097
+		}
1098
+		//ensure model name is string
1099
+		$this->_model_name = (string)$this->_model_name;
1100
+		//error proof if the name has EEM in it
1101
+		$this->_model_name = str_replace('EEM', '', $this->_model_name);
1102
+		$this->_model = EE_Registry::instance()->load_model($this->_model_name);
1103
+		if (! $this->_model instanceof EEM_Base) {
1104
+			throw new EE_Error(
1105
+				sprintf(
1106
+					__(
1107
+						'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1108
+						'event_espresso'
1109
+					),
1110
+					get_class($this),
1111
+					$this->_model
1112
+				)
1113
+			);
1114
+		}
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 *
1120
+	 * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1121
+	 * @since 4.6.x
1122
+	 *
1123
+	 * @param $caps
1124
+	 * @param $cap
1125
+	 * @param $user_id
1126
+	 * @param $args
1127
+	 *
1128
+	 * @return array
1129
+	 */
1130
+	public function map_meta_caps($caps, $cap, $user_id, $args)
1131
+	{
1132
+		return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1138
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1139
+	 *
1140
+	 * @since 4.5.0
1141
+	 * @see   wp-includes/capabilities.php
1142
+	 *
1143
+	 * @param array  $caps    actual users capabilities
1144
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1145
+	 * @param int    $user_id The user id
1146
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1147
+	 *
1148
+	 * @return array   actual users capabilities
1149
+	 */
1150
+	abstract protected function _map_meta_caps($caps, $cap, $user_id, $args);
1151 1151
 }
1152 1152
 
1153 1153
 
@@ -1163,81 +1163,81 @@  discard block
 block discarded – undo
1163 1163
 class EE_Meta_Capability_Map_Edit extends EE_Meta_Capability_Map
1164 1164
 {
1165 1165
 
1166
-    /**
1167
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1168
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1169
-     *
1170
-     * @since 4.5.0
1171
-     * @see   wp-includes/capabilities.php
1172
-     *
1173
-     * @param array  $caps    actual users capabilities
1174
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1175
-     * @param int    $user_id The user id
1176
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1177
-     *
1178
-     * @return array   actual users capabilities
1179
-     */
1180
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1181
-    {
1182
-        //only process if we're checking our mapped_cap
1183
-        if ($cap !== $this->meta_cap) {
1184
-            return $caps;
1185
-        }
1186
-
1187
-        //okay it is a meta cap so let's first remove that cap from the $caps array.
1188
-        if (($key = array_search($cap, $caps)) !== false) {
1189
-            unset($caps[$key]);
1190
-        }
1191
-
1192
-        //cast $user_id to int for later explicit comparisons
1193
-        $user_id = (int) $user_id;
1194
-
1195
-        /** @var EE_Base_Class $obj */
1196
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1197
-        //if no obj then let's just do cap
1198
-        if (! $obj instanceof EE_Base_Class) {
1199
-            $caps[] = 'do_not_allow';
1200
-            return $caps;
1201
-        }
1202
-        $caps[] = $cap . 's';
1203
-        if ($obj instanceof EE_CPT_Base) {
1204
-            //if the item author is set and the user is the author...
1205
-            if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1206
-                //if obj is published...
1207
-                if ($obj->status() === 'publish') {
1208
-                    $caps[] = $this->published_cap;
1209
-                }
1210
-            } else {
1211
-                //the user is trying to edit someone else's obj
1212
-                if (! empty($this->others_cap)) {
1213
-                    $caps[] = $this->others_cap;
1214
-                }
1215
-                if (! empty($this->published_cap) && $obj->status() === 'publish') {
1216
-                    $caps[] = $this->published_cap;
1217
-                } elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1218
-                    $caps[] = $this->private_cap;
1219
-                }
1220
-            }
1221
-        } else {
1222
-            //not a cpt object so handled differently
1223
-            $has_cap = false;
1224
-            try {
1225
-                $has_cap = method_exists($obj, 'wp_user')
1226
-                    && $obj->wp_user()
1227
-                    && $obj->wp_user() === $user_id;
1228
-            } catch (Exception $e) {
1229
-                if (WP_DEBUG) {
1230
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1231
-                }
1232
-            }
1233
-            if (! $has_cap) {
1234
-                if (! empty($this->others_cap)) {
1235
-                    $caps[] = $this->others_cap;
1236
-                }
1237
-            }
1238
-        }
1239
-        return $caps;
1240
-    }
1166
+	/**
1167
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1168
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1169
+	 *
1170
+	 * @since 4.5.0
1171
+	 * @see   wp-includes/capabilities.php
1172
+	 *
1173
+	 * @param array  $caps    actual users capabilities
1174
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1175
+	 * @param int    $user_id The user id
1176
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1177
+	 *
1178
+	 * @return array   actual users capabilities
1179
+	 */
1180
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1181
+	{
1182
+		//only process if we're checking our mapped_cap
1183
+		if ($cap !== $this->meta_cap) {
1184
+			return $caps;
1185
+		}
1186
+
1187
+		//okay it is a meta cap so let's first remove that cap from the $caps array.
1188
+		if (($key = array_search($cap, $caps)) !== false) {
1189
+			unset($caps[$key]);
1190
+		}
1191
+
1192
+		//cast $user_id to int for later explicit comparisons
1193
+		$user_id = (int) $user_id;
1194
+
1195
+		/** @var EE_Base_Class $obj */
1196
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1197
+		//if no obj then let's just do cap
1198
+		if (! $obj instanceof EE_Base_Class) {
1199
+			$caps[] = 'do_not_allow';
1200
+			return $caps;
1201
+		}
1202
+		$caps[] = $cap . 's';
1203
+		if ($obj instanceof EE_CPT_Base) {
1204
+			//if the item author is set and the user is the author...
1205
+			if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1206
+				//if obj is published...
1207
+				if ($obj->status() === 'publish') {
1208
+					$caps[] = $this->published_cap;
1209
+				}
1210
+			} else {
1211
+				//the user is trying to edit someone else's obj
1212
+				if (! empty($this->others_cap)) {
1213
+					$caps[] = $this->others_cap;
1214
+				}
1215
+				if (! empty($this->published_cap) && $obj->status() === 'publish') {
1216
+					$caps[] = $this->published_cap;
1217
+				} elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1218
+					$caps[] = $this->private_cap;
1219
+				}
1220
+			}
1221
+		} else {
1222
+			//not a cpt object so handled differently
1223
+			$has_cap = false;
1224
+			try {
1225
+				$has_cap = method_exists($obj, 'wp_user')
1226
+					&& $obj->wp_user()
1227
+					&& $obj->wp_user() === $user_id;
1228
+			} catch (Exception $e) {
1229
+				if (WP_DEBUG) {
1230
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1231
+				}
1232
+			}
1233
+			if (! $has_cap) {
1234
+				if (! empty($this->others_cap)) {
1235
+					$caps[] = $this->others_cap;
1236
+				}
1237
+			}
1238
+		}
1239
+		return $caps;
1240
+	}
1241 1241
 }
1242 1242
 
1243 1243
 
@@ -1254,24 +1254,24 @@  discard block
 block discarded – undo
1254 1254
 class EE_Meta_Capability_Map_Delete extends EE_Meta_Capability_Map_Edit
1255 1255
 {
1256 1256
 
1257
-    /**
1258
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1259
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1260
-     *
1261
-     * @since 4.5.0
1262
-     * @see   wp-includes/capabilities.php
1263
-     *
1264
-     * @param array  $caps    actual users capabilities
1265
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1266
-     * @param int    $user_id The user id
1267
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1268
-     *
1269
-     * @return array   actual users capabilities
1270
-     */
1271
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1272
-    {
1273
-        return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1274
-    }
1257
+	/**
1258
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1259
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1260
+	 *
1261
+	 * @since 4.5.0
1262
+	 * @see   wp-includes/capabilities.php
1263
+	 *
1264
+	 * @param array  $caps    actual users capabilities
1265
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1266
+	 * @param int    $user_id The user id
1267
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1268
+	 *
1269
+	 * @return array   actual users capabilities
1270
+	 */
1271
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1272
+	{
1273
+		return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1274
+	}
1275 1275
 }
1276 1276
 
1277 1277
 
@@ -1287,85 +1287,85 @@  discard block
 block discarded – undo
1287 1287
 class EE_Meta_Capability_Map_Read extends EE_Meta_Capability_Map
1288 1288
 {
1289 1289
 
1290
-    /**
1291
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1292
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1293
-     *
1294
-     * @since 4.5.0
1295
-     * @see   wp-includes/capabilities.php
1296
-     *
1297
-     * @param array  $caps    actual users capabilities
1298
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1299
-     * @param int    $user_id The user id
1300
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1301
-     *
1302
-     * @return array   actual users capabilities
1303
-     */
1304
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1305
-    {
1306
-        //only process if we're checking our mapped cap;
1307
-        if ($cap !== $this->meta_cap) {
1308
-            return $caps;
1309
-        }
1310
-
1311
-        //okay it is a meta cap so let's first remove that cap from the $caps array.
1312
-        if (($key = array_search($cap, $caps)) !== false) {
1313
-            unset($caps[$key]);
1314
-        }
1315
-
1316
-        //cast $user_id to int for later explicit comparisons
1317
-        $user_id = (int) $user_id;
1318
-
1319
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1320
-        //if no obj then let's just do cap
1321
-        if (! $obj instanceof EE_Base_Class) {
1322
-            $caps[] = 'do_not_allow';
1323
-            return $caps;
1324
-        }
1325
-
1326
-        $caps[] = $cap . 's';
1327
-        if ($obj instanceof EE_CPT_Base) {
1328
-            $status_obj = get_post_status_object($obj->status());
1329
-            if ($status_obj->public) {
1330
-                return $caps;
1331
-            }
1332
-            //if the item author is set and the user is not the author...
1333
-            if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1334
-                if (! empty($this->others_cap)) {
1335
-                    $caps[] = $this->others_cap;
1336
-                }
1337
-            }
1338
-            //yes this means that if users created the private post, they are able to see it regardless of private cap.
1339
-            if ($status_obj->private
1340
-                && ! empty($this->private_cap)
1341
-                && $obj->wp_user() !== $user_id
1342
-            ) {
1343
-                //the user is trying to view a private object for an object they don't own.
1344
-                $caps[] = $this->private_cap;
1345
-            }
1346
-        } else {
1347
-            //not a cpt object so handled differently
1348
-            $has_cap = false;
1349
-            try {
1350
-                $has_cap = method_exists($obj, 'wp_user')
1351
-                           && $obj->wp_user()
1352
-                           && $obj->wp_user() === $user_id;
1353
-            } catch (Exception $e) {
1354
-                if (WP_DEBUG) {
1355
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1356
-                }
1357
-            }
1358
-            if (! $has_cap) {
1359
-                if (! empty($this->private_cap)) {
1360
-                    $caps[] = $this->private_cap;
1361
-                }
1362
-                if (! empty($this->others_cap)) {
1363
-                    $caps[] = $this->others_cap;
1364
-                }
1365
-            }
1366
-        }
1367
-        return $caps;
1368
-    }
1290
+	/**
1291
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1292
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1293
+	 *
1294
+	 * @since 4.5.0
1295
+	 * @see   wp-includes/capabilities.php
1296
+	 *
1297
+	 * @param array  $caps    actual users capabilities
1298
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1299
+	 * @param int    $user_id The user id
1300
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1301
+	 *
1302
+	 * @return array   actual users capabilities
1303
+	 */
1304
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1305
+	{
1306
+		//only process if we're checking our mapped cap;
1307
+		if ($cap !== $this->meta_cap) {
1308
+			return $caps;
1309
+		}
1310
+
1311
+		//okay it is a meta cap so let's first remove that cap from the $caps array.
1312
+		if (($key = array_search($cap, $caps)) !== false) {
1313
+			unset($caps[$key]);
1314
+		}
1315
+
1316
+		//cast $user_id to int for later explicit comparisons
1317
+		$user_id = (int) $user_id;
1318
+
1319
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1320
+		//if no obj then let's just do cap
1321
+		if (! $obj instanceof EE_Base_Class) {
1322
+			$caps[] = 'do_not_allow';
1323
+			return $caps;
1324
+		}
1325
+
1326
+		$caps[] = $cap . 's';
1327
+		if ($obj instanceof EE_CPT_Base) {
1328
+			$status_obj = get_post_status_object($obj->status());
1329
+			if ($status_obj->public) {
1330
+				return $caps;
1331
+			}
1332
+			//if the item author is set and the user is not the author...
1333
+			if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1334
+				if (! empty($this->others_cap)) {
1335
+					$caps[] = $this->others_cap;
1336
+				}
1337
+			}
1338
+			//yes this means that if users created the private post, they are able to see it regardless of private cap.
1339
+			if ($status_obj->private
1340
+				&& ! empty($this->private_cap)
1341
+				&& $obj->wp_user() !== $user_id
1342
+			) {
1343
+				//the user is trying to view a private object for an object they don't own.
1344
+				$caps[] = $this->private_cap;
1345
+			}
1346
+		} else {
1347
+			//not a cpt object so handled differently
1348
+			$has_cap = false;
1349
+			try {
1350
+				$has_cap = method_exists($obj, 'wp_user')
1351
+						   && $obj->wp_user()
1352
+						   && $obj->wp_user() === $user_id;
1353
+			} catch (Exception $e) {
1354
+				if (WP_DEBUG) {
1355
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1356
+				}
1357
+			}
1358
+			if (! $has_cap) {
1359
+				if (! empty($this->private_cap)) {
1360
+					$caps[] = $this->private_cap;
1361
+				}
1362
+				if (! empty($this->others_cap)) {
1363
+					$caps[] = $this->others_cap;
1364
+				}
1365
+			}
1366
+		}
1367
+		return $caps;
1368
+	}
1369 1369
 }
1370 1370
 
1371 1371
 
@@ -1382,56 +1382,56 @@  discard block
 block discarded – undo
1382 1382
 class EE_Meta_Capability_Map_Messages_Cap extends EE_Meta_Capability_Map
1383 1383
 {
1384 1384
 
1385
-    /**
1386
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1387
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1388
-     *
1389
-     * @since 4.5.0
1390
-     * @see   wp-includes/capabilities.php
1391
-     *
1392
-     * @param array  $caps    actual users capabilities
1393
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1394
-     * @param int    $user_id The user id
1395
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1396
-     *
1397
-     * @return array   actual users capabilities
1398
-     */
1399
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1400
-    {
1401
-        //only process if we're checking our mapped_cap
1402
-        if ($cap !== $this->meta_cap) {
1403
-            return $caps;
1404
-        }
1405
-
1406
-        //okay it is a meta cap so let's first remove that cap from the $caps array.
1407
-        if (($key = array_search($cap, $caps)) !== false) {
1408
-            unset($caps[$key]);
1409
-        }
1410
-
1411
-        //cast $user_id to int for later explicit comparisons
1412
-        $user_id = (int) $user_id;
1413
-
1414
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1415
-        //if no obj then let's just do cap
1416
-        if (! $obj instanceof EE_Message_Template_Group) {
1417
-            $caps[] = 'do_not_allow';
1418
-            return $caps;
1419
-        }
1420
-        $caps[] = $cap . 's';
1421
-        $is_global = $obj->is_global();
1422
-        if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1423
-            if ($is_global) {
1424
-                $caps[] = $this->private_cap;
1425
-            }
1426
-        } else {
1427
-            if ($is_global) {
1428
-                $caps[] = $this->private_cap;
1429
-            } else {
1430
-                $caps[] = $this->others_cap;
1431
-            }
1432
-        }
1433
-        return $caps;
1434
-    }
1385
+	/**
1386
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1387
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1388
+	 *
1389
+	 * @since 4.5.0
1390
+	 * @see   wp-includes/capabilities.php
1391
+	 *
1392
+	 * @param array  $caps    actual users capabilities
1393
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1394
+	 * @param int    $user_id The user id
1395
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1396
+	 *
1397
+	 * @return array   actual users capabilities
1398
+	 */
1399
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1400
+	{
1401
+		//only process if we're checking our mapped_cap
1402
+		if ($cap !== $this->meta_cap) {
1403
+			return $caps;
1404
+		}
1405
+
1406
+		//okay it is a meta cap so let's first remove that cap from the $caps array.
1407
+		if (($key = array_search($cap, $caps)) !== false) {
1408
+			unset($caps[$key]);
1409
+		}
1410
+
1411
+		//cast $user_id to int for later explicit comparisons
1412
+		$user_id = (int) $user_id;
1413
+
1414
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1415
+		//if no obj then let's just do cap
1416
+		if (! $obj instanceof EE_Message_Template_Group) {
1417
+			$caps[] = 'do_not_allow';
1418
+			return $caps;
1419
+		}
1420
+		$caps[] = $cap . 's';
1421
+		$is_global = $obj->is_global();
1422
+		if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1423
+			if ($is_global) {
1424
+				$caps[] = $this->private_cap;
1425
+			}
1426
+		} else {
1427
+			if ($is_global) {
1428
+				$caps[] = $this->private_cap;
1429
+			} else {
1430
+				$caps[] = $this->others_cap;
1431
+			}
1432
+		}
1433
+		return $caps;
1434
+	}
1435 1435
 }
1436 1436
 
1437 1437
 
@@ -1448,40 +1448,40 @@  discard block
 block discarded – undo
1448 1448
 class EE_Meta_Capability_Map_Registration_Form_Cap extends EE_Meta_Capability_Map
1449 1449
 {
1450 1450
 
1451
-    /**
1452
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1453
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1454
-     *
1455
-     * @since 4.5.0
1456
-     * @see   wp-includes/capabilities.php
1457
-     * @param array  $caps    actual users capabilities
1458
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1459
-     * @param int    $user_id The user id
1460
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1461
-     * @return array   actual users capabilities
1462
-     */
1463
-    protected function _map_meta_caps($caps, $cap, $user_id, $args)
1464
-    {
1465
-        //only process if we're checking our mapped_cap
1466
-        if ($cap !== $this->meta_cap) {
1467
-            return $caps;
1468
-        }
1469
-        //okay it is a meta cap so let's first remove that cap from the $caps array.
1470
-        if (($key = array_search($cap, $caps)) !== false) {
1471
-            unset($caps[$key]);
1472
-        }
1473
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1474
-        //if no obj then let's just do cap
1475
-        if (! $obj instanceof EE_Base_Class) {
1476
-            $caps[] = 'do_not_allow';
1477
-            return $caps;
1478
-        }
1479
-        $caps[]    = $cap . 's';
1480
-        $is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1481
-        $is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1482
-        if ($is_system) {
1483
-            $caps[] = $this->private_cap;
1484
-        }
1485
-        return $caps;
1486
-    }
1451
+	/**
1452
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1453
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1454
+	 *
1455
+	 * @since 4.5.0
1456
+	 * @see   wp-includes/capabilities.php
1457
+	 * @param array  $caps    actual users capabilities
1458
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1459
+	 * @param int    $user_id The user id
1460
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1461
+	 * @return array   actual users capabilities
1462
+	 */
1463
+	protected function _map_meta_caps($caps, $cap, $user_id, $args)
1464
+	{
1465
+		//only process if we're checking our mapped_cap
1466
+		if ($cap !== $this->meta_cap) {
1467
+			return $caps;
1468
+		}
1469
+		//okay it is a meta cap so let's first remove that cap from the $caps array.
1470
+		if (($key = array_search($cap, $caps)) !== false) {
1471
+			unset($caps[$key]);
1472
+		}
1473
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1474
+		//if no obj then let's just do cap
1475
+		if (! $obj instanceof EE_Base_Class) {
1476
+			$caps[] = 'do_not_allow';
1477
+			return $caps;
1478
+		}
1479
+		$caps[]    = $cap . 's';
1480
+		$is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1481
+		$is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1482
+		if ($is_system) {
1483
+			$caps[] = $this->private_cap;
1484
+		}
1485
+		return $caps;
1486
+	}
1487 1487
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
     public static function instance()
86 86
     {
87 87
         //check if instantiated, and if not do so.
88
-        if (! self::$_instance instanceof EE_Capabilities) {
88
+        if ( ! self::$_instance instanceof EE_Capabilities) {
89 89
             self::$_instance = new self();
90 90
         }
91 91
         return self::$_instance;
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
      */
118 118
     public function init_caps($reset = false)
119 119
     {
120
-        if(! EE_Maintenance_Mode::instance()->models_can_query()){
120
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
121 121
             return false;
122 122
         }
123 123
         $this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
             $this->_get_default_meta_caps_array()
164 164
         );
165 165
         //add filter for map_meta_caps but only if models can query.
166
-        if (! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
166
+        if ( ! has_filter('map_meta_cap', array($this, 'map_meta_caps'))) {
167 167
             add_filter('map_meta_cap', array($this, 'map_meta_caps'), 10, 4);
168 168
         }
169 169
     }
@@ -324,11 +324,11 @@  discard block
 block discarded – undo
324 324
         if (did_action('AHEE__EE_System__load_espresso_addons__complete')) {
325 325
             //loop through our _meta_caps array
326 326
             foreach ($this->_meta_caps as $meta_map) {
327
-                if (! $meta_map instanceof EE_Meta_Capability_Map) {
327
+                if ( ! $meta_map instanceof EE_Meta_Capability_Map) {
328 328
                     continue;
329 329
                 }
330 330
                 // don't load models if there is no object ID in the args
331
-                if (! empty($args[0])) {
331
+                if ( ! empty($args[0])) {
332 332
                     $meta_map->ensure_is_model();
333 333
                 }
334 334
                 $caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
     private function setupCapabilitiesMap()
631 631
     {
632 632
         // if the initialization process hasn't even started, then we need to call init_caps()
633
-        if($this->initialized === null) {
633
+        if ($this->initialized === null) {
634 634
             return $this->init_caps();
635 635
         }
636 636
         // unless resetting, get caps from db if we haven't already
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
     public function addCaps(array $capabilities_to_add)
667 667
     {
668 668
         // don't do anything if the capabilities map can not be initialized
669
-        if (! $this->setupCapabilitiesMap()) {
669
+        if ( ! $this->setupCapabilitiesMap()) {
670 670
             return false;
671 671
         }
672 672
         // and filter the array so others can get in on the fun during resets
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
     public function removeCaps($caps_map)
709 709
     {
710 710
         // don't do anything if the capabilities map can not be initialized
711
-        if (! $this->setupCapabilitiesMap()) {
711
+        if ( ! $this->setupCapabilitiesMap()) {
712 712
             return false;
713 713
         }
714 714
         $update_capabilities_map = false;
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
         $orig_role = $role;
751 751
         $role = $role instanceof WP_Role ? $role : get_role($role);
752 752
         //if the role isn't available then we create it.
753
-        if (! $role instanceof WP_Role) {
753
+        if ( ! $role instanceof WP_Role) {
754 754
             // if a plugin wants to create a specific role name then they should create the role before
755 755
             // EE_Capabilities does.  Otherwise this function will create the role name from the slug:
756 756
             // - removes any `ee_` namespacing from the start of the slug.
@@ -761,12 +761,12 @@  discard block
 block discarded – undo
761 761
         }
762 762
         if ($role instanceof WP_Role) {
763 763
             // don't do anything if the capabilities map can not be initialized
764
-            if (! $this->setupCapabilitiesMap()) {
764
+            if ( ! $this->setupCapabilitiesMap()) {
765 765
                 return false;
766 766
             }
767
-            if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
767
+            if ( ! $this->capHasBeenAddedToRole($role->name, $cap)) {
768 768
                 $role->add_cap($cap, $grant);
769
-                $this->capabilities_map[ $role->name ][] = $cap;
769
+                $this->capabilities_map[$role->name][] = $cap;
770 770
                 $this->updateCapabilitiesMap($update_capabilities_map);
771 771
                 return true;
772 772
             }
@@ -791,13 +791,13 @@  discard block
 block discarded – undo
791 791
     public function remove_cap_from_role($role, $cap, $update_capabilities_map = true)
792 792
     {
793 793
         // don't do anything if the capabilities map can not be initialized
794
-        if (! $this->setupCapabilitiesMap()) {
794
+        if ( ! $this->setupCapabilitiesMap()) {
795 795
             return false;
796 796
         }
797
-        $role = $role instanceof WP_Role ? $role :get_role($role);
797
+        $role = $role instanceof WP_Role ? $role : get_role($role);
798 798
         if ($index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
799 799
             $role->remove_cap($cap);
800
-            unset($this->capabilities_map[ $role->name ][ $index ]);
800
+            unset($this->capabilities_map[$role->name][$index]);
801 801
             $this->updateCapabilitiesMap($update_capabilities_map);
802 802
             return true;
803 803
         }
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
      * @param bool   $get_index
813 813
      * @return bool|mixed
814 814
      */
815
-    private function capHasBeenAddedToRole($role_name='', $cap='', $get_index = false)
815
+    private function capHasBeenAddedToRole($role_name = '', $cap = '', $get_index = false)
816 816
     {
817 817
         if (
818 818
             isset($this->capabilities_map[$role_name])
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
     public function current_user_can($cap, $context, $id = 0)
845 845
     {
846 846
         //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
847
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id);
847
+        $filtered_cap = apply_filters('FHEE__EE_Capabilities__current_user_can__cap__'.$context, $cap, $id);
848 848
         $filtered_cap = apply_filters(
849 849
             'FHEE__EE_Capabilities__current_user_can__cap',
850 850
             $filtered_cap,
@@ -873,7 +873,7 @@  discard block
 block discarded – undo
873 873
     public function user_can($user, $cap, $context, $id = 0)
874 874
     {
875 875
         //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
876
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
876
+        $filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__'.$context, $cap, $user, $id);
877 877
         $filtered_cap = apply_filters(
878 878
             'FHEE__EE_Capabilities__user_can__cap',
879 879
             $filtered_cap,
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
             : current_user_can($blog_id, $cap);
914 914
         //apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
915 915
         $user_can = apply_filters(
916
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
916
+            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__'.$context,
917 917
             $user_can,
918 918
             $blog_id,
919 919
             $cap,
@@ -943,14 +943,14 @@  discard block
 block discarded – undo
943 943
      */
944 944
     public function get_ee_capabilities($role = 'administrator')
945 945
     {
946
-        if (! $this->initialized) {
946
+        if ( ! $this->initialized) {
947 947
             $this->init_caps();
948 948
         }
949 949
         if (empty($role)) {
950 950
             return $this->capabilities_map;
951 951
         }
952
-        return isset($this->capabilities_map[ $role ])
953
-            ? $this->capabilities_map[ $role ]
952
+        return isset($this->capabilities_map[$role])
953
+            ? $this->capabilities_map[$role]
954 954
             : array();
955 955
     }
956 956
 
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
                         'event_espresso'
983 983
                     ),
984 984
                     '$reset',
985
-                    __METHOD__ . '()',
985
+                    __METHOD__.'()',
986 986
                     'EE_Capabilities::init_caps()',
987 987
                     'true'
988 988
                 ),
@@ -1060,16 +1060,16 @@  discard block
 block discarded – undo
1060 1060
                         'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1061 1061
                         'event_espresso'
1062 1062
                     ),
1063
-                    '<br>' . print_r($map_values, true)
1063
+                    '<br>'.print_r($map_values, true)
1064 1064
                 )
1065 1065
             );
1066 1066
         }
1067 1067
         //set properties
1068 1068
         $this->_model = null;
1069 1069
         $this->_model_name = $map_values[0];
1070
-        $this->published_cap = (string)$map_values[1];
1071
-        $this->others_cap = (string)$map_values[2];
1072
-        $this->private_cap = (string)$map_values[3];
1070
+        $this->published_cap = (string) $map_values[1];
1071
+        $this->others_cap = (string) $map_values[2];
1072
+        $this->private_cap = (string) $map_values[3];
1073 1073
     }
1074 1074
 
1075 1075
     /**
@@ -1096,11 +1096,11 @@  discard block
 block discarded – undo
1096 1096
             return;
1097 1097
         }
1098 1098
         //ensure model name is string
1099
-        $this->_model_name = (string)$this->_model_name;
1099
+        $this->_model_name = (string) $this->_model_name;
1100 1100
         //error proof if the name has EEM in it
1101 1101
         $this->_model_name = str_replace('EEM', '', $this->_model_name);
1102 1102
         $this->_model = EE_Registry::instance()->load_model($this->_model_name);
1103
-        if (! $this->_model instanceof EEM_Base) {
1103
+        if ( ! $this->_model instanceof EEM_Base) {
1104 1104
             throw new EE_Error(
1105 1105
                 sprintf(
1106 1106
                     __(
@@ -1195,11 +1195,11 @@  discard block
 block discarded – undo
1195 1195
         /** @var EE_Base_Class $obj */
1196 1196
         $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1197 1197
         //if no obj then let's just do cap
1198
-        if (! $obj instanceof EE_Base_Class) {
1198
+        if ( ! $obj instanceof EE_Base_Class) {
1199 1199
             $caps[] = 'do_not_allow';
1200 1200
             return $caps;
1201 1201
         }
1202
-        $caps[] = $cap . 's';
1202
+        $caps[] = $cap.'s';
1203 1203
         if ($obj instanceof EE_CPT_Base) {
1204 1204
             //if the item author is set and the user is the author...
1205 1205
             if ($obj->wp_user() && $user_id === $obj->wp_user()) {
@@ -1209,12 +1209,12 @@  discard block
 block discarded – undo
1209 1209
                 }
1210 1210
             } else {
1211 1211
                 //the user is trying to edit someone else's obj
1212
-                if (! empty($this->others_cap)) {
1212
+                if ( ! empty($this->others_cap)) {
1213 1213
                     $caps[] = $this->others_cap;
1214 1214
                 }
1215
-                if (! empty($this->published_cap) && $obj->status() === 'publish') {
1215
+                if ( ! empty($this->published_cap) && $obj->status() === 'publish') {
1216 1216
                     $caps[] = $this->published_cap;
1217
-                } elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1217
+                } elseif ( ! empty($this->private_cap) && $obj->status() === 'private') {
1218 1218
                     $caps[] = $this->private_cap;
1219 1219
                 }
1220 1220
             }
@@ -1230,8 +1230,8 @@  discard block
 block discarded – undo
1230 1230
                     EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1231 1231
                 }
1232 1232
             }
1233
-            if (! $has_cap) {
1234
-                if (! empty($this->others_cap)) {
1233
+            if ( ! $has_cap) {
1234
+                if ( ! empty($this->others_cap)) {
1235 1235
                     $caps[] = $this->others_cap;
1236 1236
                 }
1237 1237
             }
@@ -1318,12 +1318,12 @@  discard block
 block discarded – undo
1318 1318
 
1319 1319
         $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1320 1320
         //if no obj then let's just do cap
1321
-        if (! $obj instanceof EE_Base_Class) {
1321
+        if ( ! $obj instanceof EE_Base_Class) {
1322 1322
             $caps[] = 'do_not_allow';
1323 1323
             return $caps;
1324 1324
         }
1325 1325
 
1326
-        $caps[] = $cap . 's';
1326
+        $caps[] = $cap.'s';
1327 1327
         if ($obj instanceof EE_CPT_Base) {
1328 1328
             $status_obj = get_post_status_object($obj->status());
1329 1329
             if ($status_obj->public) {
@@ -1331,7 +1331,7 @@  discard block
 block discarded – undo
1331 1331
             }
1332 1332
             //if the item author is set and the user is not the author...
1333 1333
             if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1334
-                if (! empty($this->others_cap)) {
1334
+                if ( ! empty($this->others_cap)) {
1335 1335
                     $caps[] = $this->others_cap;
1336 1336
                 }
1337 1337
             }
@@ -1355,11 +1355,11 @@  discard block
 block discarded – undo
1355 1355
                     EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1356 1356
                 }
1357 1357
             }
1358
-            if (! $has_cap) {
1359
-                if (! empty($this->private_cap)) {
1358
+            if ( ! $has_cap) {
1359
+                if ( ! empty($this->private_cap)) {
1360 1360
                     $caps[] = $this->private_cap;
1361 1361
                 }
1362
-                if (! empty($this->others_cap)) {
1362
+                if ( ! empty($this->others_cap)) {
1363 1363
                     $caps[] = $this->others_cap;
1364 1364
                 }
1365 1365
             }
@@ -1413,11 +1413,11 @@  discard block
 block discarded – undo
1413 1413
 
1414 1414
         $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1415 1415
         //if no obj then let's just do cap
1416
-        if (! $obj instanceof EE_Message_Template_Group) {
1416
+        if ( ! $obj instanceof EE_Message_Template_Group) {
1417 1417
             $caps[] = 'do_not_allow';
1418 1418
             return $caps;
1419 1419
         }
1420
-        $caps[] = $cap . 's';
1420
+        $caps[] = $cap.'s';
1421 1421
         $is_global = $obj->is_global();
1422 1422
         if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1423 1423
             if ($is_global) {
@@ -1472,11 +1472,11 @@  discard block
 block discarded – undo
1472 1472
         }
1473 1473
         $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1474 1474
         //if no obj then let's just do cap
1475
-        if (! $obj instanceof EE_Base_Class) {
1475
+        if ( ! $obj instanceof EE_Base_Class) {
1476 1476
             $caps[] = 'do_not_allow';
1477 1477
             return $caps;
1478 1478
         }
1479
-        $caps[]    = $cap . 's';
1479
+        $caps[]    = $cap.'s';
1480 1480
         $is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1481 1481
         $is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1482 1482
         if ($is_system) {
Please login to merge, or discard this patch.
admin/extend/registrations/Extend_EE_Registrations_List_Table.class.php 2 patches
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -11,104 +11,104 @@
 block discarded – undo
11 11
  */
12 12
 class Extend_EE_Registrations_List_Table extends EE_Registrations_List_Table
13 13
 {
14
-    /**
15
-     * REG_date
16
-     */
17
-    function column__REG_date(EE_Registration $item)
18
-    {
19
-        $date_linked = parent::column__REG_date($item);
20
-        $actions = array();
21
-        //Build row actions
22
-        $check_in_url        = EE_Admin_Page::add_query_args_and_nonce(array(
23
-            'action'   => 'event_registrations',
24
-            'event_id' => $item->event_ID(),
25
-        ), REG_ADMIN_URL);
26
-        $actions['check_in'] = EE_Registry::instance()->CAP->current_user_can(
27
-            'ee_read_registration',
28
-            'espresso_registrations_registration_checkins',
29
-            $item->ID()
30
-        )
31
-            && EE_Registry::instance()->CAP->current_user_can(
32
-                'ee_read_checkins',
33
-                'espresso_registrations_registration_checkins'
34
-            )
35
-            ? '<a href="' . $check_in_url . '"'
36
-              . ' title="' . esc_attr__(
37
-                  'The Check-In List allows you to easily toggle check-in status for this event',
38
-                  'event_espresso'
39
-              )
40
-              . '">' .  esc_html__('View Check-ins', 'event_espresso') . '</a>'
41
-            :  esc_html__('View Check-ins', 'event_espresso');
14
+	/**
15
+	 * REG_date
16
+	 */
17
+	function column__REG_date(EE_Registration $item)
18
+	{
19
+		$date_linked = parent::column__REG_date($item);
20
+		$actions = array();
21
+		//Build row actions
22
+		$check_in_url        = EE_Admin_Page::add_query_args_and_nonce(array(
23
+			'action'   => 'event_registrations',
24
+			'event_id' => $item->event_ID(),
25
+		), REG_ADMIN_URL);
26
+		$actions['check_in'] = EE_Registry::instance()->CAP->current_user_can(
27
+			'ee_read_registration',
28
+			'espresso_registrations_registration_checkins',
29
+			$item->ID()
30
+		)
31
+			&& EE_Registry::instance()->CAP->current_user_can(
32
+				'ee_read_checkins',
33
+				'espresso_registrations_registration_checkins'
34
+			)
35
+			? '<a href="' . $check_in_url . '"'
36
+			  . ' title="' . esc_attr__(
37
+				  'The Check-In List allows you to easily toggle check-in status for this event',
38
+				  'event_espresso'
39
+			  )
40
+			  . '">' .  esc_html__('View Check-ins', 'event_espresso') . '</a>'
41
+			:  esc_html__('View Check-ins', 'event_espresso');
42 42
 
43
-        return sprintf('%1$s %2$s', $date_linked, $this->row_actions($actions));
44
-    }
43
+		return sprintf('%1$s %2$s', $date_linked, $this->row_actions($actions));
44
+	}
45 45
 
46 46
 
47
-    /**
48
-     *        column_default
49
-     *
50
-     * @param \EE_Registration $item
51
-     * @return string
52
-     * @throws EE_Error
53
-     */
54
-    public function column_DTT_EVT_start(EE_Registration $item)
55
-    {
56
-        $remove_defaults = array('default_where_conditions' => 'none');
57
-        $ticket          = $item->ticket();
58
-        $datetimes       = $ticket instanceof EE_Ticket ? $ticket->datetimes($remove_defaults) : array();
59
-        $EVT_ID          = $item->event_ID();
60
-        $datetime_string = '';
61
-        foreach ($datetimes as $datetime) {
62
-            if (EE_Registry::instance()->CAP->current_user_can(
63
-                'ee_read_checkin',
64
-                'espresso_registrations_registration_checkins',
65
-                $item->ID()
66
-            )) {
67
-                // open "a" tag and "href"
68
-                $datetime_string .= '<a href="';
69
-                // checkin URL
70
-                $datetime_string .= EE_Admin_Page::add_query_args_and_nonce(
71
-                    array(
72
-                        'action'   => 'event_registrations',
73
-                        'event_id' => $EVT_ID,
74
-                        'DTT_ID'   => $datetime->ID(),
75
-                    ),
76
-                    REG_ADMIN_URL
77
-                );
78
-                // close "href"
79
-                $datetime_string .= '"';
80
-                // open "title" tag
81
-                $datetime_string .= ' title="';
82
-                // link title text
83
-                $datetime_string .= esc_attr__('View Checkins for this Event', 'event_espresso');
84
-                // close "title" tag and end of "a" tag opening
85
-                $datetime_string .= '">';
86
-                // link text
87
-                $datetime_string .= $datetime->get_i18n_datetime('DTT_EVT_start');
88
-                // close "a" tag
89
-                $datetime_string .= '</a>';
90
-            } else {
91
-                $datetime_string .= $datetime->get_i18n_datetime('DTT_EVT_start');
92
-            }
93
-            // add a "View Registrations" link that filters list by event AND datetime
94
-            $datetime_string .= $this->row_actions(
95
-                array(
96
-                    'event_datetime_filter' => '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
97
-                        array('event_id' => $EVT_ID, 'datetime_id' => $datetime->ID()),
98
-                        REG_ADMIN_URL
99
-                    )
100
-                                               . '" title="' . sprintf(
101
-                                                   esc_attr__(
102
-                                                       'Filter this list to only show registrations for this datetime %s',
103
-                                                       'event_espresso'
104
-                                                   ),
105
-                                                   $datetime->name()
106
-                                               ) . '">'
107
-                                               . esc_html__('View Registrations', 'event_espresso')
108
-                                               . '</a>',
109
-                )
110
-            );
111
-        }
112
-        return $datetime_string;
113
-    }
47
+	/**
48
+	 *        column_default
49
+	 *
50
+	 * @param \EE_Registration $item
51
+	 * @return string
52
+	 * @throws EE_Error
53
+	 */
54
+	public function column_DTT_EVT_start(EE_Registration $item)
55
+	{
56
+		$remove_defaults = array('default_where_conditions' => 'none');
57
+		$ticket          = $item->ticket();
58
+		$datetimes       = $ticket instanceof EE_Ticket ? $ticket->datetimes($remove_defaults) : array();
59
+		$EVT_ID          = $item->event_ID();
60
+		$datetime_string = '';
61
+		foreach ($datetimes as $datetime) {
62
+			if (EE_Registry::instance()->CAP->current_user_can(
63
+				'ee_read_checkin',
64
+				'espresso_registrations_registration_checkins',
65
+				$item->ID()
66
+			)) {
67
+				// open "a" tag and "href"
68
+				$datetime_string .= '<a href="';
69
+				// checkin URL
70
+				$datetime_string .= EE_Admin_Page::add_query_args_and_nonce(
71
+					array(
72
+						'action'   => 'event_registrations',
73
+						'event_id' => $EVT_ID,
74
+						'DTT_ID'   => $datetime->ID(),
75
+					),
76
+					REG_ADMIN_URL
77
+				);
78
+				// close "href"
79
+				$datetime_string .= '"';
80
+				// open "title" tag
81
+				$datetime_string .= ' title="';
82
+				// link title text
83
+				$datetime_string .= esc_attr__('View Checkins for this Event', 'event_espresso');
84
+				// close "title" tag and end of "a" tag opening
85
+				$datetime_string .= '">';
86
+				// link text
87
+				$datetime_string .= $datetime->get_i18n_datetime('DTT_EVT_start');
88
+				// close "a" tag
89
+				$datetime_string .= '</a>';
90
+			} else {
91
+				$datetime_string .= $datetime->get_i18n_datetime('DTT_EVT_start');
92
+			}
93
+			// add a "View Registrations" link that filters list by event AND datetime
94
+			$datetime_string .= $this->row_actions(
95
+				array(
96
+					'event_datetime_filter' => '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
97
+						array('event_id' => $EVT_ID, 'datetime_id' => $datetime->ID()),
98
+						REG_ADMIN_URL
99
+					)
100
+											   . '" title="' . sprintf(
101
+												   esc_attr__(
102
+													   'Filter this list to only show registrations for this datetime %s',
103
+													   'event_espresso'
104
+												   ),
105
+												   $datetime->name()
106
+											   ) . '">'
107
+											   . esc_html__('View Registrations', 'event_espresso')
108
+											   . '</a>',
109
+				)
110
+			);
111
+		}
112
+		return $datetime_string;
113
+	}
114 114
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
         $date_linked = parent::column__REG_date($item);
20 20
         $actions = array();
21 21
         //Build row actions
22
-        $check_in_url        = EE_Admin_Page::add_query_args_and_nonce(array(
22
+        $check_in_url = EE_Admin_Page::add_query_args_and_nonce(array(
23 23
             'action'   => 'event_registrations',
24 24
             'event_id' => $item->event_ID(),
25 25
         ), REG_ADMIN_URL);
@@ -32,12 +32,12 @@  discard block
 block discarded – undo
32 32
                 'ee_read_checkins',
33 33
                 'espresso_registrations_registration_checkins'
34 34
             )
35
-            ? '<a href="' . $check_in_url . '"'
36
-              . ' title="' . esc_attr__(
35
+            ? '<a href="'.$check_in_url.'"'
36
+              . ' title="'.esc_attr__(
37 37
                   'The Check-In List allows you to easily toggle check-in status for this event',
38 38
                   'event_espresso'
39 39
               )
40
-              . '">' .  esc_html__('View Check-ins', 'event_espresso') . '</a>'
40
+              . '">'.esc_html__('View Check-ins', 'event_espresso').'</a>'
41 41
             :  esc_html__('View Check-ins', 'event_espresso');
42 42
 
43 43
         return sprintf('%1$s %2$s', $date_linked, $this->row_actions($actions));
@@ -93,17 +93,17 @@  discard block
 block discarded – undo
93 93
             // add a "View Registrations" link that filters list by event AND datetime
94 94
             $datetime_string .= $this->row_actions(
95 95
                 array(
96
-                    'event_datetime_filter' => '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
96
+                    'event_datetime_filter' => '<a href="'.EE_Admin_Page::add_query_args_and_nonce(
97 97
                         array('event_id' => $EVT_ID, 'datetime_id' => $datetime->ID()),
98 98
                         REG_ADMIN_URL
99 99
                     )
100
-                                               . '" title="' . sprintf(
100
+                                               . '" title="'.sprintf(
101 101
                                                    esc_attr__(
102 102
                                                        'Filter this list to only show registrations for this datetime %s',
103 103
                                                        'event_espresso'
104 104
                                                    ),
105 105
                                                    $datetime->name()
106
-                                               ) . '">'
106
+                                               ).'">'
107 107
                                                . esc_html__('View Registrations', 'event_espresso')
108 108
                                                . '</a>',
109 109
                 )
Please login to merge, or discard this patch.