Completed
Branch FET-9222-rest-api-writes (9a0487)
by
unknown
71:42 queued 58:38
created
admin_pages/registrations/Registrations_Admin_Page.core.php 1 patch
Indentation   +3435 added lines, -3435 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
 
5 5
 
@@ -23,2121 +23,2121 @@  discard block
 block discarded – undo
23 23
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registration
28
-     */
29
-    private $_registration;
30
-
31
-    /**
32
-     * @var EE_Event
33
-     */
34
-    private $_reg_event;
35
-
36
-    /**
37
-     * @var EE_Session
38
-     */
39
-    private $_session;
40
-
41
-    private static $_reg_status;
42
-
43
-    /**
44
-     * Form for displaying the custom questions for this registration.
45
-     * This gets used a few times throughout the request so its best to cache it
46
-     *
47
-     * @var EE_Registration_Custom_Questions_Form
48
-     */
49
-    protected $_reg_custom_questions_form = null;
50
-
51
-
52
-    /**
53
-     *        constructor
54
-     *
55
-     * @Constructor
56
-     * @access public
57
-     * @param bool $routing
58
-     * @return Registrations_Admin_Page
59
-     */
60
-    public function __construct($routing = true)
61
-    {
62
-        parent::__construct($routing);
63
-        add_action('wp_loaded', array($this, 'wp_loaded'));
64
-    }
65
-
66
-
67
-    public function wp_loaded()
68
-    {
69
-        // when adding a new registration...
70
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
-            EE_System::do_not_cache();
72
-            if (! isset($this->_req_data['processing_registration'])
73
-                 || absint($this->_req_data['processing_registration']) !== 1
74
-            ) {
75
-                // and it's NOT the attendee information reg step
76
-                // force cookie expiration by setting time to last week
77
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
-                // and update the global
79
-                $_COOKIE['ee_registration_added'] = 0;
80
-            }
81
-        }
82
-    }
83
-
84
-
85
-    protected function _init_page_props()
86
-    {
87
-        $this->page_slug        = REG_PG_SLUG;
88
-        $this->_admin_base_url  = REG_ADMIN_URL;
89
-        $this->_admin_base_path = REG_ADMIN;
90
-        $this->page_label       = esc_html__('Registrations', 'event_espresso');
91
-        $this->_cpt_routes      = array(
92
-            'add_new_attendee' => 'espresso_attendees',
93
-            'edit_attendee'    => 'espresso_attendees',
94
-            'insert_attendee'  => 'espresso_attendees',
95
-            'update_attendee'  => 'espresso_attendees',
96
-        );
97
-        $this->_cpt_model_names = array(
98
-            'add_new_attendee' => 'EEM_Attendee',
99
-            'edit_attendee'    => 'EEM_Attendee',
100
-        );
101
-        $this->_cpt_edit_routes = array(
102
-            'espresso_attendees' => 'edit_attendee',
103
-        );
104
-        $this->_pagenow_map     = array(
105
-            'add_new_attendee' => 'post-new.php',
106
-            'edit_attendee'    => 'post.php',
107
-            'trash'            => 'post.php',
108
-        );
109
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
-        //add filters so that the comment urls don't take users to a confusing 404 page
111
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
-    }
113
-
114
-
115
-    public function clear_comment_link($link, $comment, $args)
116
-    {
117
-        //gotta make sure this only happens on this route
118
-        $post_type = get_post_type($comment->comment_post_ID);
119
-        if ($post_type === 'espresso_attendees') {
120
-            return '#commentsdiv';
121
-        }
122
-        return $link;
123
-    }
124
-
125
-
126
-    protected function _ajax_hooks()
127
-    {
128
-        //todo: all hooks for registrations ajax goes in here
129
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
-    }
131
-
132
-
133
-    protected function _define_page_props()
134
-    {
135
-        $this->_admin_page_title = $this->page_label;
136
-        $this->_labels           = array(
137
-            'buttons'                      => array(
138
-                'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
139
-                'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
140
-                'edit'                => esc_html__('Edit Contact', 'event_espresso'),
141
-                'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
142
-                'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
143
-                'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
144
-                'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
145
-                'contact_list_export' => esc_html__("Export Data", "event_espresso"),
146
-            ),
147
-            'publishbox'                   => array(
148
-                'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
149
-                'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
150
-            ),
151
-            'hide_add_button_on_cpt_route' => array(
152
-                'edit_attendee' => true,
153
-            ),
154
-        );
155
-    }
156
-
157
-
158
-    /**
159
-     *        grab url requests and route them
160
-     *
161
-     * @access private
162
-     * @return void
163
-     */
164
-    public function _set_page_routes()
165
-    {
166
-        $this->_get_registration_status_array();
167
-        $reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
-            ? $this->_req_data['_REG_ID'] : 0;
169
-        $att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
170
-            ? $this->_req_data['ATT_ID'] : 0;
171
-        $att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
172
-            ? $this->_req_data['post']
173
-            : $att_id;
174
-        $this->_page_routes = array(
175
-            'default'                            => array(
176
-                'func'       => '_registrations_overview_list_table',
177
-                'capability' => 'ee_read_registrations',
178
-            ),
179
-            'view_registration'                  => array(
180
-                'func'       => '_registration_details',
181
-                'capability' => 'ee_read_registration',
182
-                'obj_id'     => $reg_id,
183
-            ),
184
-            'edit_registration'                  => array(
185
-                'func'               => '_update_attendee_registration_form',
186
-                'noheader'           => true,
187
-                'headers_sent_route' => 'view_registration',
188
-                'capability'         => 'ee_edit_registration',
189
-                'obj_id'             => $reg_id,
190
-                '_REG_ID'            => $reg_id,
191
-            ),
192
-            'trash_registrations'                => array(
193
-                'func'       => '_trash_or_restore_registrations',
194
-                'args'       => array('trash' => true),
195
-                'noheader'   => true,
196
-                'capability' => 'ee_delete_registrations',
197
-            ),
198
-            'restore_registrations'              => array(
199
-                'func'       => '_trash_or_restore_registrations',
200
-                'args'       => array('trash' => false),
201
-                'noheader'   => true,
202
-                'capability' => 'ee_delete_registrations',
203
-            ),
204
-            'delete_registrations'               => array(
205
-                'func'       => '_delete_registrations',
206
-                'noheader'   => true,
207
-                'capability' => 'ee_delete_registrations',
208
-            ),
209
-            'new_registration'                   => array(
210
-                'func'       => 'new_registration',
211
-                'capability' => 'ee_edit_registrations',
212
-            ),
213
-            'process_reg_step'                   => array(
214
-                'func'       => 'process_reg_step',
215
-                'noheader'   => true,
216
-                'capability' => 'ee_edit_registrations',
217
-            ),
218
-            'redirect_to_txn'                    => array(
219
-                'func'       => 'redirect_to_txn',
220
-                'noheader'   => true,
221
-                'capability' => 'ee_edit_registrations',
222
-            ),
223
-            'change_reg_status'                  => array(
224
-                'func'       => '_change_reg_status',
225
-                'noheader'   => true,
226
-                'capability' => 'ee_edit_registration',
227
-                'obj_id'     => $reg_id,
228
-            ),
229
-            'approve_registration'               => array(
230
-                'func'       => 'approve_registration',
231
-                'noheader'   => true,
232
-                'capability' => 'ee_edit_registration',
233
-                'obj_id'     => $reg_id,
234
-            ),
235
-            'approve_and_notify_registration'    => array(
236
-                'func'       => 'approve_registration',
237
-                'noheader'   => true,
238
-                'args'       => array(true),
239
-                'capability' => 'ee_edit_registration',
240
-                'obj_id'     => $reg_id,
241
-            ),
242
-            'decline_registration'               => array(
243
-                'func'       => 'decline_registration',
244
-                'noheader'   => true,
245
-                'capability' => 'ee_edit_registration',
246
-                'obj_id'     => $reg_id,
247
-            ),
248
-            'decline_and_notify_registration'    => array(
249
-                'func'       => 'decline_registration',
250
-                'noheader'   => true,
251
-                'args'       => array(true),
252
-                'capability' => 'ee_edit_registration',
253
-                'obj_id'     => $reg_id,
254
-            ),
255
-            'pending_registration'               => array(
256
-                'func'       => 'pending_registration',
257
-                'noheader'   => true,
258
-                'capability' => 'ee_edit_registration',
259
-                'obj_id'     => $reg_id,
260
-            ),
261
-            'pending_and_notify_registration'    => array(
262
-                'func'       => 'pending_registration',
263
-                'noheader'   => true,
264
-                'args'       => array(true),
265
-                'capability' => 'ee_edit_registration',
266
-                'obj_id'     => $reg_id,
267
-            ),
268
-            'no_approve_registration'            => array(
269
-                'func'       => 'not_approve_registration',
270
-                'noheader'   => true,
271
-                'capability' => 'ee_edit_registration',
272
-                'obj_id'     => $reg_id,
273
-            ),
274
-            'no_approve_and_notify_registration' => array(
275
-                'func'       => 'not_approve_registration',
276
-                'noheader'   => true,
277
-                'args'       => array(true),
278
-                'capability' => 'ee_edit_registration',
279
-                'obj_id'     => $reg_id,
280
-            ),
281
-            'cancel_registration'                => array(
282
-                'func'       => 'cancel_registration',
283
-                'noheader'   => true,
284
-                'capability' => 'ee_edit_registration',
285
-                'obj_id'     => $reg_id,
286
-            ),
287
-            'cancel_and_notify_registration'     => array(
288
-                'func'       => 'cancel_registration',
289
-                'noheader'   => true,
290
-                'args'       => array(true),
291
-                'capability' => 'ee_edit_registration',
292
-                'obj_id'     => $reg_id,
293
-            ),
294
-            'wait_list_registration' => array(
295
-                'func'       => 'wait_list_registration',
296
-                'noheader'   => true,
297
-                'capability' => 'ee_edit_registration',
298
-                'obj_id'     => $reg_id,
299
-            ),
300
-            'contact_list'                       => array(
301
-                'func'       => '_attendee_contact_list_table',
302
-                'capability' => 'ee_read_contacts',
303
-            ),
304
-            'add_new_attendee'                   => array(
305
-                'func' => '_create_new_cpt_item',
306
-                'args' => array(
307
-                    'new_attendee' => true,
308
-                    'capability'   => 'ee_edit_contacts',
309
-                ),
310
-            ),
311
-            'edit_attendee'                      => array(
312
-                'func'       => '_edit_cpt_item',
313
-                'capability' => 'ee_edit_contacts',
314
-                'obj_id'     => $att_id,
315
-            ),
316
-            'duplicate_attendee'                 => array(
317
-                'func'       => '_duplicate_attendee',
318
-                'noheader'   => true,
319
-                'capability' => 'ee_edit_contacts',
320
-                'obj_id'     => $att_id,
321
-            ),
322
-            'insert_attendee'                    => array(
323
-                'func'       => '_insert_or_update_attendee',
324
-                'args'       => array(
325
-                    'new_attendee' => true,
326
-                ),
327
-                'noheader'   => true,
328
-                'capability' => 'ee_edit_contacts',
329
-            ),
330
-            'update_attendee'                    => array(
331
-                'func'       => '_insert_or_update_attendee',
332
-                'args'       => array(
333
-                    'new_attendee' => false,
334
-                ),
335
-                'noheader'   => true,
336
-                'capability' => 'ee_edit_contacts',
337
-                'obj_id'     => $att_id,
338
-            ),
339
-            'trash_attendees' => array(
340
-                'func' => '_trash_or_restore_attendees',
341
-                'args' => array(
342
-                    'trash' => 'true'
343
-                ),
344
-                'noheader' => true,
345
-                'capability' => 'ee_delete_contacts'
346
-            ),
347
-            'trash_attendee'                    => array(
348
-                'func'       => '_trash_or_restore_attendees',
349
-                'args'       => array(
350
-                    'trash' => true,
351
-                ),
352
-                'noheader'   => true,
353
-                'capability' => 'ee_delete_contacts',
354
-                'obj_id'     => $att_id,
355
-            ),
356
-            'restore_attendees'                  => array(
357
-                'func'       => '_trash_or_restore_attendees',
358
-                'args'       => array(
359
-                    'trash' => false,
360
-                ),
361
-                'noheader'   => true,
362
-                'capability' => 'ee_delete_contacts',
363
-                'obj_id'     => $att_id,
364
-            ),
365
-            'resend_registration'                => array(
366
-                'func'       => '_resend_registration',
367
-                'noheader'   => true,
368
-                'capability' => 'ee_send_message',
369
-            ),
370
-            'registrations_report'               => array(
371
-                'func'       => '_registrations_report',
372
-                'noheader'   => true,
373
-                'capability' => 'ee_read_registrations',
374
-            ),
375
-            'contact_list_export'                => array(
376
-                'func'       => '_contact_list_export',
377
-                'noheader'   => true,
378
-                'capability' => 'export',
379
-            ),
380
-            'contact_list_report'                => array(
381
-                'func'       => '_contact_list_report',
382
-                'noheader'   => true,
383
-                'capability' => 'ee_read_contacts',
384
-            ),
385
-        );
386
-    }
387
-
388
-
389
-    protected function _set_page_config()
390
-    {
391
-        $this->_page_config = array(
392
-            'default'           => array(
393
-                'nav'           => array(
394
-                    'label' => esc_html__('Overview', 'event_espresso'),
395
-                    'order' => 5,
396
-                ),
397
-                'help_tabs'     => array(
398
-                    'registrations_overview_help_tab'                       => array(
399
-                        'title'    => esc_html__('Registrations Overview', 'event_espresso'),
400
-                        'filename' => 'registrations_overview',
401
-                    ),
402
-                    'registrations_overview_table_column_headings_help_tab' => array(
403
-                        'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
404
-                        'filename' => 'registrations_overview_table_column_headings',
405
-                    ),
406
-                    'registrations_overview_filters_help_tab'               => array(
407
-                        'title'    => esc_html__('Registration Filters', 'event_espresso'),
408
-                        'filename' => 'registrations_overview_filters',
409
-                    ),
410
-                    'registrations_overview_views_help_tab'                 => array(
411
-                        'title'    => esc_html__('Registration Views', 'event_espresso'),
412
-                        'filename' => 'registrations_overview_views',
413
-                    ),
414
-                    'registrations_regoverview_other_help_tab'              => array(
415
-                        'title'    => esc_html__('Registrations Other', 'event_espresso'),
416
-                        'filename' => 'registrations_overview_other',
417
-                    ),
418
-                ),
419
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
420
-                'qtips'         => array('Registration_List_Table_Tips'),
421
-                'list_table'    => 'EE_Registrations_List_Table',
422
-                'require_nonce' => false,
423
-            ),
424
-            'view_registration' => array(
425
-                'nav'           => array(
426
-                    'label'      => esc_html__('REG Details', 'event_espresso'),
427
-                    'order'      => 15,
428
-                    'url'        => isset($this->_req_data['_REG_ID'])
429
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
430
-                        : $this->_admin_base_url,
431
-                    'persistent' => false,
432
-                ),
433
-                'help_tabs'     => array(
434
-                    'registrations_details_help_tab'                    => array(
435
-                        'title'    => esc_html__('Registration Details', 'event_espresso'),
436
-                        'filename' => 'registrations_details',
437
-                    ),
438
-                    'registrations_details_table_help_tab'              => array(
439
-                        'title'    => esc_html__('Registration Details Table', 'event_espresso'),
440
-                        'filename' => 'registrations_details_table',
441
-                    ),
442
-                    'registrations_details_form_answers_help_tab'       => array(
443
-                        'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
444
-                        'filename' => 'registrations_details_form_answers',
445
-                    ),
446
-                    'registrations_details_registrant_details_help_tab' => array(
447
-                        'title'    => esc_html__('Contact Details', 'event_espresso'),
448
-                        'filename' => 'registrations_details_registrant_details',
449
-                    ),
450
-                ),
451
-                'help_tour'     => array('Registration_Details_Help_Tour'),
452
-                'metaboxes'     => array_merge(
453
-                    $this->_default_espresso_metaboxes,
454
-                    array('_registration_details_metaboxes')
455
-                ),
456
-                'require_nonce' => false,
457
-            ),
458
-            'new_registration'  => array(
459
-                'nav'           => array(
460
-                    'label'      => esc_html__('Add New Registration', 'event_espresso'),
461
-                    'url'        => '#',
462
-                    'order'      => 15,
463
-                    'persistent' => false,
464
-                ),
465
-                'metaboxes'     => $this->_default_espresso_metaboxes,
466
-                'labels'        => array(
467
-                    'publishbox' => esc_html__('Save Registration', 'event_espresso'),
468
-                ),
469
-                'require_nonce' => false,
470
-            ),
471
-            'add_new_attendee'  => array(
472
-                'nav'           => array(
473
-                    'label'      => esc_html__('Add Contact', 'event_espresso'),
474
-                    'order'      => 15,
475
-                    'persistent' => false,
476
-                ),
477
-                'metaboxes'     => array_merge(
478
-                    $this->_default_espresso_metaboxes,
479
-                    array('_publish_post_box', 'attendee_editor_metaboxes')
480
-                ),
481
-                'require_nonce' => false,
482
-            ),
483
-            'edit_attendee'     => array(
484
-                'nav'           => array(
485
-                    'label'      => esc_html__('Edit Contact', 'event_espresso'),
486
-                    'order'      => 15,
487
-                    'persistent' => false,
488
-                    'url'        => isset($this->_req_data['ATT_ID'])
489
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
490
-                        : $this->_admin_base_url,
491
-                ),
492
-                'metaboxes'     => array('attendee_editor_metaboxes'),
493
-                'require_nonce' => false,
494
-            ),
495
-            'contact_list'      => array(
496
-                'nav'           => array(
497
-                    'label' => esc_html__('Contact List', 'event_espresso'),
498
-                    'order' => 20,
499
-                ),
500
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
501
-                'help_tabs'     => array(
502
-                    'registrations_contact_list_help_tab'                       => array(
503
-                        'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
504
-                        'filename' => 'registrations_contact_list',
505
-                    ),
506
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
507
-                        'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
508
-                        'filename' => 'registrations_contact_list_table_column_headings',
509
-                    ),
510
-                    'registrations_contact_list_views_help_tab'                 => array(
511
-                        'title'    => esc_html__('Contact List Views', 'event_espresso'),
512
-                        'filename' => 'registrations_contact_list_views',
513
-                    ),
514
-                    'registrations_contact_list_other_help_tab'                 => array(
515
-                        'title'    => esc_html__('Contact List Other', 'event_espresso'),
516
-                        'filename' => 'registrations_contact_list_other',
517
-                    ),
518
-                ),
519
-                'help_tour'     => array('Contact_List_Help_Tour'),
520
-                'metaboxes'     => array(),
521
-                'require_nonce' => false,
522
-            ),
523
-            //override default cpt routes
524
-            'create_new'        => '',
525
-            'edit'              => '',
526
-        );
527
-    }
528
-
529
-
530
-    /**
531
-     * The below methods aren't used by this class currently
532
-     */
533
-    protected function _add_screen_options()
534
-    {
535
-    }
536
-
537
-
538
-    protected function _add_feature_pointers()
539
-    {
540
-    }
541
-
542
-
543
-    public function admin_init()
544
-    {
545
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
546
-            'click "Update Registration Questions" to save your changes',
547
-            'event_espresso'
548
-        );
549
-    }
550
-
551
-
552
-    public function admin_notices()
553
-    {
554
-    }
555
-
556
-
557
-    public function admin_footer_scripts()
558
-    {
559
-    }
560
-
561
-
562
-    /**
563
-     *        get list of registration statuses
564
-     *
565
-     * @access private
566
-     * @return void
567
-     */
568
-    private function _get_registration_status_array()
569
-    {
570
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
571
-    }
572
-
573
-
574
-    protected function _add_screen_options_default()
575
-    {
576
-        $this->_per_page_screen_option();
577
-    }
578
-
579
-
580
-    protected function _add_screen_options_contact_list()
581
-    {
582
-        $page_title              = $this->_admin_page_title;
583
-        $this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
584
-        $this->_per_page_screen_option();
585
-        $this->_admin_page_title = $page_title;
586
-    }
587
-
588
-
589
-    public function load_scripts_styles()
590
-    {
591
-        //style
592
-        wp_register_style(
593
-            'espresso_reg',
594
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
595
-            array('ee-admin-css'),
596
-            EVENT_ESPRESSO_VERSION
597
-        );
598
-        wp_enqueue_style('espresso_reg');
599
-        //script
600
-        wp_register_script(
601
-            'espresso_reg',
602
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
603
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
604
-            EVENT_ESPRESSO_VERSION,
605
-            true
606
-        );
607
-        wp_enqueue_script('espresso_reg');
608
-    }
609
-
610
-
611
-    public function load_scripts_styles_edit_attendee()
612
-    {
613
-        //stuff to only show up on our attendee edit details page.
614
-        $attendee_details_translations = array(
615
-            'att_publish_text' => sprintf(
616
-                esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
617
-                $this->_cpt_model_obj->get_datetime('ATT_created')
618
-            ),
619
-        );
620
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
621
-        wp_enqueue_script('jquery-validate');
622
-    }
623
-
624
-
625
-    public function load_scripts_styles_view_registration()
626
-    {
627
-        //styles
628
-        wp_enqueue_style('espresso-ui-theme');
629
-        //scripts
630
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
631
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
632
-    }
633
-
634
-
635
-    public function load_scripts_styles_contact_list()
636
-    {
637
-        wp_deregister_style('espresso_reg');
638
-        wp_register_style(
639
-            'espresso_att',
640
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
641
-            array('ee-admin-css'),
642
-            EVENT_ESPRESSO_VERSION
643
-        );
644
-        wp_enqueue_style('espresso_att');
645
-    }
646
-
647
-
648
-    public function load_scripts_styles_new_registration()
649
-    {
650
-        wp_register_script(
651
-            'ee-spco-for-admin',
652
-            REG_ASSETS_URL . 'spco_for_admin.js',
653
-            array('underscore', 'jquery'),
654
-            EVENT_ESPRESSO_VERSION,
655
-            true
656
-        );
657
-        wp_enqueue_script('ee-spco-for-admin');
658
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
659
-        EE_Form_Section_Proper::wp_enqueue_scripts();
660
-        EED_Ticket_Selector::load_tckt_slctr_assets();
661
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
662
-    }
663
-
664
-
665
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
666
-    {
667
-        add_filter('FHEE_load_EE_messages', '__return_true');
668
-    }
669
-
670
-
671
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
672
-    {
673
-        add_filter('FHEE_load_EE_messages', '__return_true');
674
-    }
675
-
676
-
677
-    protected function _set_list_table_views_default()
678
-    {
679
-        //for notification related bulk actions we need to make sure only active messengers have an option.
680
-        EED_Messages::set_autoloaders();
681
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
682
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
683
-        $active_mts               = $message_resource_manager->list_of_active_message_types();
684
-        //key= bulk_action_slug, value= message type.
685
-        $match_array = array(
686
-            'approve_registration'    => 'registration',
687
-            'decline_registration'    => 'declined_registration',
688
-            'pending_registration'    => 'pending_approval',
689
-            'no_approve_registration' => 'not_approved_registration',
690
-            'cancel_registration'     => 'cancelled_registration',
691
-        );
692
-        $can_send = EE_Registry::instance()->CAP->current_user_can(
693
-            'ee_send_message',
694
-            'batch_send_messages'
695
-        );
696
-        /** setup reg status bulk actions **/
697
-        $def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
698
-        if ($can_send && in_array($match_array['approve_registration'], $active_mts, true)) {
699
-                $def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
700
-                    'event_espresso');
701
-        }
702
-        $def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
703
-        if ($can_send && in_array($match_array['decline_registration'], $active_mts, true)) {
704
-                $def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
705
-                    'event_espresso');
706
-        }
707
-        $def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
708
-        if ($can_send && in_array($match_array['pending_registration'], $active_mts, true)) {
709
-                $def_reg_status_actions['pending_and_notify_registration'] = __(
710
-                    'Set Registrations to Pending Payment and Notify',
711
-                    'event_espresso'
712
-                );
713
-        }
714
-        $def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
715
-        if ($can_send && in_array($match_array['no_approve_registration'], $active_mts, true)) {
716
-                $def_reg_status_actions['no_approve_and_notify_registration'] = __(
717
-                    'Set Registrations to Not Approved and Notify',
718
-                    'event_espresso'
719
-                );
720
-        }
721
-        $def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
722
-        if ($can_send && in_array($match_array['cancel_registration'], $active_mts, true)) {
723
-                $def_reg_status_actions['cancel_and_notify_registration'] = __(
724
-                    'Cancel Registrations and Notify',
725
-                    'event_espresso'
726
-                );
727
-        }
728
-        $def_reg_status_actions = apply_filters(
729
-            'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
730
-            $def_reg_status_actions,
731
-            $active_mts
732
-        );
733
-
734
-        $this->_views = array(
735
-            'all'   => array(
736
-                'slug'        => 'all',
737
-                'label'       => esc_html__('View All Registrations', 'event_espresso'),
738
-                'count'       => 0,
739
-                'bulk_action' => array_merge($def_reg_status_actions, array(
740
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
741
-                )),
742
-            ),
743
-            'month' => array(
744
-                'slug'        => 'month',
745
-                'label'       => esc_html__('This Month', 'event_espresso'),
746
-                'count'       => 0,
747
-                'bulk_action' => array_merge($def_reg_status_actions, array(
748
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
749
-                )),
750
-            ),
751
-            'today' => array(
752
-                'slug'        => 'today',
753
-                'label'       => sprintf(
754
-                    esc_html__('Today - %s', 'event_espresso'),
755
-                    date('M d, Y', current_time('timestamp'))
756
-                ),
757
-                'count'       => 0,
758
-                'bulk_action' => array_merge($def_reg_status_actions, array(
759
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
760
-                )),
761
-            ),
762
-        );
763
-        if (EE_Registry::instance()->CAP->current_user_can(
764
-            'ee_delete_registrations',
765
-            'espresso_registrations_delete_registration'
766
-        )) {
767
-            $this->_views['incomplete'] = array(
768
-                'slug'        => 'incomplete',
769
-                'label'       => esc_html__('Incomplete', 'event_espresso'),
770
-                'count'       => 0,
771
-                'bulk_action' => array(
772
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
773
-                ),
774
-            );
775
-            $this->_views['trash']      = array(
776
-                'slug'        => 'trash',
777
-                'label'       => esc_html__('Trash', 'event_espresso'),
778
-                'count'       => 0,
779
-                'bulk_action' => array(
780
-                    'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
781
-                    'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
782
-                ),
783
-            );
784
-        }
785
-    }
786
-
787
-
788
-    protected function _set_list_table_views_contact_list()
789
-    {
790
-        $this->_views = array(
791
-            'in_use' => array(
792
-                'slug'        => 'in_use',
793
-                'label'       => esc_html__('In Use', 'event_espresso'),
794
-                'count'       => 0,
795
-                'bulk_action' => array(
796
-                    'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
797
-                ),
798
-            ),
799
-        );
800
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
801
-            'espresso_registrations_trash_attendees')
802
-        ) {
803
-            $this->_views['trash'] = array(
804
-                'slug'        => 'trash',
805
-                'label'       => esc_html__('Trash', 'event_espresso'),
806
-                'count'       => 0,
807
-                'bulk_action' => array(
808
-                    'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
809
-                ),
810
-            );
811
-        }
812
-    }
813
-
814
-
815
-    protected function _registration_legend_items()
816
-    {
817
-        $fc_items = array(
818
-            'star-icon'        => array(
819
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
820
-                'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
821
-            ),
822
-            'view_details'     => array(
823
-                'class' => 'dashicons dashicons-clipboard',
824
-                'desc'  => esc_html__('View Registration Details', 'event_espresso'),
825
-            ),
826
-            'edit_attendee'    => array(
827
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
828
-                'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
829
-            ),
830
-            'view_transaction' => array(
831
-                'class' => 'dashicons dashicons-cart',
832
-                'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
833
-            ),
834
-            'view_invoice'     => array(
835
-                'class' => 'dashicons dashicons-media-spreadsheet',
836
-                'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
837
-            ),
838
-        );
839
-        if (EE_Registry::instance()->CAP->current_user_can(
840
-            'ee_send_message',
841
-            'espresso_registrations_resend_registration'
842
-        )) {
843
-            $fc_items['resend_registration'] = array(
844
-                'class' => 'dashicons dashicons-email-alt',
845
-                'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
846
-            );
847
-        } else {
848
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
849
-        }
850
-        if (EE_Registry::instance()->CAP->current_user_can(
851
-            'ee_read_global_messages',
852
-            'view_filtered_messages'
853
-        )) {
854
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
855
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
856
-                $fc_items['view_related_messages'] = array(
857
-                    'class' => $related_for_icon['css_class'],
858
-                    'desc'  => $related_for_icon['label'],
859
-                );
860
-            }
861
-        }
862
-        $sc_items = array(
863
-            'approved_status'   => array(
864
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
865
-                'desc'  => EEH_Template::pretty_status(
866
-                    EEM_Registration::status_id_approved,
867
-                    false,
868
-                    'sentence'
869
-                ),
870
-            ),
871
-            'pending_status'    => array(
872
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
873
-                'desc'  => EEH_Template::pretty_status(
874
-                    EEM_Registration::status_id_pending_payment,
875
-                    false,
876
-                    'sentence'
877
-                ),
878
-            ),
879
-            'wait_list'         => array(
880
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
881
-                'desc'  => EEH_Template::pretty_status(
882
-                    EEM_Registration::status_id_wait_list,
883
-                    false,
884
-                    'sentence'
885
-                ),
886
-            ),
887
-            'incomplete_status' => array(
888
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
889
-                'desc'  => EEH_Template::pretty_status(
890
-                    EEM_Registration::status_id_incomplete,
891
-                    false,
892
-                    'sentence'
893
-                ),
894
-            ),
895
-            'not_approved'      => array(
896
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
897
-                'desc'  => EEH_Template::pretty_status(
898
-                    EEM_Registration::status_id_not_approved,
899
-                    false,
900
-                    'sentence'
901
-                ),
902
-            ),
903
-            'declined_status'   => array(
904
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
905
-                'desc'  => EEH_Template::pretty_status(
906
-                    EEM_Registration::status_id_declined,
907
-                    false,
908
-                    'sentence'
909
-                ),
910
-            ),
911
-            'cancelled_status'  => array(
912
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
913
-                'desc'  => EEH_Template::pretty_status(
914
-                    EEM_Registration::status_id_cancelled,
915
-                    false,
916
-                    'sentence'
917
-                ),
918
-            ),
919
-        );
920
-        return array_merge($fc_items, $sc_items);
921
-    }
922
-
923
-
924
-
925
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
926
-    /**
927
-     * @throws \EE_Error
928
-     */
929
-    protected function _registrations_overview_list_table()
930
-    {
931
-        $this->_template_args['admin_page_header'] = '';
932
-        $EVT_ID                                    = ! empty($this->_req_data['event_id'])
933
-            ? absint($this->_req_data['event_id'])
934
-            : 0;
935
-        if ($EVT_ID) {
936
-            if (EE_Registry::instance()->CAP->current_user_can(
937
-                'ee_edit_registrations',
938
-                'espresso_registrations_new_registration',
939
-                $EVT_ID
940
-            )) {
941
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
942
-                    'new_registration',
943
-                    'add-registrant',
944
-                    array('event_id' => $EVT_ID),
945
-                    'add-new-h2'
946
-                );
947
-            }
948
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
949
-            if ($event instanceof EE_Event) {
950
-                $this->_template_args['admin_page_header'] = sprintf(
951
-                    esc_html__(
952
-                        '%s Viewing registrations for the event: %s%s',
953
-                        'event_espresso'
954
-                    ),
955
-                    '<h3 style="line-height:1.5em;">',
956
-                    '<br /><a href="'
957
-                        . EE_Admin_Page::add_query_args_and_nonce(
958
-                            array(
959
-                                'action' => 'edit',
960
-                                'post'   => $event->ID(),
961
-                            ),
962
-                            EVENTS_ADMIN_URL
963
-                        )
964
-                        . '">&nbsp;'
965
-                        . $event->get('EVT_name')
966
-                        . '&nbsp;</a>&nbsp;',
967
-                    '</h3>'
968
-                );
969
-            }
970
-            $DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
971
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
972
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
973
-                $this->_template_args['admin_page_header'] = substr(
974
-                    $this->_template_args['admin_page_header'],
975
-                    0,
976
-                    -5
977
-                );
978
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
979
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
980
-                $this->_template_args['admin_page_header'] .= $datetime->name();
981
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
982
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
983
-            }
984
-        }
985
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
986
-        $this->display_admin_list_table_page_with_no_sidebar();
987
-    }
988
-
989
-
990
-    /**
991
-     * This sets the _registration property for the registration details screen
992
-     *
993
-     * @access private
994
-     * @return bool
995
-     */
996
-    private function _set_registration_object()
997
-    {
998
-        //get out if we've already set the object
999
-        if (is_object($this->_registration)) {
1000
-            return true;
1001
-        }
1002
-        $REG    = EEM_Registration::instance();
1003
-        $REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1004
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1005
-            return true;
1006
-        } else {
1007
-            $error_msg = sprintf(
1008
-                esc_html__(
1009
-                    'An error occurred and the details for Registration ID #%s could not be retrieved.',
1010
-                    'event_espresso'
1011
-                ),
1012
-                $REG_ID
1013
-            );
1014
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1015
-            $this->_registration = null;
1016
-            return false;
1017
-        }
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Used to retrieve registrations for the list table.
1023
-     *
1024
-     * @param int  $per_page
1025
-     * @param bool $count
1026
-     * @param bool $this_month
1027
-     * @param bool $today
1028
-     * @return EE_Registration[]|int
1029
-     * @throws EE_Error
1030
-     */
1031
-    public function get_registrations(
1032
-        $per_page = 10,
1033
-        $count = false,
1034
-        $this_month = false,
1035
-        $today = false
1036
-    ) {
1037
-        if ($this_month) {
1038
-            $this->_req_data['status'] = 'month';
1039
-        }
1040
-        if ($today) {
1041
-            $this->_req_data['status'] = 'today';
1042
-        }
1043
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1044
-        /**
1045
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1046
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1047
-         * @see EEM_Base::get_all()
1048
-         */
1049
-        $query_params['group_by'] = '';
1050
-
1051
-        return $count
1052
-            ? EEM_Registration::instance()->count($query_params)
1053
-            /** @type EE_Registration[] */
1054
-            : EEM_Registration::instance()->get_all($query_params);
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
1061
-     * Note: this listens to values on the request for some of the query parameters.
1062
-     *
1063
-     * @param array $request
1064
-     * @param int    $per_page
1065
-     * @param bool   $count
1066
-     * @return array
1067
-     */
1068
-    protected function _get_registration_query_parameters(
1069
-        $request = array(),
1070
-        $per_page = 10,
1071
-        $count = false
1072
-    ) {
1073
-
1074
-        $query_params = array(
1075
-            0                          => $this->_get_where_conditions_for_registrations_query(
1076
-                $request
1077
-            ),
1078
-            'caps'                     => EEM_Registration::caps_read_admin,
1079
-            'default_where_conditions' => 'this_model_only',
1080
-        );
1081
-        if (! $count) {
1082
-            $query_params = array_merge(
1083
-                $query_params,
1084
-                $this->_get_orderby_for_registrations_query(),
1085
-                $this->_get_limit($per_page)
1086
-            );
1087
-        }
1088
-
1089
-        return $query_params;
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
1095
-     *
1096
-     * @param array $request usually the same as $this->_req_data but not necessarily
1097
-     * @return array
1098
-     */
1099
-    protected function _add_event_id_to_where_conditions(array $request)
1100
-    {
1101
-        $where = array();
1102
-        if (! empty($request['event_id'])) {
1103
-            $where['EVT_ID'] = absint($request['event_id']);
1104
-        }
1105
-        return $where;
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
1111
-     *
1112
-     * @param array $request usually the same as $this->_req_data but not necessarily
1113
-     * @return array
1114
-     */
1115
-    protected function _add_category_id_to_where_conditions(array $request)
1116
-    {
1117
-        $where = array();
1118
-        if (! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
1119
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1120
-        }
1121
-        return $where;
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1127
-     *
1128
-     * @param array $request usually the same as $this->_req_data but not necessarily
1129
-     * @return array
1130
-     */
1131
-    protected function _add_datetime_id_to_where_conditions(array $request)
1132
-    {
1133
-        $where = array();
1134
-        if (! empty($request['datetime_id'])) {
1135
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1136
-        }
1137
-        if (! empty($request['DTT_ID'])) {
1138
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1139
-        }
1140
-        return $where;
1141
-    }
1142
-
1143
-
1144
-    /**
1145
-     * Adds the correct registration status to the where conditions for the registrations query.
1146
-     *
1147
-     * @param array $request usually the same as $this->_req_data but not necessarily
1148
-     * @return array
1149
-     */
1150
-    protected function _add_registration_status_to_where_conditions(array $request)
1151
-    {
1152
-        $where = array();
1153
-        $view = EEH_Array::is_set($request, 'status', '');
1154
-        $registration_status = ! empty($request['_reg_status'])
1155
-            ? sanitize_text_field($request['_reg_status'])
1156
-            : '';
1157
-
1158
-        /*
26
+	/**
27
+	 * @var EE_Registration
28
+	 */
29
+	private $_registration;
30
+
31
+	/**
32
+	 * @var EE_Event
33
+	 */
34
+	private $_reg_event;
35
+
36
+	/**
37
+	 * @var EE_Session
38
+	 */
39
+	private $_session;
40
+
41
+	private static $_reg_status;
42
+
43
+	/**
44
+	 * Form for displaying the custom questions for this registration.
45
+	 * This gets used a few times throughout the request so its best to cache it
46
+	 *
47
+	 * @var EE_Registration_Custom_Questions_Form
48
+	 */
49
+	protected $_reg_custom_questions_form = null;
50
+
51
+
52
+	/**
53
+	 *        constructor
54
+	 *
55
+	 * @Constructor
56
+	 * @access public
57
+	 * @param bool $routing
58
+	 * @return Registrations_Admin_Page
59
+	 */
60
+	public function __construct($routing = true)
61
+	{
62
+		parent::__construct($routing);
63
+		add_action('wp_loaded', array($this, 'wp_loaded'));
64
+	}
65
+
66
+
67
+	public function wp_loaded()
68
+	{
69
+		// when adding a new registration...
70
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
+			EE_System::do_not_cache();
72
+			if (! isset($this->_req_data['processing_registration'])
73
+				 || absint($this->_req_data['processing_registration']) !== 1
74
+			) {
75
+				// and it's NOT the attendee information reg step
76
+				// force cookie expiration by setting time to last week
77
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
+				// and update the global
79
+				$_COOKIE['ee_registration_added'] = 0;
80
+			}
81
+		}
82
+	}
83
+
84
+
85
+	protected function _init_page_props()
86
+	{
87
+		$this->page_slug        = REG_PG_SLUG;
88
+		$this->_admin_base_url  = REG_ADMIN_URL;
89
+		$this->_admin_base_path = REG_ADMIN;
90
+		$this->page_label       = esc_html__('Registrations', 'event_espresso');
91
+		$this->_cpt_routes      = array(
92
+			'add_new_attendee' => 'espresso_attendees',
93
+			'edit_attendee'    => 'espresso_attendees',
94
+			'insert_attendee'  => 'espresso_attendees',
95
+			'update_attendee'  => 'espresso_attendees',
96
+		);
97
+		$this->_cpt_model_names = array(
98
+			'add_new_attendee' => 'EEM_Attendee',
99
+			'edit_attendee'    => 'EEM_Attendee',
100
+		);
101
+		$this->_cpt_edit_routes = array(
102
+			'espresso_attendees' => 'edit_attendee',
103
+		);
104
+		$this->_pagenow_map     = array(
105
+			'add_new_attendee' => 'post-new.php',
106
+			'edit_attendee'    => 'post.php',
107
+			'trash'            => 'post.php',
108
+		);
109
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
+		//add filters so that the comment urls don't take users to a confusing 404 page
111
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
+	}
113
+
114
+
115
+	public function clear_comment_link($link, $comment, $args)
116
+	{
117
+		//gotta make sure this only happens on this route
118
+		$post_type = get_post_type($comment->comment_post_ID);
119
+		if ($post_type === 'espresso_attendees') {
120
+			return '#commentsdiv';
121
+		}
122
+		return $link;
123
+	}
124
+
125
+
126
+	protected function _ajax_hooks()
127
+	{
128
+		//todo: all hooks for registrations ajax goes in here
129
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
+	}
131
+
132
+
133
+	protected function _define_page_props()
134
+	{
135
+		$this->_admin_page_title = $this->page_label;
136
+		$this->_labels           = array(
137
+			'buttons'                      => array(
138
+				'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
139
+				'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
140
+				'edit'                => esc_html__('Edit Contact', 'event_espresso'),
141
+				'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
142
+				'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
143
+				'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
144
+				'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
145
+				'contact_list_export' => esc_html__("Export Data", "event_espresso"),
146
+			),
147
+			'publishbox'                   => array(
148
+				'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
149
+				'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
150
+			),
151
+			'hide_add_button_on_cpt_route' => array(
152
+				'edit_attendee' => true,
153
+			),
154
+		);
155
+	}
156
+
157
+
158
+	/**
159
+	 *        grab url requests and route them
160
+	 *
161
+	 * @access private
162
+	 * @return void
163
+	 */
164
+	public function _set_page_routes()
165
+	{
166
+		$this->_get_registration_status_array();
167
+		$reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
+			? $this->_req_data['_REG_ID'] : 0;
169
+		$att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
170
+			? $this->_req_data['ATT_ID'] : 0;
171
+		$att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
172
+			? $this->_req_data['post']
173
+			: $att_id;
174
+		$this->_page_routes = array(
175
+			'default'                            => array(
176
+				'func'       => '_registrations_overview_list_table',
177
+				'capability' => 'ee_read_registrations',
178
+			),
179
+			'view_registration'                  => array(
180
+				'func'       => '_registration_details',
181
+				'capability' => 'ee_read_registration',
182
+				'obj_id'     => $reg_id,
183
+			),
184
+			'edit_registration'                  => array(
185
+				'func'               => '_update_attendee_registration_form',
186
+				'noheader'           => true,
187
+				'headers_sent_route' => 'view_registration',
188
+				'capability'         => 'ee_edit_registration',
189
+				'obj_id'             => $reg_id,
190
+				'_REG_ID'            => $reg_id,
191
+			),
192
+			'trash_registrations'                => array(
193
+				'func'       => '_trash_or_restore_registrations',
194
+				'args'       => array('trash' => true),
195
+				'noheader'   => true,
196
+				'capability' => 'ee_delete_registrations',
197
+			),
198
+			'restore_registrations'              => array(
199
+				'func'       => '_trash_or_restore_registrations',
200
+				'args'       => array('trash' => false),
201
+				'noheader'   => true,
202
+				'capability' => 'ee_delete_registrations',
203
+			),
204
+			'delete_registrations'               => array(
205
+				'func'       => '_delete_registrations',
206
+				'noheader'   => true,
207
+				'capability' => 'ee_delete_registrations',
208
+			),
209
+			'new_registration'                   => array(
210
+				'func'       => 'new_registration',
211
+				'capability' => 'ee_edit_registrations',
212
+			),
213
+			'process_reg_step'                   => array(
214
+				'func'       => 'process_reg_step',
215
+				'noheader'   => true,
216
+				'capability' => 'ee_edit_registrations',
217
+			),
218
+			'redirect_to_txn'                    => array(
219
+				'func'       => 'redirect_to_txn',
220
+				'noheader'   => true,
221
+				'capability' => 'ee_edit_registrations',
222
+			),
223
+			'change_reg_status'                  => array(
224
+				'func'       => '_change_reg_status',
225
+				'noheader'   => true,
226
+				'capability' => 'ee_edit_registration',
227
+				'obj_id'     => $reg_id,
228
+			),
229
+			'approve_registration'               => array(
230
+				'func'       => 'approve_registration',
231
+				'noheader'   => true,
232
+				'capability' => 'ee_edit_registration',
233
+				'obj_id'     => $reg_id,
234
+			),
235
+			'approve_and_notify_registration'    => array(
236
+				'func'       => 'approve_registration',
237
+				'noheader'   => true,
238
+				'args'       => array(true),
239
+				'capability' => 'ee_edit_registration',
240
+				'obj_id'     => $reg_id,
241
+			),
242
+			'decline_registration'               => array(
243
+				'func'       => 'decline_registration',
244
+				'noheader'   => true,
245
+				'capability' => 'ee_edit_registration',
246
+				'obj_id'     => $reg_id,
247
+			),
248
+			'decline_and_notify_registration'    => array(
249
+				'func'       => 'decline_registration',
250
+				'noheader'   => true,
251
+				'args'       => array(true),
252
+				'capability' => 'ee_edit_registration',
253
+				'obj_id'     => $reg_id,
254
+			),
255
+			'pending_registration'               => array(
256
+				'func'       => 'pending_registration',
257
+				'noheader'   => true,
258
+				'capability' => 'ee_edit_registration',
259
+				'obj_id'     => $reg_id,
260
+			),
261
+			'pending_and_notify_registration'    => array(
262
+				'func'       => 'pending_registration',
263
+				'noheader'   => true,
264
+				'args'       => array(true),
265
+				'capability' => 'ee_edit_registration',
266
+				'obj_id'     => $reg_id,
267
+			),
268
+			'no_approve_registration'            => array(
269
+				'func'       => 'not_approve_registration',
270
+				'noheader'   => true,
271
+				'capability' => 'ee_edit_registration',
272
+				'obj_id'     => $reg_id,
273
+			),
274
+			'no_approve_and_notify_registration' => array(
275
+				'func'       => 'not_approve_registration',
276
+				'noheader'   => true,
277
+				'args'       => array(true),
278
+				'capability' => 'ee_edit_registration',
279
+				'obj_id'     => $reg_id,
280
+			),
281
+			'cancel_registration'                => array(
282
+				'func'       => 'cancel_registration',
283
+				'noheader'   => true,
284
+				'capability' => 'ee_edit_registration',
285
+				'obj_id'     => $reg_id,
286
+			),
287
+			'cancel_and_notify_registration'     => array(
288
+				'func'       => 'cancel_registration',
289
+				'noheader'   => true,
290
+				'args'       => array(true),
291
+				'capability' => 'ee_edit_registration',
292
+				'obj_id'     => $reg_id,
293
+			),
294
+			'wait_list_registration' => array(
295
+				'func'       => 'wait_list_registration',
296
+				'noheader'   => true,
297
+				'capability' => 'ee_edit_registration',
298
+				'obj_id'     => $reg_id,
299
+			),
300
+			'contact_list'                       => array(
301
+				'func'       => '_attendee_contact_list_table',
302
+				'capability' => 'ee_read_contacts',
303
+			),
304
+			'add_new_attendee'                   => array(
305
+				'func' => '_create_new_cpt_item',
306
+				'args' => array(
307
+					'new_attendee' => true,
308
+					'capability'   => 'ee_edit_contacts',
309
+				),
310
+			),
311
+			'edit_attendee'                      => array(
312
+				'func'       => '_edit_cpt_item',
313
+				'capability' => 'ee_edit_contacts',
314
+				'obj_id'     => $att_id,
315
+			),
316
+			'duplicate_attendee'                 => array(
317
+				'func'       => '_duplicate_attendee',
318
+				'noheader'   => true,
319
+				'capability' => 'ee_edit_contacts',
320
+				'obj_id'     => $att_id,
321
+			),
322
+			'insert_attendee'                    => array(
323
+				'func'       => '_insert_or_update_attendee',
324
+				'args'       => array(
325
+					'new_attendee' => true,
326
+				),
327
+				'noheader'   => true,
328
+				'capability' => 'ee_edit_contacts',
329
+			),
330
+			'update_attendee'                    => array(
331
+				'func'       => '_insert_or_update_attendee',
332
+				'args'       => array(
333
+					'new_attendee' => false,
334
+				),
335
+				'noheader'   => true,
336
+				'capability' => 'ee_edit_contacts',
337
+				'obj_id'     => $att_id,
338
+			),
339
+			'trash_attendees' => array(
340
+				'func' => '_trash_or_restore_attendees',
341
+				'args' => array(
342
+					'trash' => 'true'
343
+				),
344
+				'noheader' => true,
345
+				'capability' => 'ee_delete_contacts'
346
+			),
347
+			'trash_attendee'                    => array(
348
+				'func'       => '_trash_or_restore_attendees',
349
+				'args'       => array(
350
+					'trash' => true,
351
+				),
352
+				'noheader'   => true,
353
+				'capability' => 'ee_delete_contacts',
354
+				'obj_id'     => $att_id,
355
+			),
356
+			'restore_attendees'                  => array(
357
+				'func'       => '_trash_or_restore_attendees',
358
+				'args'       => array(
359
+					'trash' => false,
360
+				),
361
+				'noheader'   => true,
362
+				'capability' => 'ee_delete_contacts',
363
+				'obj_id'     => $att_id,
364
+			),
365
+			'resend_registration'                => array(
366
+				'func'       => '_resend_registration',
367
+				'noheader'   => true,
368
+				'capability' => 'ee_send_message',
369
+			),
370
+			'registrations_report'               => array(
371
+				'func'       => '_registrations_report',
372
+				'noheader'   => true,
373
+				'capability' => 'ee_read_registrations',
374
+			),
375
+			'contact_list_export'                => array(
376
+				'func'       => '_contact_list_export',
377
+				'noheader'   => true,
378
+				'capability' => 'export',
379
+			),
380
+			'contact_list_report'                => array(
381
+				'func'       => '_contact_list_report',
382
+				'noheader'   => true,
383
+				'capability' => 'ee_read_contacts',
384
+			),
385
+		);
386
+	}
387
+
388
+
389
+	protected function _set_page_config()
390
+	{
391
+		$this->_page_config = array(
392
+			'default'           => array(
393
+				'nav'           => array(
394
+					'label' => esc_html__('Overview', 'event_espresso'),
395
+					'order' => 5,
396
+				),
397
+				'help_tabs'     => array(
398
+					'registrations_overview_help_tab'                       => array(
399
+						'title'    => esc_html__('Registrations Overview', 'event_espresso'),
400
+						'filename' => 'registrations_overview',
401
+					),
402
+					'registrations_overview_table_column_headings_help_tab' => array(
403
+						'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
404
+						'filename' => 'registrations_overview_table_column_headings',
405
+					),
406
+					'registrations_overview_filters_help_tab'               => array(
407
+						'title'    => esc_html__('Registration Filters', 'event_espresso'),
408
+						'filename' => 'registrations_overview_filters',
409
+					),
410
+					'registrations_overview_views_help_tab'                 => array(
411
+						'title'    => esc_html__('Registration Views', 'event_espresso'),
412
+						'filename' => 'registrations_overview_views',
413
+					),
414
+					'registrations_regoverview_other_help_tab'              => array(
415
+						'title'    => esc_html__('Registrations Other', 'event_espresso'),
416
+						'filename' => 'registrations_overview_other',
417
+					),
418
+				),
419
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
420
+				'qtips'         => array('Registration_List_Table_Tips'),
421
+				'list_table'    => 'EE_Registrations_List_Table',
422
+				'require_nonce' => false,
423
+			),
424
+			'view_registration' => array(
425
+				'nav'           => array(
426
+					'label'      => esc_html__('REG Details', 'event_espresso'),
427
+					'order'      => 15,
428
+					'url'        => isset($this->_req_data['_REG_ID'])
429
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
430
+						: $this->_admin_base_url,
431
+					'persistent' => false,
432
+				),
433
+				'help_tabs'     => array(
434
+					'registrations_details_help_tab'                    => array(
435
+						'title'    => esc_html__('Registration Details', 'event_espresso'),
436
+						'filename' => 'registrations_details',
437
+					),
438
+					'registrations_details_table_help_tab'              => array(
439
+						'title'    => esc_html__('Registration Details Table', 'event_espresso'),
440
+						'filename' => 'registrations_details_table',
441
+					),
442
+					'registrations_details_form_answers_help_tab'       => array(
443
+						'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
444
+						'filename' => 'registrations_details_form_answers',
445
+					),
446
+					'registrations_details_registrant_details_help_tab' => array(
447
+						'title'    => esc_html__('Contact Details', 'event_espresso'),
448
+						'filename' => 'registrations_details_registrant_details',
449
+					),
450
+				),
451
+				'help_tour'     => array('Registration_Details_Help_Tour'),
452
+				'metaboxes'     => array_merge(
453
+					$this->_default_espresso_metaboxes,
454
+					array('_registration_details_metaboxes')
455
+				),
456
+				'require_nonce' => false,
457
+			),
458
+			'new_registration'  => array(
459
+				'nav'           => array(
460
+					'label'      => esc_html__('Add New Registration', 'event_espresso'),
461
+					'url'        => '#',
462
+					'order'      => 15,
463
+					'persistent' => false,
464
+				),
465
+				'metaboxes'     => $this->_default_espresso_metaboxes,
466
+				'labels'        => array(
467
+					'publishbox' => esc_html__('Save Registration', 'event_espresso'),
468
+				),
469
+				'require_nonce' => false,
470
+			),
471
+			'add_new_attendee'  => array(
472
+				'nav'           => array(
473
+					'label'      => esc_html__('Add Contact', 'event_espresso'),
474
+					'order'      => 15,
475
+					'persistent' => false,
476
+				),
477
+				'metaboxes'     => array_merge(
478
+					$this->_default_espresso_metaboxes,
479
+					array('_publish_post_box', 'attendee_editor_metaboxes')
480
+				),
481
+				'require_nonce' => false,
482
+			),
483
+			'edit_attendee'     => array(
484
+				'nav'           => array(
485
+					'label'      => esc_html__('Edit Contact', 'event_espresso'),
486
+					'order'      => 15,
487
+					'persistent' => false,
488
+					'url'        => isset($this->_req_data['ATT_ID'])
489
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
490
+						: $this->_admin_base_url,
491
+				),
492
+				'metaboxes'     => array('attendee_editor_metaboxes'),
493
+				'require_nonce' => false,
494
+			),
495
+			'contact_list'      => array(
496
+				'nav'           => array(
497
+					'label' => esc_html__('Contact List', 'event_espresso'),
498
+					'order' => 20,
499
+				),
500
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
501
+				'help_tabs'     => array(
502
+					'registrations_contact_list_help_tab'                       => array(
503
+						'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
504
+						'filename' => 'registrations_contact_list',
505
+					),
506
+					'registrations_contact-list_table_column_headings_help_tab' => array(
507
+						'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
508
+						'filename' => 'registrations_contact_list_table_column_headings',
509
+					),
510
+					'registrations_contact_list_views_help_tab'                 => array(
511
+						'title'    => esc_html__('Contact List Views', 'event_espresso'),
512
+						'filename' => 'registrations_contact_list_views',
513
+					),
514
+					'registrations_contact_list_other_help_tab'                 => array(
515
+						'title'    => esc_html__('Contact List Other', 'event_espresso'),
516
+						'filename' => 'registrations_contact_list_other',
517
+					),
518
+				),
519
+				'help_tour'     => array('Contact_List_Help_Tour'),
520
+				'metaboxes'     => array(),
521
+				'require_nonce' => false,
522
+			),
523
+			//override default cpt routes
524
+			'create_new'        => '',
525
+			'edit'              => '',
526
+		);
527
+	}
528
+
529
+
530
+	/**
531
+	 * The below methods aren't used by this class currently
532
+	 */
533
+	protected function _add_screen_options()
534
+	{
535
+	}
536
+
537
+
538
+	protected function _add_feature_pointers()
539
+	{
540
+	}
541
+
542
+
543
+	public function admin_init()
544
+	{
545
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
546
+			'click "Update Registration Questions" to save your changes',
547
+			'event_espresso'
548
+		);
549
+	}
550
+
551
+
552
+	public function admin_notices()
553
+	{
554
+	}
555
+
556
+
557
+	public function admin_footer_scripts()
558
+	{
559
+	}
560
+
561
+
562
+	/**
563
+	 *        get list of registration statuses
564
+	 *
565
+	 * @access private
566
+	 * @return void
567
+	 */
568
+	private function _get_registration_status_array()
569
+	{
570
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
571
+	}
572
+
573
+
574
+	protected function _add_screen_options_default()
575
+	{
576
+		$this->_per_page_screen_option();
577
+	}
578
+
579
+
580
+	protected function _add_screen_options_contact_list()
581
+	{
582
+		$page_title              = $this->_admin_page_title;
583
+		$this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
584
+		$this->_per_page_screen_option();
585
+		$this->_admin_page_title = $page_title;
586
+	}
587
+
588
+
589
+	public function load_scripts_styles()
590
+	{
591
+		//style
592
+		wp_register_style(
593
+			'espresso_reg',
594
+			REG_ASSETS_URL . 'espresso_registrations_admin.css',
595
+			array('ee-admin-css'),
596
+			EVENT_ESPRESSO_VERSION
597
+		);
598
+		wp_enqueue_style('espresso_reg');
599
+		//script
600
+		wp_register_script(
601
+			'espresso_reg',
602
+			REG_ASSETS_URL . 'espresso_registrations_admin.js',
603
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
604
+			EVENT_ESPRESSO_VERSION,
605
+			true
606
+		);
607
+		wp_enqueue_script('espresso_reg');
608
+	}
609
+
610
+
611
+	public function load_scripts_styles_edit_attendee()
612
+	{
613
+		//stuff to only show up on our attendee edit details page.
614
+		$attendee_details_translations = array(
615
+			'att_publish_text' => sprintf(
616
+				esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
617
+				$this->_cpt_model_obj->get_datetime('ATT_created')
618
+			),
619
+		);
620
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
621
+		wp_enqueue_script('jquery-validate');
622
+	}
623
+
624
+
625
+	public function load_scripts_styles_view_registration()
626
+	{
627
+		//styles
628
+		wp_enqueue_style('espresso-ui-theme');
629
+		//scripts
630
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
631
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
632
+	}
633
+
634
+
635
+	public function load_scripts_styles_contact_list()
636
+	{
637
+		wp_deregister_style('espresso_reg');
638
+		wp_register_style(
639
+			'espresso_att',
640
+			REG_ASSETS_URL . 'espresso_attendees_admin.css',
641
+			array('ee-admin-css'),
642
+			EVENT_ESPRESSO_VERSION
643
+		);
644
+		wp_enqueue_style('espresso_att');
645
+	}
646
+
647
+
648
+	public function load_scripts_styles_new_registration()
649
+	{
650
+		wp_register_script(
651
+			'ee-spco-for-admin',
652
+			REG_ASSETS_URL . 'spco_for_admin.js',
653
+			array('underscore', 'jquery'),
654
+			EVENT_ESPRESSO_VERSION,
655
+			true
656
+		);
657
+		wp_enqueue_script('ee-spco-for-admin');
658
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
659
+		EE_Form_Section_Proper::wp_enqueue_scripts();
660
+		EED_Ticket_Selector::load_tckt_slctr_assets();
661
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
662
+	}
663
+
664
+
665
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
666
+	{
667
+		add_filter('FHEE_load_EE_messages', '__return_true');
668
+	}
669
+
670
+
671
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
672
+	{
673
+		add_filter('FHEE_load_EE_messages', '__return_true');
674
+	}
675
+
676
+
677
+	protected function _set_list_table_views_default()
678
+	{
679
+		//for notification related bulk actions we need to make sure only active messengers have an option.
680
+		EED_Messages::set_autoloaders();
681
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
682
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
683
+		$active_mts               = $message_resource_manager->list_of_active_message_types();
684
+		//key= bulk_action_slug, value= message type.
685
+		$match_array = array(
686
+			'approve_registration'    => 'registration',
687
+			'decline_registration'    => 'declined_registration',
688
+			'pending_registration'    => 'pending_approval',
689
+			'no_approve_registration' => 'not_approved_registration',
690
+			'cancel_registration'     => 'cancelled_registration',
691
+		);
692
+		$can_send = EE_Registry::instance()->CAP->current_user_can(
693
+			'ee_send_message',
694
+			'batch_send_messages'
695
+		);
696
+		/** setup reg status bulk actions **/
697
+		$def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
698
+		if ($can_send && in_array($match_array['approve_registration'], $active_mts, true)) {
699
+				$def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
700
+					'event_espresso');
701
+		}
702
+		$def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
703
+		if ($can_send && in_array($match_array['decline_registration'], $active_mts, true)) {
704
+				$def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
705
+					'event_espresso');
706
+		}
707
+		$def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
708
+		if ($can_send && in_array($match_array['pending_registration'], $active_mts, true)) {
709
+				$def_reg_status_actions['pending_and_notify_registration'] = __(
710
+					'Set Registrations to Pending Payment and Notify',
711
+					'event_espresso'
712
+				);
713
+		}
714
+		$def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
715
+		if ($can_send && in_array($match_array['no_approve_registration'], $active_mts, true)) {
716
+				$def_reg_status_actions['no_approve_and_notify_registration'] = __(
717
+					'Set Registrations to Not Approved and Notify',
718
+					'event_espresso'
719
+				);
720
+		}
721
+		$def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
722
+		if ($can_send && in_array($match_array['cancel_registration'], $active_mts, true)) {
723
+				$def_reg_status_actions['cancel_and_notify_registration'] = __(
724
+					'Cancel Registrations and Notify',
725
+					'event_espresso'
726
+				);
727
+		}
728
+		$def_reg_status_actions = apply_filters(
729
+			'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
730
+			$def_reg_status_actions,
731
+			$active_mts
732
+		);
733
+
734
+		$this->_views = array(
735
+			'all'   => array(
736
+				'slug'        => 'all',
737
+				'label'       => esc_html__('View All Registrations', 'event_espresso'),
738
+				'count'       => 0,
739
+				'bulk_action' => array_merge($def_reg_status_actions, array(
740
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
741
+				)),
742
+			),
743
+			'month' => array(
744
+				'slug'        => 'month',
745
+				'label'       => esc_html__('This Month', 'event_espresso'),
746
+				'count'       => 0,
747
+				'bulk_action' => array_merge($def_reg_status_actions, array(
748
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
749
+				)),
750
+			),
751
+			'today' => array(
752
+				'slug'        => 'today',
753
+				'label'       => sprintf(
754
+					esc_html__('Today - %s', 'event_espresso'),
755
+					date('M d, Y', current_time('timestamp'))
756
+				),
757
+				'count'       => 0,
758
+				'bulk_action' => array_merge($def_reg_status_actions, array(
759
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
760
+				)),
761
+			),
762
+		);
763
+		if (EE_Registry::instance()->CAP->current_user_can(
764
+			'ee_delete_registrations',
765
+			'espresso_registrations_delete_registration'
766
+		)) {
767
+			$this->_views['incomplete'] = array(
768
+				'slug'        => 'incomplete',
769
+				'label'       => esc_html__('Incomplete', 'event_espresso'),
770
+				'count'       => 0,
771
+				'bulk_action' => array(
772
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
773
+				),
774
+			);
775
+			$this->_views['trash']      = array(
776
+				'slug'        => 'trash',
777
+				'label'       => esc_html__('Trash', 'event_espresso'),
778
+				'count'       => 0,
779
+				'bulk_action' => array(
780
+					'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
781
+					'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
782
+				),
783
+			);
784
+		}
785
+	}
786
+
787
+
788
+	protected function _set_list_table_views_contact_list()
789
+	{
790
+		$this->_views = array(
791
+			'in_use' => array(
792
+				'slug'        => 'in_use',
793
+				'label'       => esc_html__('In Use', 'event_espresso'),
794
+				'count'       => 0,
795
+				'bulk_action' => array(
796
+					'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
797
+				),
798
+			),
799
+		);
800
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
801
+			'espresso_registrations_trash_attendees')
802
+		) {
803
+			$this->_views['trash'] = array(
804
+				'slug'        => 'trash',
805
+				'label'       => esc_html__('Trash', 'event_espresso'),
806
+				'count'       => 0,
807
+				'bulk_action' => array(
808
+					'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
809
+				),
810
+			);
811
+		}
812
+	}
813
+
814
+
815
+	protected function _registration_legend_items()
816
+	{
817
+		$fc_items = array(
818
+			'star-icon'        => array(
819
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
820
+				'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
821
+			),
822
+			'view_details'     => array(
823
+				'class' => 'dashicons dashicons-clipboard',
824
+				'desc'  => esc_html__('View Registration Details', 'event_espresso'),
825
+			),
826
+			'edit_attendee'    => array(
827
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
828
+				'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
829
+			),
830
+			'view_transaction' => array(
831
+				'class' => 'dashicons dashicons-cart',
832
+				'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
833
+			),
834
+			'view_invoice'     => array(
835
+				'class' => 'dashicons dashicons-media-spreadsheet',
836
+				'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
837
+			),
838
+		);
839
+		if (EE_Registry::instance()->CAP->current_user_can(
840
+			'ee_send_message',
841
+			'espresso_registrations_resend_registration'
842
+		)) {
843
+			$fc_items['resend_registration'] = array(
844
+				'class' => 'dashicons dashicons-email-alt',
845
+				'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
846
+			);
847
+		} else {
848
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
849
+		}
850
+		if (EE_Registry::instance()->CAP->current_user_can(
851
+			'ee_read_global_messages',
852
+			'view_filtered_messages'
853
+		)) {
854
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
855
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
856
+				$fc_items['view_related_messages'] = array(
857
+					'class' => $related_for_icon['css_class'],
858
+					'desc'  => $related_for_icon['label'],
859
+				);
860
+			}
861
+		}
862
+		$sc_items = array(
863
+			'approved_status'   => array(
864
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
865
+				'desc'  => EEH_Template::pretty_status(
866
+					EEM_Registration::status_id_approved,
867
+					false,
868
+					'sentence'
869
+				),
870
+			),
871
+			'pending_status'    => array(
872
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
873
+				'desc'  => EEH_Template::pretty_status(
874
+					EEM_Registration::status_id_pending_payment,
875
+					false,
876
+					'sentence'
877
+				),
878
+			),
879
+			'wait_list'         => array(
880
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
881
+				'desc'  => EEH_Template::pretty_status(
882
+					EEM_Registration::status_id_wait_list,
883
+					false,
884
+					'sentence'
885
+				),
886
+			),
887
+			'incomplete_status' => array(
888
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
889
+				'desc'  => EEH_Template::pretty_status(
890
+					EEM_Registration::status_id_incomplete,
891
+					false,
892
+					'sentence'
893
+				),
894
+			),
895
+			'not_approved'      => array(
896
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
897
+				'desc'  => EEH_Template::pretty_status(
898
+					EEM_Registration::status_id_not_approved,
899
+					false,
900
+					'sentence'
901
+				),
902
+			),
903
+			'declined_status'   => array(
904
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
905
+				'desc'  => EEH_Template::pretty_status(
906
+					EEM_Registration::status_id_declined,
907
+					false,
908
+					'sentence'
909
+				),
910
+			),
911
+			'cancelled_status'  => array(
912
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
913
+				'desc'  => EEH_Template::pretty_status(
914
+					EEM_Registration::status_id_cancelled,
915
+					false,
916
+					'sentence'
917
+				),
918
+			),
919
+		);
920
+		return array_merge($fc_items, $sc_items);
921
+	}
922
+
923
+
924
+
925
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
926
+	/**
927
+	 * @throws \EE_Error
928
+	 */
929
+	protected function _registrations_overview_list_table()
930
+	{
931
+		$this->_template_args['admin_page_header'] = '';
932
+		$EVT_ID                                    = ! empty($this->_req_data['event_id'])
933
+			? absint($this->_req_data['event_id'])
934
+			: 0;
935
+		if ($EVT_ID) {
936
+			if (EE_Registry::instance()->CAP->current_user_can(
937
+				'ee_edit_registrations',
938
+				'espresso_registrations_new_registration',
939
+				$EVT_ID
940
+			)) {
941
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
942
+					'new_registration',
943
+					'add-registrant',
944
+					array('event_id' => $EVT_ID),
945
+					'add-new-h2'
946
+				);
947
+			}
948
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
949
+			if ($event instanceof EE_Event) {
950
+				$this->_template_args['admin_page_header'] = sprintf(
951
+					esc_html__(
952
+						'%s Viewing registrations for the event: %s%s',
953
+						'event_espresso'
954
+					),
955
+					'<h3 style="line-height:1.5em;">',
956
+					'<br /><a href="'
957
+						. EE_Admin_Page::add_query_args_and_nonce(
958
+							array(
959
+								'action' => 'edit',
960
+								'post'   => $event->ID(),
961
+							),
962
+							EVENTS_ADMIN_URL
963
+						)
964
+						. '">&nbsp;'
965
+						. $event->get('EVT_name')
966
+						. '&nbsp;</a>&nbsp;',
967
+					'</h3>'
968
+				);
969
+			}
970
+			$DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
971
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
972
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
973
+				$this->_template_args['admin_page_header'] = substr(
974
+					$this->_template_args['admin_page_header'],
975
+					0,
976
+					-5
977
+				);
978
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
979
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
980
+				$this->_template_args['admin_page_header'] .= $datetime->name();
981
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
982
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
983
+			}
984
+		}
985
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
986
+		$this->display_admin_list_table_page_with_no_sidebar();
987
+	}
988
+
989
+
990
+	/**
991
+	 * This sets the _registration property for the registration details screen
992
+	 *
993
+	 * @access private
994
+	 * @return bool
995
+	 */
996
+	private function _set_registration_object()
997
+	{
998
+		//get out if we've already set the object
999
+		if (is_object($this->_registration)) {
1000
+			return true;
1001
+		}
1002
+		$REG    = EEM_Registration::instance();
1003
+		$REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1004
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1005
+			return true;
1006
+		} else {
1007
+			$error_msg = sprintf(
1008
+				esc_html__(
1009
+					'An error occurred and the details for Registration ID #%s could not be retrieved.',
1010
+					'event_espresso'
1011
+				),
1012
+				$REG_ID
1013
+			);
1014
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1015
+			$this->_registration = null;
1016
+			return false;
1017
+		}
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Used to retrieve registrations for the list table.
1023
+	 *
1024
+	 * @param int  $per_page
1025
+	 * @param bool $count
1026
+	 * @param bool $this_month
1027
+	 * @param bool $today
1028
+	 * @return EE_Registration[]|int
1029
+	 * @throws EE_Error
1030
+	 */
1031
+	public function get_registrations(
1032
+		$per_page = 10,
1033
+		$count = false,
1034
+		$this_month = false,
1035
+		$today = false
1036
+	) {
1037
+		if ($this_month) {
1038
+			$this->_req_data['status'] = 'month';
1039
+		}
1040
+		if ($today) {
1041
+			$this->_req_data['status'] = 'today';
1042
+		}
1043
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1044
+		/**
1045
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1046
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1047
+		 * @see EEM_Base::get_all()
1048
+		 */
1049
+		$query_params['group_by'] = '';
1050
+
1051
+		return $count
1052
+			? EEM_Registration::instance()->count($query_params)
1053
+			/** @type EE_Registration[] */
1054
+			: EEM_Registration::instance()->get_all($query_params);
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
1061
+	 * Note: this listens to values on the request for some of the query parameters.
1062
+	 *
1063
+	 * @param array $request
1064
+	 * @param int    $per_page
1065
+	 * @param bool   $count
1066
+	 * @return array
1067
+	 */
1068
+	protected function _get_registration_query_parameters(
1069
+		$request = array(),
1070
+		$per_page = 10,
1071
+		$count = false
1072
+	) {
1073
+
1074
+		$query_params = array(
1075
+			0                          => $this->_get_where_conditions_for_registrations_query(
1076
+				$request
1077
+			),
1078
+			'caps'                     => EEM_Registration::caps_read_admin,
1079
+			'default_where_conditions' => 'this_model_only',
1080
+		);
1081
+		if (! $count) {
1082
+			$query_params = array_merge(
1083
+				$query_params,
1084
+				$this->_get_orderby_for_registrations_query(),
1085
+				$this->_get_limit($per_page)
1086
+			);
1087
+		}
1088
+
1089
+		return $query_params;
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
1095
+	 *
1096
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1097
+	 * @return array
1098
+	 */
1099
+	protected function _add_event_id_to_where_conditions(array $request)
1100
+	{
1101
+		$where = array();
1102
+		if (! empty($request['event_id'])) {
1103
+			$where['EVT_ID'] = absint($request['event_id']);
1104
+		}
1105
+		return $where;
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
1111
+	 *
1112
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1113
+	 * @return array
1114
+	 */
1115
+	protected function _add_category_id_to_where_conditions(array $request)
1116
+	{
1117
+		$where = array();
1118
+		if (! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
1119
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1120
+		}
1121
+		return $where;
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1127
+	 *
1128
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1129
+	 * @return array
1130
+	 */
1131
+	protected function _add_datetime_id_to_where_conditions(array $request)
1132
+	{
1133
+		$where = array();
1134
+		if (! empty($request['datetime_id'])) {
1135
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1136
+		}
1137
+		if (! empty($request['DTT_ID'])) {
1138
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1139
+		}
1140
+		return $where;
1141
+	}
1142
+
1143
+
1144
+	/**
1145
+	 * Adds the correct registration status to the where conditions for the registrations query.
1146
+	 *
1147
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1148
+	 * @return array
1149
+	 */
1150
+	protected function _add_registration_status_to_where_conditions(array $request)
1151
+	{
1152
+		$where = array();
1153
+		$view = EEH_Array::is_set($request, 'status', '');
1154
+		$registration_status = ! empty($request['_reg_status'])
1155
+			? sanitize_text_field($request['_reg_status'])
1156
+			: '';
1157
+
1158
+		/*
1159 1159
          * If filtering by registration status, then we show registrations matching that status.
1160 1160
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1161 1161
          * UNLESS viewing trashed registrations.
1162 1162
          */
1163
-        if (! empty($registration_status)) {
1164
-            $where['STS_ID'] = $registration_status;
1165
-        } else {
1166
-            //make sure we exclude incomplete registrations, but only if not trashed.
1167
-            if ($view === 'trash') {
1168
-                $where['REG_deleted'] = true;
1169
-            } elseif ($view === 'incomplete') {
1170
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1171
-            } else {
1172
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1173
-            }
1174
-        }
1175
-        return $where;
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Adds any provided date restraints to the where conditions for the registrations query.
1181
-     *
1182
-     * @param array $request usually the same as $this->_req_data but not necessarily
1183
-     * @return array
1184
-     * @throws EE_Error
1185
-     */
1186
-    protected function _add_date_to_where_conditions(array $request)
1187
-    {
1188
-        $where = array();
1189
-        $view = EEH_Array::is_set($request, 'status', '');
1190
-        $month_range             = ! empty($request['month_range'])
1191
-            ? sanitize_text_field($request['month_range'])
1192
-            : '';
1193
-        $retrieve_for_today      = $view === 'today';
1194
-        $retrieve_for_this_month = $view === 'month';
1195
-
1196
-        if ($retrieve_for_today) {
1197
-            $now               = date('Y-m-d', current_time('timestamp'));
1198
-            $where['REG_date'] = array(
1199
-                'BETWEEN',
1200
-                array(
1201
-                    EEM_Registration::instance()->convert_datetime_for_query(
1202
-                        'REG_date',
1203
-                        $now . ' 00:00:00',
1204
-                        'Y-m-d H:i:s'
1205
-                    ),
1206
-                    EEM_Registration::instance()->convert_datetime_for_query(
1207
-                        'REG_date',
1208
-                        $now . ' 23:59:59',
1209
-                        'Y-m-d H:i:s'
1210
-                    ),
1211
-                ),
1212
-            );
1213
-        } elseif ($retrieve_for_this_month) {
1214
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1215
-            $days_this_month        = date('t', current_time('timestamp'));
1216
-            $where['REG_date']      = array(
1217
-                'BETWEEN',
1218
-                array(
1219
-                    EEM_Registration::instance()->convert_datetime_for_query(
1220
-                        'REG_date',
1221
-                        $current_year_and_month . '-01 00:00:00',
1222
-                        'Y-m-d H:i:s'
1223
-                    ),
1224
-                    EEM_Registration::instance()->convert_datetime_for_query(
1225
-                        'REG_date',
1226
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1227
-                        'Y-m-d H:i:s'
1228
-                    ),
1229
-                ),
1230
-            );
1231
-        } elseif ($month_range) {
1232
-            $pieces          = explode(' ', $month_range, 3);
1233
-            $month_requested = ! empty($pieces[0])
1234
-                ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1235
-                : '';
1236
-            $year_requested  = ! empty($pieces[1])
1237
-                ? $pieces[1]
1238
-                : '';
1239
-            //if there is not a month or year then we can't go further
1240
-            if ($month_requested && $year_requested) {
1241
-                $days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1242
-                $where['REG_date'] = array(
1243
-                    'BETWEEN',
1244
-                    array(
1245
-                        EEM_Registration::instance()->convert_datetime_for_query(
1246
-                            'REG_date',
1247
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1248
-                            'Y-m-d H:i:s'
1249
-                        ),
1250
-                        EEM_Registration::instance()->convert_datetime_for_query(
1251
-                            'REG_date',
1252
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1253
-                            'Y-m-d H:i:s'
1254
-                        ),
1255
-                    ),
1256
-                );
1257
-            }
1258
-        }
1259
-        return $where;
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Adds any provided search restraints to the where conditions for the registrations query
1265
-     *
1266
-     * @param array $request usually the same as $this->_req_data but not necessarily
1267
-     * @return array
1268
-     */
1269
-    protected function _add_search_to_where_conditions(array $request)
1270
-    {
1271
-        $where = array();
1272
-        if (! empty($request['s'])) {
1273
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1274
-            $where['OR*search_conditions'] = array(
1275
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1276
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1277
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1278
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1279
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1280
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1281
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1282
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1283
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1284
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1285
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1286
-                'REG_final_price'                         => array('LIKE', $search_string),
1287
-                'REG_code'                                => array('LIKE', $search_string),
1288
-                'REG_count'                               => array('LIKE', $search_string),
1289
-                'REG_group_size'                          => array('LIKE', $search_string),
1290
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1291
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1292
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1293
-            );
1294
-        }
1295
-        return $where;
1296
-    }
1297
-
1298
-
1299
-    /**
1300
-     * Sets up the where conditions for the registrations query.
1301
-     *
1302
-     * @param array $request
1303
-     * @return array
1304
-     * @throws EE_Error
1305
-     */
1306
-    protected function _get_where_conditions_for_registrations_query($request)
1307
-    {
1308
-        return apply_filters(
1309
-            'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1310
-            array_merge(
1311
-                $this->_add_event_id_to_where_conditions($request),
1312
-                $this->_add_category_id_to_where_conditions($request),
1313
-                $this->_add_datetime_id_to_where_conditions($request),
1314
-                $this->_add_registration_status_to_where_conditions($request),
1315
-                $this->_add_date_to_where_conditions($request),
1316
-                $this->_add_search_to_where_conditions($request)
1317
-            ),
1318
-            $request
1319
-        );
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Sets up the orderby for the registrations query.
1325
-     *
1326
-     * @return array
1327
-     */
1328
-    protected function _get_orderby_for_registrations_query()
1329
-    {
1330
-        $orderby_field = ! empty($this->_req_data['orderby'])
1331
-            ? sanitize_text_field($this->_req_data['orderby'])
1332
-            : '';
1333
-        switch ($orderby_field) {
1334
-            case '_REG_ID':
1335
-                $orderby_field = 'REG_ID';
1336
-                break;
1337
-            case '_Reg_status':
1338
-                $orderby_field = 'STS_ID';
1339
-                break;
1340
-            case 'ATT_fname':
1341
-                $orderby_field = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1342
-                break;
1343
-            case 'ATT_lname':
1344
-                $orderby_field = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1345
-                break;
1346
-            case 'event_name':
1347
-                $orderby_field = 'Event.EVT_name';
1348
-                break;
1349
-            case 'DTT_EVT_start':
1350
-                $orderby_field = 'Event.Datetime.DTT_EVT_start';
1351
-                break;
1352
-            default: //'REG_date'
1353
-                $orderby_field = 'REG_date';
1354
-        }
1355
-
1356
-        //order
1357
-        $order = ! empty($this->_req_data['order'])
1358
-            ? sanitize_text_field($this->_req_data['order'])
1359
-            : 'DESC';
1360
-
1361
-        //mutate orderby_field
1362
-        $orderby_field = array_combine(
1363
-            (array) $orderby_field,
1364
-            array_fill(0, count($orderby_field), $order)
1365
-        );
1366
-        return array('order_by' => $orderby_field);
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * Sets up the limit for the registrations query.
1372
-     *
1373
-     * @param $per_page
1374
-     * @return array
1375
-     */
1376
-    protected function _get_limit($per_page)
1377
-    {
1378
-        $current_page = ! empty($this->_req_data['paged'])
1379
-            ? absint($this->_req_data['paged'])
1380
-            : 1;
1381
-        $per_page     = ! empty($this->_req_data['perpage'])
1382
-            ? $this->_req_data['perpage']
1383
-            : $per_page;
1384
-
1385
-        //-1 means return all results so get out if that's set.
1386
-        if ((int)$per_page === -1) {
1387
-            return array();
1388
-        }
1389
-        $per_page = absint($per_page);
1390
-        $offset   = ($current_page - 1) * $per_page;
1391
-        return array('limit' => array($offset, $per_page));
1392
-    }
1393
-
1394
-
1395
-    public function get_registration_status_array()
1396
-    {
1397
-        return self::$_reg_status;
1398
-    }
1399
-
1400
-
1401
-
1402
-
1403
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1404
-    /**
1405
-     *        generates HTML for the View Registration Details Admin page
1406
-     *
1407
-     * @access protected
1408
-     * @return void
1409
-     * @throws DomainException
1410
-     * @throws EE_Error
1411
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1412
-     */
1413
-    protected function _registration_details()
1414
-    {
1415
-        $this->_template_args = array();
1416
-        $this->_set_registration_object();
1417
-        if (is_object($this->_registration)) {
1418
-            $transaction                                   = $this->_registration->transaction()
1419
-                ? $this->_registration->transaction()
1420
-                : EE_Transaction::new_instance();
1421
-            $this->_session                                = $transaction->session_data();
1422
-            $event_id                                      = $this->_registration->event_ID();
1423
-            $this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1424
-            $this->_template_args['reg_nmbr']['label']     = esc_html__('Registration Number', 'event_espresso');
1425
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1426
-            $this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1427
-            $this->_template_args['grand_total']           = $transaction->total();
1428
-            $this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1429
-            // link back to overview
1430
-            $this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1431
-            $this->_template_args['registration']                = $this->_registration;
1432
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1433
-                array(
1434
-                    'action'   => 'default',
1435
-                    'event_id' => $event_id,
1436
-                ),
1437
-                REG_ADMIN_URL
1438
-            );
1439
-            $this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(
1440
-                array(
1441
-                    'action' => 'default',
1442
-                    'EVT_ID' => $event_id,
1443
-                    'page'   => 'espresso_transactions',
1444
-                ),
1445
-                admin_url('admin.php')
1446
-            );
1447
-            $this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(
1448
-                array(
1449
-                    'page'   => 'espresso_events',
1450
-                    'action' => 'edit',
1451
-                    'post'   => $event_id,
1452
-                ),
1453
-                admin_url('admin.php')
1454
-            );
1455
-            //next and previous links
1456
-            $next_reg                                      = $this->_registration->next(
1457
-                null,
1458
-                array(),
1459
-                'REG_ID'
1460
-            );
1461
-            $this->_template_args['next_registration']     = $next_reg
1462
-                ? $this->_next_link(
1463
-                    EE_Admin_Page::add_query_args_and_nonce(
1464
-                        array(
1465
-                            'action'  => 'view_registration',
1466
-                            '_REG_ID' => $next_reg['REG_ID'],
1467
-                        ),
1468
-                        REG_ADMIN_URL
1469
-                    ),
1470
-                    'dashicons dashicons-arrow-right ee-icon-size-22'
1471
-                )
1472
-                : '';
1473
-            $previous_reg                                  = $this->_registration->previous(
1474
-                null,
1475
-                array(),
1476
-                'REG_ID'
1477
-            );
1478
-            $this->_template_args['previous_registration'] = $previous_reg
1479
-                ? $this->_previous_link(
1480
-                    EE_Admin_Page::add_query_args_and_nonce(
1481
-                        array(
1482
-                            'action'  => 'view_registration',
1483
-                            '_REG_ID' => $previous_reg['REG_ID'],
1484
-                        ),
1485
-                        REG_ADMIN_URL
1486
-                    ),
1487
-                    'dashicons dashicons-arrow-left ee-icon-size-22'
1488
-                )
1489
-                : '';
1490
-            // grab header
1491
-            $template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1492
-            $this->_template_args['REG_ID']            = $this->_registration->ID();
1493
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1494
-                $template_path,
1495
-                $this->_template_args,
1496
-                true
1497
-            );
1498
-        } else {
1499
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1500
-        }
1501
-        // the details template wrapper
1502
-        $this->display_admin_page_with_sidebar();
1503
-    }
1504
-
1505
-
1506
-    protected function _registration_details_metaboxes()
1507
-    {
1508
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1509
-        $this->_set_registration_object();
1510
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1511
-        add_meta_box('edit-reg-status-mbox', esc_html__('Registration Status', 'event_espresso'),
1512
-            array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1513
-        add_meta_box('edit-reg-details-mbox', esc_html__('Registration Details', 'event_espresso'),
1514
-            array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1515
-        if ($attendee instanceof EE_Attendee
1516
-            && EE_Registry::instance()->CAP->current_user_can(
1517
-                'ee_edit_registration',
1518
-                'edit-reg-questions-mbox'
1519
-            )
1520
-        ) {
1521
-            add_meta_box(
1522
-                'edit-reg-questions-mbox',
1523
-                esc_html__('Registration Form Answers', 'event_espresso'),
1524
-                array($this, '_reg_questions_meta_box'),
1525
-                $this->wp_page_slug,
1526
-                'normal',
1527
-                'high'
1528
-            );
1529
-        }
1530
-        add_meta_box(
1531
-            'edit-reg-registrant-mbox',
1532
-            esc_html__('Contact Details', 'event_espresso'),
1533
-            array($this, '_reg_registrant_side_meta_box'),
1534
-            $this->wp_page_slug,
1535
-            'side',
1536
-            'high'
1537
-        );
1538
-        if ($this->_registration->group_size() > 1) {
1539
-            add_meta_box(
1540
-                'edit-reg-attendees-mbox',
1541
-                esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1542
-                array($this, '_reg_attendees_meta_box'),
1543
-                $this->wp_page_slug,
1544
-                'normal',
1545
-                'high'
1546
-            );
1547
-        }
1548
-    }
1549
-
1550
-
1551
-    /**
1552
-     * set_reg_status_buttons_metabox
1553
-     *
1554
-     * @access protected
1555
-     * @return string
1556
-     * @throws \EE_Error
1557
-     */
1558
-    public function set_reg_status_buttons_metabox()
1559
-    {
1560
-        $this->_set_registration_object();
1561
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1562
-        echo $change_reg_status_form->form_open(
1563
-            self::add_query_args_and_nonce(
1564
-                array(
1565
-                    'action' => 'change_reg_status',
1566
-                ),
1567
-                REG_ADMIN_URL
1568
-            )
1569
-        );
1570
-        echo $change_reg_status_form->get_html();
1571
-        echo $change_reg_status_form->form_close();
1572
-    }
1573
-
1574
-
1575
-
1576
-    /**
1577
-     * @return EE_Form_Section_Proper
1578
-     * @throws EE_Error
1579
-     */
1580
-    protected function _generate_reg_status_change_form()
1581
-    {
1582
-        return new EE_Form_Section_Proper(array(
1583
-            'name'            => 'reg_status_change_form',
1584
-            'html_id'         => 'reg-status-change-form',
1585
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1586
-            'subsections'     => array(
1587
-                'return'             => new EE_Hidden_Input(array(
1588
-                    'name'    => 'return',
1589
-                    'default' => 'view_registration',
1590
-                )),
1591
-                'REG_ID'             => new EE_Hidden_Input(array(
1592
-                    'name'    => 'REG_ID',
1593
-                    'default' => $this->_registration->ID(),
1594
-                )),
1595
-                'current_status'     => new EE_Form_Section_HTML(
1596
-                    EEH_HTML::tr(
1597
-                        EEH_HTML::th(
1598
-                            EEH_HTML::label(
1599
-                                EEH_HTML::strong(esc_html__('Current Registration Status', 'event_espresso')
1600
-                                )
1601
-                            )
1602
-                        )
1603
-                        . EEH_HTML::td(
1604
-                            EEH_HTML::strong(
1605
-                                $this->_registration->pretty_status(),
1606
-                                '',
1607
-                                'status-' . $this->_registration->status_ID(),
1608
-                                'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1609
-                            )
1610
-                        )
1611
-                    )
1612
-                ),
1613
-                'reg_status'         => new EE_Select_Input(
1614
-                    $this->_get_reg_statuses(),
1615
-                    array(
1616
-                        'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1617
-                        'default'         => $this->_registration->status_ID(),
1618
-                    )
1619
-                ),
1620
-                'send_notifications' => new EE_Yes_No_Input(
1621
-                    array(
1622
-                        'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1623
-                        'default'         => false,
1624
-                        'html_help_text'  => esc_html__(
1625
-                            'If set to "Yes", then the related messages will be sent to the registrant.',
1626
-                            'event_espresso'
1627
-                        ),
1628
-                    )
1629
-                ),
1630
-                'submit'             => new EE_Submit_Input(
1631
-                    array(
1632
-                        'html_class'      => 'button-primary',
1633
-                        'html_label_text' => '&nbsp;',
1634
-                        'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1635
-                    )
1636
-                ),
1637
-            ),
1638
-        ));
1639
-    }
1640
-
1641
-
1642
-    /**
1643
-     * Returns an array of all the buttons for the various statuses and switch status actions
1644
-     *
1645
-     * @return array
1646
-     * @throws EE_Error
1647
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1648
-     */
1649
-    protected function _get_reg_statuses()
1650
-    {
1651
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1652
-        unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1653
-        // get current reg status
1654
-        $current_status = $this->_registration->status_ID();
1655
-        // is registration for free event? This will determine whether to display the pending payment option
1656
-        if (
1657
-            $current_status !== EEM_Registration::status_id_pending_payment
1658
-            && $this->_registration->transaction()->is_free()
1659
-        ) {
1660
-            unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1661
-        }
1662
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1663
-    }
1664
-
1665
-
1666
-
1667
-    /**
1668
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1669
-     *
1670
-     * @param bool $status REG status given for changing registrations to.
1671
-     * @param bool $notify Whether to send messages notifications or not.
1672
-     * @return array  (array with reg_id(s) updated and whether update was successful.
1673
-     * @throws \EE_Error
1674
-     */
1675
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1676
-    {
1677
-        if (isset($this->_req_data['reg_status_change_form'])) {
1678
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1679
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1680
-        } else {
1681
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1682
-        }
1683
-        $success = $this->_set_registration_status($REG_IDs, $status);
1684
-        //notify?
1685
-        if ($success
1686
-            && $notify
1687
-            && EE_Registry::instance()->CAP->current_user_can(
1688
-                'ee_send_message',
1689
-                'espresso_registrations_resend_registration'
1690
-            )
1691
-        ) {
1692
-            $this->_process_resend_registration();
1693
-        }
1694
-        return $success;
1695
-    }
1696
-
1697
-
1698
-
1699
-    /**
1700
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1701
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1702
-     *
1703
-     * @param array $REG_IDs
1704
-     * @param bool  $status
1705
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1706
-     * @throws \RuntimeException
1707
-     * @throws \EE_Error
1708
-     *               the array of updated registrations).
1709
-     * @throws EE_Error
1710
-     * @throws RuntimeException
1711
-     */
1712
-    protected function _set_registration_status($REG_IDs = array(), $status = false)
1713
-    {
1714
-        $success = false;
1715
-        // typecast $REG_IDs
1716
-        $REG_IDs = (array)$REG_IDs;
1717
-        if ( ! empty($REG_IDs)) {
1718
-            $success = true;
1719
-            // set default status if none is passed
1720
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1721
-            // sanitize $REG_IDs
1722
-            $REG_IDs = array_filter($REG_IDs, 'absint');
1723
-            //loop through REG_ID's and change status
1724
-            foreach ($REG_IDs as $REG_ID) {
1725
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1726
-                if ($registration instanceof EE_Registration) {
1727
-                    $registration->set_status($status);
1728
-                    $result = $registration->save();
1729
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1730
-                    $success = $result !== false ? $success : false;
1731
-                }
1732
-            }
1733
-        }
1734
-        //reset _req_data['_REG_ID'] for any potential future messages notifications
1735
-        $this->_req_data['_REG_ID'] = $REG_IDs;
1736
-        //return $success and processed registrations
1737
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1738
-    }
1739
-
1740
-
1741
-    /**
1742
-     * Common logic for setting up success message and redirecting to appropriate route
1743
-     *
1744
-     * @param  string $STS_ID status id for the registration changed to
1745
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1746
-     * @return void
1747
-     */
1748
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1749
-    {
1750
-        $result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1751
-            : array('success' => false);
1752
-        $success = isset($result['success']) && $result['success'];
1753
-        //setup success message
1754
-        if ($success) {
1755
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1756
-                $msg = sprintf(esc_html__('Registration status has been set to %s', 'event_espresso'),
1757
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1758
-            } else {
1759
-                $msg = sprintf(esc_html__('Registrations have been set to %s.', 'event_espresso'),
1760
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1761
-            }
1762
-            EE_Error::add_success($msg);
1763
-        } else {
1764
-            EE_Error::add_error(
1765
-                esc_html__(
1766
-                    'Something went wrong, and the status was not changed',
1767
-                    'event_espresso'
1768
-                ), __FILE__, __LINE__, __FUNCTION__
1769
-            );
1770
-        }
1771
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1772
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1773
-        } else {
1774
-            $route = array('action' => 'default');
1775
-        }
1776
-        //unset nonces
1777
-        foreach ($this->_req_data as $ref => $value) {
1778
-            if (strpos($ref, 'nonce') !== false) {
1779
-                unset($this->_req_data[$ref]);
1780
-                continue;
1781
-            }
1782
-            $value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1783
-            $this->_req_data[$ref] = $value;
1784
-        }
1785
-        //merge request vars so that the reloaded list table contains any existing filter query params
1786
-        $route = array_merge($this->_req_data, $route);
1787
-        $this->_redirect_after_action($success, '', '', $route, true);
1788
-    }
1789
-
1790
-
1791
-    /**
1792
-     * incoming reg status change from reg details page.
1793
-     *
1794
-     * @return void
1795
-     */
1796
-    protected function _change_reg_status()
1797
-    {
1798
-        $this->_req_data['return'] = 'view_registration';
1799
-        //set notify based on whether the send notifications toggle is set or not
1800
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1801
-        //$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1802
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1803
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1804
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1805
-            case EEM_Registration::status_id_approved :
1806
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1807
-                $this->approve_registration($notify);
1808
-                break;
1809
-            case EEM_Registration::status_id_pending_payment :
1810
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1811
-                $this->pending_registration($notify);
1812
-                break;
1813
-            case EEM_Registration::status_id_not_approved :
1814
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1815
-                $this->not_approve_registration($notify);
1816
-                break;
1817
-            case EEM_Registration::status_id_declined :
1818
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1819
-                $this->decline_registration($notify);
1820
-                break;
1821
-            case EEM_Registration::status_id_cancelled :
1822
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1823
-                $this->cancel_registration($notify);
1824
-                break;
1825
-            case EEM_Registration::status_id_wait_list :
1826
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1827
-                $this->wait_list_registration($notify);
1828
-                break;
1829
-            case EEM_Registration::status_id_incomplete :
1830
-            default :
1831
-                $result['success'] = false;
1832
-                unset($this->_req_data['return']);
1833
-                $this->_reg_status_change_return('', false);
1834
-                break;
1835
-        }
1836
-    }
1837
-
1838
-
1839
-    /**
1840
-     * approve_registration
1841
-     *
1842
-     * @access protected
1843
-     * @param bool $notify whether or not to notify the registrant about their approval.
1844
-     * @return void
1845
-     */
1846
-    protected function approve_registration($notify = false)
1847
-    {
1848
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1849
-    }
1850
-
1851
-
1852
-    /**
1853
-     *        decline_registration
1854
-     *
1855
-     * @access protected
1856
-     * @param bool $notify whether or not to notify the registrant about their status change.
1857
-     * @return void
1858
-     */
1859
-    protected function decline_registration($notify = false)
1860
-    {
1861
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     *        cancel_registration
1867
-     *
1868
-     * @access protected
1869
-     * @param bool $notify whether or not to notify the registrant about their status change.
1870
-     * @return void
1871
-     */
1872
-    protected function cancel_registration($notify = false)
1873
-    {
1874
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1875
-    }
1876
-
1877
-
1878
-    /**
1879
-     *        not_approve_registration
1880
-     *
1881
-     * @access protected
1882
-     * @param bool $notify whether or not to notify the registrant about their status change.
1883
-     * @return void
1884
-     */
1885
-    protected function not_approve_registration($notify = false)
1886
-    {
1887
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1888
-    }
1889
-
1890
-
1891
-    /**
1892
-     *        decline_registration
1893
-     *
1894
-     * @access protected
1895
-     * @param bool $notify whether or not to notify the registrant about their status change.
1896
-     * @return void
1897
-     */
1898
-    protected function pending_registration($notify = false)
1899
-    {
1900
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1901
-    }
1902
-
1903
-
1904
-    /**
1905
-     * waitlist_registration
1906
-     *
1907
-     * @access protected
1908
-     * @param bool $notify whether or not to notify the registrant about their status change.
1909
-     * @return void
1910
-     */
1911
-    protected function wait_list_registration($notify = false)
1912
-    {
1913
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1914
-    }
1915
-
1916
-
1917
-    /**
1918
-     *        generates HTML for the Registration main meta box
1919
-     *
1920
-     * @access public
1921
-     * @return void
1922
-     * @throws DomainException
1923
-     * @throws EE_Error
1924
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1925
-     */
1926
-    public function _reg_details_meta_box()
1927
-    {
1928
-        EEH_Autoloader::register_line_item_display_autoloaders();
1929
-        EEH_Autoloader::register_line_item_filter_autoloaders();
1930
-        EE_Registry::instance()->load_helper('Line_Item');
1931
-        $transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
1932
-            : EE_Transaction::new_instance();
1933
-        $this->_session = $transaction->session_data();
1934
-        $filters        = new EE_Line_Item_Filter_Collection();
1935
-        //$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1936
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1937
-        $line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
1938
-            $transaction->total_line_item());
1939
-        $filtered_line_item_tree                 = $line_item_filter_processor->process();
1940
-        $line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
1941
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1942
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item(
1943
-            $filtered_line_item_tree,
1944
-            array('EE_Registration' => $this->_registration)
1945
-        );
1946
-        $attendee                                = $this->_registration->attendee();
1947
-        if (EE_Registry::instance()->CAP->current_user_can(
1948
-            'ee_read_transaction',
1949
-            'espresso_transactions_view_transaction'
1950
-        )) {
1951
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
1952
-                EE_Admin_Page::add_query_args_and_nonce(
1953
-                    array(
1954
-                        'action' => 'view_transaction',
1955
-                        'TXN_ID' => $transaction->ID(),
1956
-                    ),
1957
-                    TXN_ADMIN_URL
1958
-                ),
1959
-                esc_html__(' View Transaction', 'event_espresso'),
1960
-                'button secondary-button right',
1961
-                'dashicons dashicons-cart'
1962
-            );
1963
-        } else {
1964
-            $this->_template_args['view_transaction_button'] = '';
1965
-        }
1966
-        if ($attendee instanceof EE_Attendee
1967
-            && EE_Registry::instance()->CAP->current_user_can(
1968
-                'ee_send_message',
1969
-                'espresso_registrations_resend_registration'
1970
-            )
1971
-        ) {
1972
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
1973
-                EE_Admin_Page::add_query_args_and_nonce(
1974
-                    array(
1975
-                        'action'      => 'resend_registration',
1976
-                        '_REG_ID'     => $this->_registration->ID(),
1977
-                        'redirect_to' => 'view_registration',
1978
-                    ),
1979
-                    REG_ADMIN_URL
1980
-                ),
1981
-                esc_html__(' Resend Registration', 'event_espresso'),
1982
-                'button secondary-button right',
1983
-                'dashicons dashicons-email-alt'
1984
-            );
1985
-        } else {
1986
-            $this->_template_args['resend_registration_button'] = '';
1987
-        }
1988
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1989
-        $payment                               = $transaction->get_first_related('Payment');
1990
-        $payment                               = ! $payment instanceof EE_Payment
1991
-            ? EE_Payment::new_instance()
1992
-            : $payment;
1993
-        $payment_method                        = $payment->get_first_related('Payment_Method');
1994
-        $payment_method                        = ! $payment_method instanceof EE_Payment_Method
1995
-            ? EE_Payment_Method::new_instance()
1996
-            : $payment_method;
1997
-        $reg_details                           = array(
1998
-            'payment_method'       => $payment_method->name(),
1999
-            'response_msg'         => $payment->gateway_response(),
2000
-            'registration_id'      => $this->_registration->get('REG_code'),
2001
-            'registration_session' => $this->_registration->session_ID(),
2002
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2003
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2004
-        );
2005
-        if (isset($reg_details['registration_id'])) {
2006
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2007
-            $this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2008
-                'Registration ID',
2009
-                'event_espresso'
2010
-            );
2011
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2012
-        }
2013
-        if (isset($reg_details['payment_method'])) {
2014
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2015
-            $this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2016
-                'Most Recent Payment Method',
2017
-                'event_espresso'
2018
-            );
2019
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2020
-            $this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
2021
-            $this->_template_args['reg_details']['response_msg']['label']   = esc_html__(
2022
-                'Payment method response',
2023
-                'event_espresso'
2024
-            );
2025
-            $this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
2026
-        }
2027
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2028
-        $this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2029
-            'Registration Session',
2030
-            'event_espresso'
2031
-        );
2032
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2033
-        $this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
2034
-        $this->_template_args['reg_details']['ip_address']['label']           = esc_html__(
2035
-            'Registration placed from IP',
2036
-            'event_espresso'
2037
-        );
2038
-        $this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
2039
-        $this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
2040
-        $this->_template_args['reg_details']['user_agent']['label']           = esc_html__('Registrant User Agent',
2041
-            'event_espresso');
2042
-        $this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
2043
-        $this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(
2044
-            array(
2045
-                'action'   => 'default',
2046
-                'event_id' => $this->_registration->event_ID(),
2047
-            ),
2048
-            REG_ADMIN_URL
2049
-        );
2050
-        $this->_template_args['REG_ID']                                       = $this->_registration->ID();
2051
-        $this->_template_args['event_id']                                     = $this->_registration->event_ID();
2052
-        $template_path                                                        =
2053
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2054
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2055
-    }
2056
-
2057
-
2058
-    /**
2059
-     * generates HTML for the Registration Questions meta box.
2060
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2061
-     * otherwise uses new forms system
2062
-     *
2063
-     * @access public
2064
-     * @return void
2065
-     * @throws DomainException
2066
-     * @throws EE_Error
2067
-     */
2068
-    public function _reg_questions_meta_box()
2069
-    {
2070
-        //allow someone to override this method entirely
2071
-        if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
2072
-            $this->_registration)) {
2073
-            $form                                              = $this->_get_reg_custom_questions_form(
2074
-                $this->_registration->ID()
2075
-            );
2076
-            $this->_template_args['att_questions']             = count($form->subforms()) > 0
2077
-                ? $form->get_html_and_js()
2078
-                : '';
2079
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2080
-            $this->_template_args['REG_ID']                    = $this->_registration->ID();
2081
-            $template_path                                     =
2082
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2083
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
2084
-        }
2085
-    }
2086
-
2087
-
2088
-    /**
2089
-     * form_before_question_group
2090
-     *
2091
-     * @deprecated    as of 4.8.32.rc.000
2092
-     * @access        public
2093
-     * @param        string $output
2094
-     * @return        string
2095
-     */
2096
-    public function form_before_question_group($output)
2097
-    {
2098
-        EE_Error::doing_it_wrong(
2099
-            __CLASS__ . '::' . __FUNCTION__,
2100
-            esc_html__(
2101
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2102
-                'event_espresso'
2103
-            ),
2104
-            '4.8.32.rc.000'
2105
-        );
2106
-        return '
1163
+		if (! empty($registration_status)) {
1164
+			$where['STS_ID'] = $registration_status;
1165
+		} else {
1166
+			//make sure we exclude incomplete registrations, but only if not trashed.
1167
+			if ($view === 'trash') {
1168
+				$where['REG_deleted'] = true;
1169
+			} elseif ($view === 'incomplete') {
1170
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1171
+			} else {
1172
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1173
+			}
1174
+		}
1175
+		return $where;
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1181
+	 *
1182
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1183
+	 * @return array
1184
+	 * @throws EE_Error
1185
+	 */
1186
+	protected function _add_date_to_where_conditions(array $request)
1187
+	{
1188
+		$where = array();
1189
+		$view = EEH_Array::is_set($request, 'status', '');
1190
+		$month_range             = ! empty($request['month_range'])
1191
+			? sanitize_text_field($request['month_range'])
1192
+			: '';
1193
+		$retrieve_for_today      = $view === 'today';
1194
+		$retrieve_for_this_month = $view === 'month';
1195
+
1196
+		if ($retrieve_for_today) {
1197
+			$now               = date('Y-m-d', current_time('timestamp'));
1198
+			$where['REG_date'] = array(
1199
+				'BETWEEN',
1200
+				array(
1201
+					EEM_Registration::instance()->convert_datetime_for_query(
1202
+						'REG_date',
1203
+						$now . ' 00:00:00',
1204
+						'Y-m-d H:i:s'
1205
+					),
1206
+					EEM_Registration::instance()->convert_datetime_for_query(
1207
+						'REG_date',
1208
+						$now . ' 23:59:59',
1209
+						'Y-m-d H:i:s'
1210
+					),
1211
+				),
1212
+			);
1213
+		} elseif ($retrieve_for_this_month) {
1214
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1215
+			$days_this_month        = date('t', current_time('timestamp'));
1216
+			$where['REG_date']      = array(
1217
+				'BETWEEN',
1218
+				array(
1219
+					EEM_Registration::instance()->convert_datetime_for_query(
1220
+						'REG_date',
1221
+						$current_year_and_month . '-01 00:00:00',
1222
+						'Y-m-d H:i:s'
1223
+					),
1224
+					EEM_Registration::instance()->convert_datetime_for_query(
1225
+						'REG_date',
1226
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1227
+						'Y-m-d H:i:s'
1228
+					),
1229
+				),
1230
+			);
1231
+		} elseif ($month_range) {
1232
+			$pieces          = explode(' ', $month_range, 3);
1233
+			$month_requested = ! empty($pieces[0])
1234
+				? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1235
+				: '';
1236
+			$year_requested  = ! empty($pieces[1])
1237
+				? $pieces[1]
1238
+				: '';
1239
+			//if there is not a month or year then we can't go further
1240
+			if ($month_requested && $year_requested) {
1241
+				$days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1242
+				$where['REG_date'] = array(
1243
+					'BETWEEN',
1244
+					array(
1245
+						EEM_Registration::instance()->convert_datetime_for_query(
1246
+							'REG_date',
1247
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1248
+							'Y-m-d H:i:s'
1249
+						),
1250
+						EEM_Registration::instance()->convert_datetime_for_query(
1251
+							'REG_date',
1252
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1253
+							'Y-m-d H:i:s'
1254
+						),
1255
+					),
1256
+				);
1257
+			}
1258
+		}
1259
+		return $where;
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Adds any provided search restraints to the where conditions for the registrations query
1265
+	 *
1266
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1267
+	 * @return array
1268
+	 */
1269
+	protected function _add_search_to_where_conditions(array $request)
1270
+	{
1271
+		$where = array();
1272
+		if (! empty($request['s'])) {
1273
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1274
+			$where['OR*search_conditions'] = array(
1275
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1276
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1277
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1278
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1279
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1280
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1281
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1282
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1283
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1284
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1285
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1286
+				'REG_final_price'                         => array('LIKE', $search_string),
1287
+				'REG_code'                                => array('LIKE', $search_string),
1288
+				'REG_count'                               => array('LIKE', $search_string),
1289
+				'REG_group_size'                          => array('LIKE', $search_string),
1290
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1291
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1292
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1293
+			);
1294
+		}
1295
+		return $where;
1296
+	}
1297
+
1298
+
1299
+	/**
1300
+	 * Sets up the where conditions for the registrations query.
1301
+	 *
1302
+	 * @param array $request
1303
+	 * @return array
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	protected function _get_where_conditions_for_registrations_query($request)
1307
+	{
1308
+		return apply_filters(
1309
+			'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1310
+			array_merge(
1311
+				$this->_add_event_id_to_where_conditions($request),
1312
+				$this->_add_category_id_to_where_conditions($request),
1313
+				$this->_add_datetime_id_to_where_conditions($request),
1314
+				$this->_add_registration_status_to_where_conditions($request),
1315
+				$this->_add_date_to_where_conditions($request),
1316
+				$this->_add_search_to_where_conditions($request)
1317
+			),
1318
+			$request
1319
+		);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Sets up the orderby for the registrations query.
1325
+	 *
1326
+	 * @return array
1327
+	 */
1328
+	protected function _get_orderby_for_registrations_query()
1329
+	{
1330
+		$orderby_field = ! empty($this->_req_data['orderby'])
1331
+			? sanitize_text_field($this->_req_data['orderby'])
1332
+			: '';
1333
+		switch ($orderby_field) {
1334
+			case '_REG_ID':
1335
+				$orderby_field = 'REG_ID';
1336
+				break;
1337
+			case '_Reg_status':
1338
+				$orderby_field = 'STS_ID';
1339
+				break;
1340
+			case 'ATT_fname':
1341
+				$orderby_field = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1342
+				break;
1343
+			case 'ATT_lname':
1344
+				$orderby_field = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1345
+				break;
1346
+			case 'event_name':
1347
+				$orderby_field = 'Event.EVT_name';
1348
+				break;
1349
+			case 'DTT_EVT_start':
1350
+				$orderby_field = 'Event.Datetime.DTT_EVT_start';
1351
+				break;
1352
+			default: //'REG_date'
1353
+				$orderby_field = 'REG_date';
1354
+		}
1355
+
1356
+		//order
1357
+		$order = ! empty($this->_req_data['order'])
1358
+			? sanitize_text_field($this->_req_data['order'])
1359
+			: 'DESC';
1360
+
1361
+		//mutate orderby_field
1362
+		$orderby_field = array_combine(
1363
+			(array) $orderby_field,
1364
+			array_fill(0, count($orderby_field), $order)
1365
+		);
1366
+		return array('order_by' => $orderby_field);
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * Sets up the limit for the registrations query.
1372
+	 *
1373
+	 * @param $per_page
1374
+	 * @return array
1375
+	 */
1376
+	protected function _get_limit($per_page)
1377
+	{
1378
+		$current_page = ! empty($this->_req_data['paged'])
1379
+			? absint($this->_req_data['paged'])
1380
+			: 1;
1381
+		$per_page     = ! empty($this->_req_data['perpage'])
1382
+			? $this->_req_data['perpage']
1383
+			: $per_page;
1384
+
1385
+		//-1 means return all results so get out if that's set.
1386
+		if ((int)$per_page === -1) {
1387
+			return array();
1388
+		}
1389
+		$per_page = absint($per_page);
1390
+		$offset   = ($current_page - 1) * $per_page;
1391
+		return array('limit' => array($offset, $per_page));
1392
+	}
1393
+
1394
+
1395
+	public function get_registration_status_array()
1396
+	{
1397
+		return self::$_reg_status;
1398
+	}
1399
+
1400
+
1401
+
1402
+
1403
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1404
+	/**
1405
+	 *        generates HTML for the View Registration Details Admin page
1406
+	 *
1407
+	 * @access protected
1408
+	 * @return void
1409
+	 * @throws DomainException
1410
+	 * @throws EE_Error
1411
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1412
+	 */
1413
+	protected function _registration_details()
1414
+	{
1415
+		$this->_template_args = array();
1416
+		$this->_set_registration_object();
1417
+		if (is_object($this->_registration)) {
1418
+			$transaction                                   = $this->_registration->transaction()
1419
+				? $this->_registration->transaction()
1420
+				: EE_Transaction::new_instance();
1421
+			$this->_session                                = $transaction->session_data();
1422
+			$event_id                                      = $this->_registration->event_ID();
1423
+			$this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1424
+			$this->_template_args['reg_nmbr']['label']     = esc_html__('Registration Number', 'event_espresso');
1425
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1426
+			$this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1427
+			$this->_template_args['grand_total']           = $transaction->total();
1428
+			$this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1429
+			// link back to overview
1430
+			$this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1431
+			$this->_template_args['registration']                = $this->_registration;
1432
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1433
+				array(
1434
+					'action'   => 'default',
1435
+					'event_id' => $event_id,
1436
+				),
1437
+				REG_ADMIN_URL
1438
+			);
1439
+			$this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(
1440
+				array(
1441
+					'action' => 'default',
1442
+					'EVT_ID' => $event_id,
1443
+					'page'   => 'espresso_transactions',
1444
+				),
1445
+				admin_url('admin.php')
1446
+			);
1447
+			$this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(
1448
+				array(
1449
+					'page'   => 'espresso_events',
1450
+					'action' => 'edit',
1451
+					'post'   => $event_id,
1452
+				),
1453
+				admin_url('admin.php')
1454
+			);
1455
+			//next and previous links
1456
+			$next_reg                                      = $this->_registration->next(
1457
+				null,
1458
+				array(),
1459
+				'REG_ID'
1460
+			);
1461
+			$this->_template_args['next_registration']     = $next_reg
1462
+				? $this->_next_link(
1463
+					EE_Admin_Page::add_query_args_and_nonce(
1464
+						array(
1465
+							'action'  => 'view_registration',
1466
+							'_REG_ID' => $next_reg['REG_ID'],
1467
+						),
1468
+						REG_ADMIN_URL
1469
+					),
1470
+					'dashicons dashicons-arrow-right ee-icon-size-22'
1471
+				)
1472
+				: '';
1473
+			$previous_reg                                  = $this->_registration->previous(
1474
+				null,
1475
+				array(),
1476
+				'REG_ID'
1477
+			);
1478
+			$this->_template_args['previous_registration'] = $previous_reg
1479
+				? $this->_previous_link(
1480
+					EE_Admin_Page::add_query_args_and_nonce(
1481
+						array(
1482
+							'action'  => 'view_registration',
1483
+							'_REG_ID' => $previous_reg['REG_ID'],
1484
+						),
1485
+						REG_ADMIN_URL
1486
+					),
1487
+					'dashicons dashicons-arrow-left ee-icon-size-22'
1488
+				)
1489
+				: '';
1490
+			// grab header
1491
+			$template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1492
+			$this->_template_args['REG_ID']            = $this->_registration->ID();
1493
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template(
1494
+				$template_path,
1495
+				$this->_template_args,
1496
+				true
1497
+			);
1498
+		} else {
1499
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1500
+		}
1501
+		// the details template wrapper
1502
+		$this->display_admin_page_with_sidebar();
1503
+	}
1504
+
1505
+
1506
+	protected function _registration_details_metaboxes()
1507
+	{
1508
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1509
+		$this->_set_registration_object();
1510
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1511
+		add_meta_box('edit-reg-status-mbox', esc_html__('Registration Status', 'event_espresso'),
1512
+			array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1513
+		add_meta_box('edit-reg-details-mbox', esc_html__('Registration Details', 'event_espresso'),
1514
+			array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1515
+		if ($attendee instanceof EE_Attendee
1516
+			&& EE_Registry::instance()->CAP->current_user_can(
1517
+				'ee_edit_registration',
1518
+				'edit-reg-questions-mbox'
1519
+			)
1520
+		) {
1521
+			add_meta_box(
1522
+				'edit-reg-questions-mbox',
1523
+				esc_html__('Registration Form Answers', 'event_espresso'),
1524
+				array($this, '_reg_questions_meta_box'),
1525
+				$this->wp_page_slug,
1526
+				'normal',
1527
+				'high'
1528
+			);
1529
+		}
1530
+		add_meta_box(
1531
+			'edit-reg-registrant-mbox',
1532
+			esc_html__('Contact Details', 'event_espresso'),
1533
+			array($this, '_reg_registrant_side_meta_box'),
1534
+			$this->wp_page_slug,
1535
+			'side',
1536
+			'high'
1537
+		);
1538
+		if ($this->_registration->group_size() > 1) {
1539
+			add_meta_box(
1540
+				'edit-reg-attendees-mbox',
1541
+				esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1542
+				array($this, '_reg_attendees_meta_box'),
1543
+				$this->wp_page_slug,
1544
+				'normal',
1545
+				'high'
1546
+			);
1547
+		}
1548
+	}
1549
+
1550
+
1551
+	/**
1552
+	 * set_reg_status_buttons_metabox
1553
+	 *
1554
+	 * @access protected
1555
+	 * @return string
1556
+	 * @throws \EE_Error
1557
+	 */
1558
+	public function set_reg_status_buttons_metabox()
1559
+	{
1560
+		$this->_set_registration_object();
1561
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1562
+		echo $change_reg_status_form->form_open(
1563
+			self::add_query_args_and_nonce(
1564
+				array(
1565
+					'action' => 'change_reg_status',
1566
+				),
1567
+				REG_ADMIN_URL
1568
+			)
1569
+		);
1570
+		echo $change_reg_status_form->get_html();
1571
+		echo $change_reg_status_form->form_close();
1572
+	}
1573
+
1574
+
1575
+
1576
+	/**
1577
+	 * @return EE_Form_Section_Proper
1578
+	 * @throws EE_Error
1579
+	 */
1580
+	protected function _generate_reg_status_change_form()
1581
+	{
1582
+		return new EE_Form_Section_Proper(array(
1583
+			'name'            => 'reg_status_change_form',
1584
+			'html_id'         => 'reg-status-change-form',
1585
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1586
+			'subsections'     => array(
1587
+				'return'             => new EE_Hidden_Input(array(
1588
+					'name'    => 'return',
1589
+					'default' => 'view_registration',
1590
+				)),
1591
+				'REG_ID'             => new EE_Hidden_Input(array(
1592
+					'name'    => 'REG_ID',
1593
+					'default' => $this->_registration->ID(),
1594
+				)),
1595
+				'current_status'     => new EE_Form_Section_HTML(
1596
+					EEH_HTML::tr(
1597
+						EEH_HTML::th(
1598
+							EEH_HTML::label(
1599
+								EEH_HTML::strong(esc_html__('Current Registration Status', 'event_espresso')
1600
+								)
1601
+							)
1602
+						)
1603
+						. EEH_HTML::td(
1604
+							EEH_HTML::strong(
1605
+								$this->_registration->pretty_status(),
1606
+								'',
1607
+								'status-' . $this->_registration->status_ID(),
1608
+								'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1609
+							)
1610
+						)
1611
+					)
1612
+				),
1613
+				'reg_status'         => new EE_Select_Input(
1614
+					$this->_get_reg_statuses(),
1615
+					array(
1616
+						'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1617
+						'default'         => $this->_registration->status_ID(),
1618
+					)
1619
+				),
1620
+				'send_notifications' => new EE_Yes_No_Input(
1621
+					array(
1622
+						'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1623
+						'default'         => false,
1624
+						'html_help_text'  => esc_html__(
1625
+							'If set to "Yes", then the related messages will be sent to the registrant.',
1626
+							'event_espresso'
1627
+						),
1628
+					)
1629
+				),
1630
+				'submit'             => new EE_Submit_Input(
1631
+					array(
1632
+						'html_class'      => 'button-primary',
1633
+						'html_label_text' => '&nbsp;',
1634
+						'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1635
+					)
1636
+				),
1637
+			),
1638
+		));
1639
+	}
1640
+
1641
+
1642
+	/**
1643
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1644
+	 *
1645
+	 * @return array
1646
+	 * @throws EE_Error
1647
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1648
+	 */
1649
+	protected function _get_reg_statuses()
1650
+	{
1651
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1652
+		unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1653
+		// get current reg status
1654
+		$current_status = $this->_registration->status_ID();
1655
+		// is registration for free event? This will determine whether to display the pending payment option
1656
+		if (
1657
+			$current_status !== EEM_Registration::status_id_pending_payment
1658
+			&& $this->_registration->transaction()->is_free()
1659
+		) {
1660
+			unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1661
+		}
1662
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1663
+	}
1664
+
1665
+
1666
+
1667
+	/**
1668
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1669
+	 *
1670
+	 * @param bool $status REG status given for changing registrations to.
1671
+	 * @param bool $notify Whether to send messages notifications or not.
1672
+	 * @return array  (array with reg_id(s) updated and whether update was successful.
1673
+	 * @throws \EE_Error
1674
+	 */
1675
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1676
+	{
1677
+		if (isset($this->_req_data['reg_status_change_form'])) {
1678
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1679
+				? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1680
+		} else {
1681
+			$REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1682
+		}
1683
+		$success = $this->_set_registration_status($REG_IDs, $status);
1684
+		//notify?
1685
+		if ($success
1686
+			&& $notify
1687
+			&& EE_Registry::instance()->CAP->current_user_can(
1688
+				'ee_send_message',
1689
+				'espresso_registrations_resend_registration'
1690
+			)
1691
+		) {
1692
+			$this->_process_resend_registration();
1693
+		}
1694
+		return $success;
1695
+	}
1696
+
1697
+
1698
+
1699
+	/**
1700
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1701
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1702
+	 *
1703
+	 * @param array $REG_IDs
1704
+	 * @param bool  $status
1705
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1706
+	 * @throws \RuntimeException
1707
+	 * @throws \EE_Error
1708
+	 *               the array of updated registrations).
1709
+	 * @throws EE_Error
1710
+	 * @throws RuntimeException
1711
+	 */
1712
+	protected function _set_registration_status($REG_IDs = array(), $status = false)
1713
+	{
1714
+		$success = false;
1715
+		// typecast $REG_IDs
1716
+		$REG_IDs = (array)$REG_IDs;
1717
+		if ( ! empty($REG_IDs)) {
1718
+			$success = true;
1719
+			// set default status if none is passed
1720
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1721
+			// sanitize $REG_IDs
1722
+			$REG_IDs = array_filter($REG_IDs, 'absint');
1723
+			//loop through REG_ID's and change status
1724
+			foreach ($REG_IDs as $REG_ID) {
1725
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1726
+				if ($registration instanceof EE_Registration) {
1727
+					$registration->set_status($status);
1728
+					$result = $registration->save();
1729
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1730
+					$success = $result !== false ? $success : false;
1731
+				}
1732
+			}
1733
+		}
1734
+		//reset _req_data['_REG_ID'] for any potential future messages notifications
1735
+		$this->_req_data['_REG_ID'] = $REG_IDs;
1736
+		//return $success and processed registrations
1737
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1738
+	}
1739
+
1740
+
1741
+	/**
1742
+	 * Common logic for setting up success message and redirecting to appropriate route
1743
+	 *
1744
+	 * @param  string $STS_ID status id for the registration changed to
1745
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1746
+	 * @return void
1747
+	 */
1748
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1749
+	{
1750
+		$result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1751
+			: array('success' => false);
1752
+		$success = isset($result['success']) && $result['success'];
1753
+		//setup success message
1754
+		if ($success) {
1755
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1756
+				$msg = sprintf(esc_html__('Registration status has been set to %s', 'event_espresso'),
1757
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1758
+			} else {
1759
+				$msg = sprintf(esc_html__('Registrations have been set to %s.', 'event_espresso'),
1760
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1761
+			}
1762
+			EE_Error::add_success($msg);
1763
+		} else {
1764
+			EE_Error::add_error(
1765
+				esc_html__(
1766
+					'Something went wrong, and the status was not changed',
1767
+					'event_espresso'
1768
+				), __FILE__, __LINE__, __FUNCTION__
1769
+			);
1770
+		}
1771
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1772
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1773
+		} else {
1774
+			$route = array('action' => 'default');
1775
+		}
1776
+		//unset nonces
1777
+		foreach ($this->_req_data as $ref => $value) {
1778
+			if (strpos($ref, 'nonce') !== false) {
1779
+				unset($this->_req_data[$ref]);
1780
+				continue;
1781
+			}
1782
+			$value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1783
+			$this->_req_data[$ref] = $value;
1784
+		}
1785
+		//merge request vars so that the reloaded list table contains any existing filter query params
1786
+		$route = array_merge($this->_req_data, $route);
1787
+		$this->_redirect_after_action($success, '', '', $route, true);
1788
+	}
1789
+
1790
+
1791
+	/**
1792
+	 * incoming reg status change from reg details page.
1793
+	 *
1794
+	 * @return void
1795
+	 */
1796
+	protected function _change_reg_status()
1797
+	{
1798
+		$this->_req_data['return'] = 'view_registration';
1799
+		//set notify based on whether the send notifications toggle is set or not
1800
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1801
+		//$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1802
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1803
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1804
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1805
+			case EEM_Registration::status_id_approved :
1806
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1807
+				$this->approve_registration($notify);
1808
+				break;
1809
+			case EEM_Registration::status_id_pending_payment :
1810
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1811
+				$this->pending_registration($notify);
1812
+				break;
1813
+			case EEM_Registration::status_id_not_approved :
1814
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1815
+				$this->not_approve_registration($notify);
1816
+				break;
1817
+			case EEM_Registration::status_id_declined :
1818
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1819
+				$this->decline_registration($notify);
1820
+				break;
1821
+			case EEM_Registration::status_id_cancelled :
1822
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1823
+				$this->cancel_registration($notify);
1824
+				break;
1825
+			case EEM_Registration::status_id_wait_list :
1826
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1827
+				$this->wait_list_registration($notify);
1828
+				break;
1829
+			case EEM_Registration::status_id_incomplete :
1830
+			default :
1831
+				$result['success'] = false;
1832
+				unset($this->_req_data['return']);
1833
+				$this->_reg_status_change_return('', false);
1834
+				break;
1835
+		}
1836
+	}
1837
+
1838
+
1839
+	/**
1840
+	 * approve_registration
1841
+	 *
1842
+	 * @access protected
1843
+	 * @param bool $notify whether or not to notify the registrant about their approval.
1844
+	 * @return void
1845
+	 */
1846
+	protected function approve_registration($notify = false)
1847
+	{
1848
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1849
+	}
1850
+
1851
+
1852
+	/**
1853
+	 *        decline_registration
1854
+	 *
1855
+	 * @access protected
1856
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1857
+	 * @return void
1858
+	 */
1859
+	protected function decline_registration($notify = false)
1860
+	{
1861
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 *        cancel_registration
1867
+	 *
1868
+	 * @access protected
1869
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1870
+	 * @return void
1871
+	 */
1872
+	protected function cancel_registration($notify = false)
1873
+	{
1874
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1875
+	}
1876
+
1877
+
1878
+	/**
1879
+	 *        not_approve_registration
1880
+	 *
1881
+	 * @access protected
1882
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1883
+	 * @return void
1884
+	 */
1885
+	protected function not_approve_registration($notify = false)
1886
+	{
1887
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1888
+	}
1889
+
1890
+
1891
+	/**
1892
+	 *        decline_registration
1893
+	 *
1894
+	 * @access protected
1895
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1896
+	 * @return void
1897
+	 */
1898
+	protected function pending_registration($notify = false)
1899
+	{
1900
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1901
+	}
1902
+
1903
+
1904
+	/**
1905
+	 * waitlist_registration
1906
+	 *
1907
+	 * @access protected
1908
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1909
+	 * @return void
1910
+	 */
1911
+	protected function wait_list_registration($notify = false)
1912
+	{
1913
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1914
+	}
1915
+
1916
+
1917
+	/**
1918
+	 *        generates HTML for the Registration main meta box
1919
+	 *
1920
+	 * @access public
1921
+	 * @return void
1922
+	 * @throws DomainException
1923
+	 * @throws EE_Error
1924
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1925
+	 */
1926
+	public function _reg_details_meta_box()
1927
+	{
1928
+		EEH_Autoloader::register_line_item_display_autoloaders();
1929
+		EEH_Autoloader::register_line_item_filter_autoloaders();
1930
+		EE_Registry::instance()->load_helper('Line_Item');
1931
+		$transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
1932
+			: EE_Transaction::new_instance();
1933
+		$this->_session = $transaction->session_data();
1934
+		$filters        = new EE_Line_Item_Filter_Collection();
1935
+		//$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1936
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1937
+		$line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
1938
+			$transaction->total_line_item());
1939
+		$filtered_line_item_tree                 = $line_item_filter_processor->process();
1940
+		$line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
1941
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1942
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item(
1943
+			$filtered_line_item_tree,
1944
+			array('EE_Registration' => $this->_registration)
1945
+		);
1946
+		$attendee                                = $this->_registration->attendee();
1947
+		if (EE_Registry::instance()->CAP->current_user_can(
1948
+			'ee_read_transaction',
1949
+			'espresso_transactions_view_transaction'
1950
+		)) {
1951
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
1952
+				EE_Admin_Page::add_query_args_and_nonce(
1953
+					array(
1954
+						'action' => 'view_transaction',
1955
+						'TXN_ID' => $transaction->ID(),
1956
+					),
1957
+					TXN_ADMIN_URL
1958
+				),
1959
+				esc_html__(' View Transaction', 'event_espresso'),
1960
+				'button secondary-button right',
1961
+				'dashicons dashicons-cart'
1962
+			);
1963
+		} else {
1964
+			$this->_template_args['view_transaction_button'] = '';
1965
+		}
1966
+		if ($attendee instanceof EE_Attendee
1967
+			&& EE_Registry::instance()->CAP->current_user_can(
1968
+				'ee_send_message',
1969
+				'espresso_registrations_resend_registration'
1970
+			)
1971
+		) {
1972
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
1973
+				EE_Admin_Page::add_query_args_and_nonce(
1974
+					array(
1975
+						'action'      => 'resend_registration',
1976
+						'_REG_ID'     => $this->_registration->ID(),
1977
+						'redirect_to' => 'view_registration',
1978
+					),
1979
+					REG_ADMIN_URL
1980
+				),
1981
+				esc_html__(' Resend Registration', 'event_espresso'),
1982
+				'button secondary-button right',
1983
+				'dashicons dashicons-email-alt'
1984
+			);
1985
+		} else {
1986
+			$this->_template_args['resend_registration_button'] = '';
1987
+		}
1988
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1989
+		$payment                               = $transaction->get_first_related('Payment');
1990
+		$payment                               = ! $payment instanceof EE_Payment
1991
+			? EE_Payment::new_instance()
1992
+			: $payment;
1993
+		$payment_method                        = $payment->get_first_related('Payment_Method');
1994
+		$payment_method                        = ! $payment_method instanceof EE_Payment_Method
1995
+			? EE_Payment_Method::new_instance()
1996
+			: $payment_method;
1997
+		$reg_details                           = array(
1998
+			'payment_method'       => $payment_method->name(),
1999
+			'response_msg'         => $payment->gateway_response(),
2000
+			'registration_id'      => $this->_registration->get('REG_code'),
2001
+			'registration_session' => $this->_registration->session_ID(),
2002
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2003
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2004
+		);
2005
+		if (isset($reg_details['registration_id'])) {
2006
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2007
+			$this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2008
+				'Registration ID',
2009
+				'event_espresso'
2010
+			);
2011
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2012
+		}
2013
+		if (isset($reg_details['payment_method'])) {
2014
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2015
+			$this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2016
+				'Most Recent Payment Method',
2017
+				'event_espresso'
2018
+			);
2019
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2020
+			$this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
2021
+			$this->_template_args['reg_details']['response_msg']['label']   = esc_html__(
2022
+				'Payment method response',
2023
+				'event_espresso'
2024
+			);
2025
+			$this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
2026
+		}
2027
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2028
+		$this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2029
+			'Registration Session',
2030
+			'event_espresso'
2031
+		);
2032
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2033
+		$this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
2034
+		$this->_template_args['reg_details']['ip_address']['label']           = esc_html__(
2035
+			'Registration placed from IP',
2036
+			'event_espresso'
2037
+		);
2038
+		$this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
2039
+		$this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
2040
+		$this->_template_args['reg_details']['user_agent']['label']           = esc_html__('Registrant User Agent',
2041
+			'event_espresso');
2042
+		$this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
2043
+		$this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(
2044
+			array(
2045
+				'action'   => 'default',
2046
+				'event_id' => $this->_registration->event_ID(),
2047
+			),
2048
+			REG_ADMIN_URL
2049
+		);
2050
+		$this->_template_args['REG_ID']                                       = $this->_registration->ID();
2051
+		$this->_template_args['event_id']                                     = $this->_registration->event_ID();
2052
+		$template_path                                                        =
2053
+			REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2054
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2055
+	}
2056
+
2057
+
2058
+	/**
2059
+	 * generates HTML for the Registration Questions meta box.
2060
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2061
+	 * otherwise uses new forms system
2062
+	 *
2063
+	 * @access public
2064
+	 * @return void
2065
+	 * @throws DomainException
2066
+	 * @throws EE_Error
2067
+	 */
2068
+	public function _reg_questions_meta_box()
2069
+	{
2070
+		//allow someone to override this method entirely
2071
+		if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
2072
+			$this->_registration)) {
2073
+			$form                                              = $this->_get_reg_custom_questions_form(
2074
+				$this->_registration->ID()
2075
+			);
2076
+			$this->_template_args['att_questions']             = count($form->subforms()) > 0
2077
+				? $form->get_html_and_js()
2078
+				: '';
2079
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
2080
+			$this->_template_args['REG_ID']                    = $this->_registration->ID();
2081
+			$template_path                                     =
2082
+				REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2083
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
2084
+		}
2085
+	}
2086
+
2087
+
2088
+	/**
2089
+	 * form_before_question_group
2090
+	 *
2091
+	 * @deprecated    as of 4.8.32.rc.000
2092
+	 * @access        public
2093
+	 * @param        string $output
2094
+	 * @return        string
2095
+	 */
2096
+	public function form_before_question_group($output)
2097
+	{
2098
+		EE_Error::doing_it_wrong(
2099
+			__CLASS__ . '::' . __FUNCTION__,
2100
+			esc_html__(
2101
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2102
+				'event_espresso'
2103
+			),
2104
+			'4.8.32.rc.000'
2105
+		);
2106
+		return '
2107 2107
 	<table class="form-table ee-width-100">
2108 2108
 		<tbody>
2109 2109
 			';
2110
-    }
2111
-
2112
-
2113
-    /**
2114
-     * form_after_question_group
2115
-     *
2116
-     * @deprecated    as of 4.8.32.rc.000
2117
-     * @access        public
2118
-     * @param        string $output
2119
-     * @return        string
2120
-     */
2121
-    public function form_after_question_group($output)
2122
-    {
2123
-        EE_Error::doing_it_wrong(
2124
-            __CLASS__ . '::' . __FUNCTION__,
2125
-            esc_html__(
2126
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2127
-                'event_espresso'
2128
-            ),
2129
-            '4.8.32.rc.000'
2130
-        );
2131
-        return '
2110
+	}
2111
+
2112
+
2113
+	/**
2114
+	 * form_after_question_group
2115
+	 *
2116
+	 * @deprecated    as of 4.8.32.rc.000
2117
+	 * @access        public
2118
+	 * @param        string $output
2119
+	 * @return        string
2120
+	 */
2121
+	public function form_after_question_group($output)
2122
+	{
2123
+		EE_Error::doing_it_wrong(
2124
+			__CLASS__ . '::' . __FUNCTION__,
2125
+			esc_html__(
2126
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2127
+				'event_espresso'
2128
+			),
2129
+			'4.8.32.rc.000'
2130
+		);
2131
+		return '
2132 2132
 			<tr class="hide-if-no-js">
2133 2133
 				<th> </th>
2134 2134
 				<td class="reg-admin-edit-attendee-question-td">
2135 2135
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
2136
-               . esc_attr__('click to edit question', 'event_espresso')
2137
-               . '">
2136
+			   . esc_attr__('click to edit question', 'event_espresso')
2137
+			   . '">
2138 2138
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
2139
-               . esc_html__('edit the above question group', 'event_espresso')
2140
-               . '</span>
2139
+			   . esc_html__('edit the above question group', 'event_espresso')
2140
+			   . '</span>
2141 2141
 						<div class="dashicons dashicons-edit"></div>
2142 2142
 					</a>
2143 2143
 				</td>
@@ -2145,558 +2145,558 @@  discard block
 block discarded – undo
2145 2145
 		</tbody>
2146 2146
 	</table>
2147 2147
 ';
2148
-    }
2149
-
2150
-
2151
-    /**
2152
-     * form_form_field_label_wrap
2153
-     *
2154
-     * @deprecated    as of 4.8.32.rc.000
2155
-     * @access        public
2156
-     * @param        string $label
2157
-     * @return        string
2158
-     */
2159
-    public function form_form_field_label_wrap($label)
2160
-    {
2161
-        EE_Error::doing_it_wrong(
2162
-            __CLASS__ . '::' . __FUNCTION__,
2163
-            esc_html__(
2164
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2165
-                'event_espresso'
2166
-            ),
2167
-            '4.8.32.rc.000'
2168
-        );
2169
-        return '
2148
+	}
2149
+
2150
+
2151
+	/**
2152
+	 * form_form_field_label_wrap
2153
+	 *
2154
+	 * @deprecated    as of 4.8.32.rc.000
2155
+	 * @access        public
2156
+	 * @param        string $label
2157
+	 * @return        string
2158
+	 */
2159
+	public function form_form_field_label_wrap($label)
2160
+	{
2161
+		EE_Error::doing_it_wrong(
2162
+			__CLASS__ . '::' . __FUNCTION__,
2163
+			esc_html__(
2164
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2165
+				'event_espresso'
2166
+			),
2167
+			'4.8.32.rc.000'
2168
+		);
2169
+		return '
2170 2170
 			<tr>
2171 2171
 				<th>
2172 2172
 					' . $label . '
2173 2173
 				</th>';
2174
-    }
2175
-
2176
-
2177
-    /**
2178
-     * form_form_field_input__wrap
2179
-     *
2180
-     * @deprecated    as of 4.8.32.rc.000
2181
-     * @access        public
2182
-     * @param        string $input
2183
-     * @return        string
2184
-     */
2185
-    public function form_form_field_input__wrap($input)
2186
-    {
2187
-        EE_Error::doing_it_wrong(
2188
-            __CLASS__ . '::' . __FUNCTION__,
2189
-            esc_html__(
2190
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2191
-                'event_espresso'
2192
-            ),
2193
-            '4.8.32.rc.000'
2194
-        );
2195
-        return '
2174
+	}
2175
+
2176
+
2177
+	/**
2178
+	 * form_form_field_input__wrap
2179
+	 *
2180
+	 * @deprecated    as of 4.8.32.rc.000
2181
+	 * @access        public
2182
+	 * @param        string $input
2183
+	 * @return        string
2184
+	 */
2185
+	public function form_form_field_input__wrap($input)
2186
+	{
2187
+		EE_Error::doing_it_wrong(
2188
+			__CLASS__ . '::' . __FUNCTION__,
2189
+			esc_html__(
2190
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2191
+				'event_espresso'
2192
+			),
2193
+			'4.8.32.rc.000'
2194
+		);
2195
+		return '
2196 2196
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2197 2197
 					' . $input . '
2198 2198
 				</td>
2199 2199
 			</tr>';
2200
-    }
2201
-
2202
-
2203
-    /**
2204
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
2205
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
2206
-     * to display the page
2207
-     *
2208
-     * @access protected
2209
-     * @return void
2210
-     * @throws EE_Error
2211
-     */
2212
-    protected function _update_attendee_registration_form()
2213
-    {
2214
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2215
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2216
-            $REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2217
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
2218
-            if ($success) {
2219
-                $what  = esc_html__('Registration Form', 'event_espresso');
2220
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2221
-                    : array('action' => 'default');
2222
-                $this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2223
-            }
2224
-        }
2225
-    }
2226
-
2227
-
2228
-    /**
2229
-     * Gets the form for saving registrations custom questions (if done
2230
-     * previously retrieves the cached form object, which may have validation errors in it)
2231
-     *
2232
-     * @param int $REG_ID
2233
-     * @return EE_Registration_Custom_Questions_Form
2234
-     * @throws EE_Error
2235
-     */
2236
-    protected function _get_reg_custom_questions_form($REG_ID)
2237
-    {
2238
-        if ( ! $this->_reg_custom_questions_form) {
2239
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2240
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2241
-                EEM_Registration::instance()->get_one_by_ID($REG_ID)
2242
-            );
2243
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
2244
-        }
2245
-        return $this->_reg_custom_questions_form;
2246
-    }
2247
-
2248
-
2249
-    /**
2250
-     * Saves
2251
-     *
2252
-     * @access private
2253
-     * @param bool $REG_ID
2254
-     * @return bool
2255
-     * @throws EE_Error
2256
-     */
2257
-    private function _save_reg_custom_questions_form($REG_ID = false)
2258
-    {
2259
-        if ( ! $REG_ID) {
2260
-            EE_Error::add_error(
2261
-                esc_html__(
2262
-                    'An error occurred. No registration ID was received.', 'event_espresso'),
2263
-                __FILE__, __FUNCTION__, __LINE__
2264
-            );
2265
-        }
2266
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
2267
-        $form->receive_form_submission($this->_req_data);
2268
-        $success = false;
2269
-        if ($form->is_valid()) {
2270
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
2271
-                foreach ($question_group_form->inputs() as $question_id => $input) {
2272
-                    $where_conditions    = array(
2273
-                        'QST_ID' => $question_id,
2274
-                        'REG_ID' => $REG_ID,
2275
-                    );
2276
-                    $possibly_new_values = array(
2277
-                        'ANS_value' => $input->normalized_value(),
2278
-                    );
2279
-                    $answer              = EEM_Answer::instance()->get_one(array($where_conditions));
2280
-                    if ($answer instanceof EE_Answer) {
2281
-                        $success = $answer->save($possibly_new_values);
2282
-                    } else {
2283
-                        //insert it then
2284
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2285
-                        $answer      = EE_Answer::new_instance($cols_n_vals);
2286
-                        $success     = $answer->save();
2287
-                    }
2288
-                }
2289
-            }
2290
-        } else {
2291
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2292
-        }
2293
-        return $success;
2294
-    }
2295
-
2296
-
2297
-    /**
2298
-     *        generates HTML for the Registration main meta box
2299
-     *
2300
-     * @access public
2301
-     * @return void
2302
-     * @throws DomainException
2303
-     * @throws EE_Error
2304
-     */
2305
-    public function _reg_attendees_meta_box()
2306
-    {
2307
-        $REG = EEM_Registration::instance();
2308
-        //get all other registrations on this transaction, and cache
2309
-        //the attendees for them so we don't have to run another query using force_join
2310
-        $registrations                           = $REG->get_all(array(
2311
-            array(
2312
-                'TXN_ID' => $this->_registration->transaction_ID(),
2313
-                'REG_ID' => array('!=', $this->_registration->ID()),
2314
-            ),
2315
-            'force_join' => array('Attendee'),
2316
-        ));
2317
-        $this->_template_args['attendees']       = array();
2318
-        $this->_template_args['attendee_notice'] = '';
2319
-        if (empty($registrations)
2320
-            || (is_array($registrations)
2321
-                && ! EEH_Array::get_one_item_from_array($registrations))
2322
-        ) {
2323
-            EE_Error::add_error(
2324
-                esc_html__(
2325
-                    'There are no records attached to this registration. Something may have gone wrong with the registration',
2326
-                    'event_espresso'
2327
-                ), __FILE__, __FUNCTION__, __LINE__
2328
-            );
2329
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2330
-        } else {
2331
-            $att_nmbr = 1;
2332
-            foreach ($registrations as $registration) {
2333
-                /* @var $registration EE_Registration */
2334
-                $attendee                                                    = $registration->attendee()
2335
-                    ? $registration->attendee()
2336
-                    : EEM_Attendee::instance()
2337
-                                  ->create_default_object();
2338
-                $this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2339
-                $this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();
2340
-                $this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();
2341
-                $this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();
2342
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();
2343
-                $this->_template_args['attendees'][$att_nmbr]['address']     = implode(
2344
-                    ', ',
2345
-                    $attendee->full_address_as_array()
2346
-                );
2347
-                $this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(
2348
-                    array(
2349
-                        'action' => 'edit_attendee',
2350
-                        'post'   => $attendee->ID(),
2351
-                    ),
2352
-                    REG_ADMIN_URL
2353
-                );
2354
-                $this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2355
-                $att_nmbr++;
2356
-            }
2357
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2358
-        }
2359
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2360
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2361
-    }
2362
-
2363
-
2364
-    /**
2365
-     *        generates HTML for the Edit Registration side meta box
2366
-     *
2367
-     * @access public
2368
-     * @return void
2369
-     * @throws DomainException
2370
-     * @throws EE_Error
2371
-     */
2372
-    public function _reg_registrant_side_meta_box()
2373
-    {
2374
-        /*@var $attendee EE_Attendee */
2375
-        $att_check = $this->_registration->attendee();
2376
-        $attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2377
-        //now let's determine if this is not the primary registration.  If it isn't then we set the
2378
-        //primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2379
-        //primary registration object (that way we know if we need to show create button or not)
2380
-        if ( ! $this->_registration->is_primary_registrant()) {
2381
-            $primary_registration = $this->_registration->get_primary_registration();
2382
-            $primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2383
-                : null;
2384
-            if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2385
-                //in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2386
-                //custom attendee object so let's not worry about the primary reg.
2387
-                $primary_registration = null;
2388
-            }
2389
-        } else {
2390
-            $primary_registration = null;
2391
-        }
2392
-        $this->_template_args['ATT_ID']            = $attendee->ID();
2393
-        $this->_template_args['fname']             = $attendee->fname();
2394
-        $this->_template_args['lname']             = $attendee->lname();
2395
-        $this->_template_args['email']             = $attendee->email();
2396
-        $this->_template_args['phone']             = $attendee->phone();
2397
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2398
-        //edit link
2399
-        $this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2400
-            'action' => 'edit_attendee',
2401
-            'post'   => $attendee->ID(),
2402
-        ), REG_ADMIN_URL);
2403
-        $this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2404
-        //create link
2405
-        $this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2406
-            ? EE_Admin_Page::add_query_args_and_nonce(array(
2407
-                'action'  => 'duplicate_attendee',
2408
-                '_REG_ID' => $this->_registration->ID(),
2409
-            ), REG_ADMIN_URL) : '';
2410
-        $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2411
-        $this->_template_args['att_check']    = $att_check;
2412
-        $template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2413
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2414
-    }
2415
-
2416
-
2417
-    /**
2418
-     * trash or restore registrations
2419
-     *
2420
-     * @param  boolean $trash whether to archive or restore
2421
-     * @return void
2422
-     * @throws EE_Error
2423
-     * @throws RuntimeException
2424
-     * @access protected
2425
-     */
2426
-    protected function _trash_or_restore_registrations($trash = true)
2427
-    {
2428
-        //if empty _REG_ID then get out because there's nothing to do
2429
-        if (empty($this->_req_data['_REG_ID'])) {
2430
-            EE_Error::add_error(
2431
-                sprintf(
2432
-                    esc_html__(
2433
-                        'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2434
-                        'event_espresso'
2435
-                    ),
2436
-                    $trash ? 'trash' : 'restore'
2437
-                ),
2438
-                __FILE__, __LINE__, __FUNCTION__
2439
-            );
2440
-            $this->_redirect_after_action(false, '', '', array(), true);
2441
-        }
2442
-        $success = 0;
2443
-        $overwrite_msgs = false;
2444
-        //Checkboxes
2445
-        if ( ! is_array($this->_req_data['_REG_ID'])) {
2446
-            $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2447
-        }
2448
-        $reg_count = count($this->_req_data['_REG_ID']);
2449
-        // cycle thru checkboxes
2450
-        foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2451
-            /** @var EE_Registration $REG */
2452
-            $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2453
-            $payments = $REG->registration_payments();
2454
-            if (! empty($payments)) {
2455
-                $name = $REG->attendee() instanceof EE_Attendee
2456
-                    ? $REG->attendee()->full_name()
2457
-                    : esc_html__('Unknown Attendee', 'event_espresso');
2458
-                $overwrite_msgs = true;
2459
-                EE_Error::add_error(
2460
-                    sprintf(
2461
-                        esc_html__(
2462
-                            'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2463
-                            'event_espresso'
2464
-                        ),
2465
-                        $name
2466
-                    ),
2467
-                    __FILE__, __FUNCTION__, __LINE__
2468
-                );
2469
-                //can't trash this registration because it has payments.
2470
-                continue;
2471
-            }
2472
-            $updated = $trash ? $REG->delete() : $REG->restore();
2473
-            if ($updated) {
2474
-                $success++;
2475
-            }
2476
-        }
2477
-        $this->_redirect_after_action(
2478
-            $success === $reg_count, // were ALL registrations affected?
2479
-            $success > 1
2480
-                ? esc_html__('Registrations', 'event_espresso')
2481
-                : esc_html__('Registration', 'event_espresso'),
2482
-            $trash
2483
-                ? esc_html__('moved to the trash', 'event_espresso')
2484
-                : esc_html__('restored', 'event_espresso'),
2485
-            array('action' => 'default'),
2486
-            $overwrite_msgs
2487
-        );
2488
-    }
2489
-
2490
-
2491
-    /**
2492
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2493
-     * registration but also.
2494
-     * 1. Removing relations to EE_Attendee
2495
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2496
-     * ALSO trashed.
2497
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2498
-     * 4. Removing relationships between all tickets and the related registrations
2499
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2500
-     * 6. Deleting permanently any related Checkins.
2501
-     *
2502
-     * @return void
2503
-     * @throws EE_Error
2504
-     */
2505
-    protected function _delete_registrations()
2506
-    {
2507
-        $REG_MDL = EEM_Registration::instance();
2508
-        $success = 1;
2509
-        //Checkboxes
2510
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2511
-            // if array has more than one element than success message should be plural
2512
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2513
-            // cycle thru checkboxes
2514
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2515
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2516
-                if ( ! $REG instanceof EE_Registration) {
2517
-                    continue;
2518
-                }
2519
-                $deleted = $this->_delete_registration($REG);
2520
-                if ( ! $deleted) {
2521
-                    $success = 0;
2522
-                }
2523
-            }
2524
-        } else {
2525
-            // grab single id and delete
2526
-            $REG_ID  = $this->_req_data['_REG_ID'];
2527
-            $REG     = $REG_MDL->get_one_by_ID($REG_ID);
2528
-            $deleted = $this->_delete_registration($REG);
2529
-            if ( ! $deleted) {
2530
-                $success = 0;
2531
-            }
2532
-        }
2533
-        $what        = $success > 1
2534
-            ? esc_html__('Registrations', 'event_espresso')
2535
-            : esc_html__('Registration', 'event_espresso');
2536
-        $action_desc = esc_html__('permanently deleted.', 'event_espresso');
2537
-        $this->_redirect_after_action(
2538
-            $success,
2539
-            $what,
2540
-            $action_desc,
2541
-            array('action' => 'default'),
2542
-            true
2543
-        );
2544
-    }
2545
-
2546
-
2547
-    /**
2548
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2549
-     * models get affected.
2550
-     *
2551
-     * @param  EE_Registration $REG registration to be deleted permenantly
2552
-     * @return bool true = successful deletion, false = fail.
2553
-     * @throws EE_Error
2554
-     */
2555
-    protected function _delete_registration(EE_Registration $REG)
2556
-    {
2557
-        //first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2558
-        //registrations on the transaction that are NOT trashed.
2559
-        $TXN         = $REG->get_first_related('Transaction');
2560
-        $REGS        = $TXN->get_many_related('Registration');
2561
-        $all_trashed = true;
2562
-        foreach ($REGS as $registration) {
2563
-            if ( ! $registration->get('REG_deleted')) {
2564
-                $all_trashed = false;
2565
-            }
2566
-        }
2567
-        if ( ! $all_trashed) {
2568
-            EE_Error::add_error(
2569
-                esc_html__(
2570
-                    'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2571
-                    'event_espresso'
2572
-                ),
2573
-                __FILE__, __FUNCTION__, __LINE__
2574
-            );
2575
-            return false;
2576
-        }
2577
-        //k made it here so that means we can delete all the related transactions and their answers (but let's do them
2578
-        //separately from THIS one).
2579
-        foreach ($REGS as $registration) {
2580
-            //delete related answers
2581
-            $registration->delete_related_permanently('Answer');
2582
-            //remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2583
-            $attendee = $registration->get_first_related('Attendee');
2584
-            if ($attendee instanceof EE_Attendee) {
2585
-                $registration->_remove_relation_to($attendee, 'Attendee');
2586
-            }
2587
-            //now remove relationships to tickets on this registration.
2588
-            $registration->_remove_relations('Ticket');
2589
-            //now delete permanently the checkins related to this registration.
2590
-            $registration->delete_related_permanently('Checkin');
2591
-            if ($registration->ID() === $REG->ID()) {
2592
-                continue;
2593
-            } //we don't want to delete permanently the existing registration just yet.
2594
-            //remove relation to transaction for these registrations if NOT the existing registrations
2595
-            $registration->_remove_relations('Transaction');
2596
-            //delete permanently any related messages.
2597
-            $registration->delete_related_permanently('Message');
2598
-            //now delete this registration permanently
2599
-            $registration->delete_permanently();
2600
-        }
2601
-        //now all related registrations on the transaction are handled.  So let's just handle this registration itself
2602
-        // (the transaction and line items should be all that's left).
2603
-        // delete the line items related to the transaction for this registration.
2604
-        $TXN->delete_related_permanently('Line_Item');
2605
-        //we need to remove all the relationships on the transaction
2606
-        $TXN->delete_related_permanently('Payment');
2607
-        $TXN->delete_related_permanently('Extra_Meta');
2608
-        $TXN->delete_related_permanently('Message');
2609
-        //now we can delete this REG permanently (and the transaction of course)
2610
-        $REG->delete_related_permanently('Transaction');
2611
-        return $REG->delete_permanently();
2612
-    }
2613
-
2614
-
2615
-    /**
2616
-     *    generates HTML for the Register New Attendee Admin page
2617
-     *
2618
-     * @access private
2619
-     * @throws DomainException
2620
-     * @throws EE_Error
2621
-     */
2622
-    public function new_registration()
2623
-    {
2624
-        if ( ! $this->_set_reg_event()) {
2625
-            throw new EE_Error(
2626
-                esc_html__(
2627
-                    'Unable to continue with registering because there is no Event ID in the request',
2628
-                    'event_espresso'
2629
-                )
2630
-            );
2631
-        }
2632
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2633
-        // gotta start with a clean slate if we're not coming here via ajax
2634
-        if ( ! defined('DOING_AJAX')
2635
-             && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2636
-        ) {
2637
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2638
-        }
2639
-        $this->_template_args['event_name'] = '';
2640
-        // event name
2641
-        if ($this->_reg_event) {
2642
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2643
-            $edit_event_url                     = self::add_query_args_and_nonce(array(
2644
-                'action' => 'edit',
2645
-                'post'   => $this->_reg_event->ID(),
2646
-            ), EVENTS_ADMIN_URL);
2647
-            $edit_event_lnk                     = '<a href="'
2648
-                                                  . $edit_event_url
2649
-                                                  . '" title="'
2650
-                                                  . esc_attr__('Edit ', 'event_espresso')
2651
-                                                  . $this->_reg_event->name()
2652
-                                                  . '">'
2653
-                                                  . esc_html__('Edit Event', 'event_espresso')
2654
-                                                  . '</a>';
2655
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2656
-                                                   . $edit_event_lnk
2657
-                                                   . '</span>';
2658
-        }
2659
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2660
-        if (defined('DOING_AJAX')) {
2661
-            $this->_return_json();
2662
-        }
2663
-        // grab header
2664
-        $template_path                              =
2665
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2666
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2667
-            $this->_template_args, true);
2668
-        //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2669
-        // the details template wrapper
2670
-        $this->display_admin_page_with_sidebar();
2671
-    }
2672
-
2673
-
2674
-    /**
2675
-     * This returns the content for a registration step
2676
-     *
2677
-     * @access protected
2678
-     * @return string html
2679
-     * @throws DomainException
2680
-     * @throws EE_Error
2681
-     */
2682
-    protected function _get_registration_step_content()
2683
-    {
2684
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2685
-            $warning_msg = sprintf(
2686
-                esc_html__(
2687
-                    '%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2688
-                    'event_espresso'
2689
-                ),
2690
-                '<br />',
2691
-                '<h3 class="important-notice">',
2692
-                '</h3>',
2693
-                '<div class="float-right">',
2694
-                '<span id="redirect_timer" class="important-notice">30</span>',
2695
-                '</div>',
2696
-                '<b>',
2697
-                '</b>'
2698
-            );
2699
-            return '
2200
+	}
2201
+
2202
+
2203
+	/**
2204
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
2205
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
2206
+	 * to display the page
2207
+	 *
2208
+	 * @access protected
2209
+	 * @return void
2210
+	 * @throws EE_Error
2211
+	 */
2212
+	protected function _update_attendee_registration_form()
2213
+	{
2214
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2215
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2216
+			$REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2217
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
2218
+			if ($success) {
2219
+				$what  = esc_html__('Registration Form', 'event_espresso');
2220
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2221
+					: array('action' => 'default');
2222
+				$this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2223
+			}
2224
+		}
2225
+	}
2226
+
2227
+
2228
+	/**
2229
+	 * Gets the form for saving registrations custom questions (if done
2230
+	 * previously retrieves the cached form object, which may have validation errors in it)
2231
+	 *
2232
+	 * @param int $REG_ID
2233
+	 * @return EE_Registration_Custom_Questions_Form
2234
+	 * @throws EE_Error
2235
+	 */
2236
+	protected function _get_reg_custom_questions_form($REG_ID)
2237
+	{
2238
+		if ( ! $this->_reg_custom_questions_form) {
2239
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2240
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2241
+				EEM_Registration::instance()->get_one_by_ID($REG_ID)
2242
+			);
2243
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
2244
+		}
2245
+		return $this->_reg_custom_questions_form;
2246
+	}
2247
+
2248
+
2249
+	/**
2250
+	 * Saves
2251
+	 *
2252
+	 * @access private
2253
+	 * @param bool $REG_ID
2254
+	 * @return bool
2255
+	 * @throws EE_Error
2256
+	 */
2257
+	private function _save_reg_custom_questions_form($REG_ID = false)
2258
+	{
2259
+		if ( ! $REG_ID) {
2260
+			EE_Error::add_error(
2261
+				esc_html__(
2262
+					'An error occurred. No registration ID was received.', 'event_espresso'),
2263
+				__FILE__, __FUNCTION__, __LINE__
2264
+			);
2265
+		}
2266
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
2267
+		$form->receive_form_submission($this->_req_data);
2268
+		$success = false;
2269
+		if ($form->is_valid()) {
2270
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
2271
+				foreach ($question_group_form->inputs() as $question_id => $input) {
2272
+					$where_conditions    = array(
2273
+						'QST_ID' => $question_id,
2274
+						'REG_ID' => $REG_ID,
2275
+					);
2276
+					$possibly_new_values = array(
2277
+						'ANS_value' => $input->normalized_value(),
2278
+					);
2279
+					$answer              = EEM_Answer::instance()->get_one(array($where_conditions));
2280
+					if ($answer instanceof EE_Answer) {
2281
+						$success = $answer->save($possibly_new_values);
2282
+					} else {
2283
+						//insert it then
2284
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2285
+						$answer      = EE_Answer::new_instance($cols_n_vals);
2286
+						$success     = $answer->save();
2287
+					}
2288
+				}
2289
+			}
2290
+		} else {
2291
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2292
+		}
2293
+		return $success;
2294
+	}
2295
+
2296
+
2297
+	/**
2298
+	 *        generates HTML for the Registration main meta box
2299
+	 *
2300
+	 * @access public
2301
+	 * @return void
2302
+	 * @throws DomainException
2303
+	 * @throws EE_Error
2304
+	 */
2305
+	public function _reg_attendees_meta_box()
2306
+	{
2307
+		$REG = EEM_Registration::instance();
2308
+		//get all other registrations on this transaction, and cache
2309
+		//the attendees for them so we don't have to run another query using force_join
2310
+		$registrations                           = $REG->get_all(array(
2311
+			array(
2312
+				'TXN_ID' => $this->_registration->transaction_ID(),
2313
+				'REG_ID' => array('!=', $this->_registration->ID()),
2314
+			),
2315
+			'force_join' => array('Attendee'),
2316
+		));
2317
+		$this->_template_args['attendees']       = array();
2318
+		$this->_template_args['attendee_notice'] = '';
2319
+		if (empty($registrations)
2320
+			|| (is_array($registrations)
2321
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2322
+		) {
2323
+			EE_Error::add_error(
2324
+				esc_html__(
2325
+					'There are no records attached to this registration. Something may have gone wrong with the registration',
2326
+					'event_espresso'
2327
+				), __FILE__, __FUNCTION__, __LINE__
2328
+			);
2329
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2330
+		} else {
2331
+			$att_nmbr = 1;
2332
+			foreach ($registrations as $registration) {
2333
+				/* @var $registration EE_Registration */
2334
+				$attendee                                                    = $registration->attendee()
2335
+					? $registration->attendee()
2336
+					: EEM_Attendee::instance()
2337
+								  ->create_default_object();
2338
+				$this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2339
+				$this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();
2340
+				$this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();
2341
+				$this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();
2342
+				$this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();
2343
+				$this->_template_args['attendees'][$att_nmbr]['address']     = implode(
2344
+					', ',
2345
+					$attendee->full_address_as_array()
2346
+				);
2347
+				$this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(
2348
+					array(
2349
+						'action' => 'edit_attendee',
2350
+						'post'   => $attendee->ID(),
2351
+					),
2352
+					REG_ADMIN_URL
2353
+				);
2354
+				$this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2355
+				$att_nmbr++;
2356
+			}
2357
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2358
+		}
2359
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2360
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2361
+	}
2362
+
2363
+
2364
+	/**
2365
+	 *        generates HTML for the Edit Registration side meta box
2366
+	 *
2367
+	 * @access public
2368
+	 * @return void
2369
+	 * @throws DomainException
2370
+	 * @throws EE_Error
2371
+	 */
2372
+	public function _reg_registrant_side_meta_box()
2373
+	{
2374
+		/*@var $attendee EE_Attendee */
2375
+		$att_check = $this->_registration->attendee();
2376
+		$attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2377
+		//now let's determine if this is not the primary registration.  If it isn't then we set the
2378
+		//primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2379
+		//primary registration object (that way we know if we need to show create button or not)
2380
+		if ( ! $this->_registration->is_primary_registrant()) {
2381
+			$primary_registration = $this->_registration->get_primary_registration();
2382
+			$primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2383
+				: null;
2384
+			if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2385
+				//in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2386
+				//custom attendee object so let's not worry about the primary reg.
2387
+				$primary_registration = null;
2388
+			}
2389
+		} else {
2390
+			$primary_registration = null;
2391
+		}
2392
+		$this->_template_args['ATT_ID']            = $attendee->ID();
2393
+		$this->_template_args['fname']             = $attendee->fname();
2394
+		$this->_template_args['lname']             = $attendee->lname();
2395
+		$this->_template_args['email']             = $attendee->email();
2396
+		$this->_template_args['phone']             = $attendee->phone();
2397
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2398
+		//edit link
2399
+		$this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2400
+			'action' => 'edit_attendee',
2401
+			'post'   => $attendee->ID(),
2402
+		), REG_ADMIN_URL);
2403
+		$this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2404
+		//create link
2405
+		$this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2406
+			? EE_Admin_Page::add_query_args_and_nonce(array(
2407
+				'action'  => 'duplicate_attendee',
2408
+				'_REG_ID' => $this->_registration->ID(),
2409
+			), REG_ADMIN_URL) : '';
2410
+		$this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2411
+		$this->_template_args['att_check']    = $att_check;
2412
+		$template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2413
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2414
+	}
2415
+
2416
+
2417
+	/**
2418
+	 * trash or restore registrations
2419
+	 *
2420
+	 * @param  boolean $trash whether to archive or restore
2421
+	 * @return void
2422
+	 * @throws EE_Error
2423
+	 * @throws RuntimeException
2424
+	 * @access protected
2425
+	 */
2426
+	protected function _trash_or_restore_registrations($trash = true)
2427
+	{
2428
+		//if empty _REG_ID then get out because there's nothing to do
2429
+		if (empty($this->_req_data['_REG_ID'])) {
2430
+			EE_Error::add_error(
2431
+				sprintf(
2432
+					esc_html__(
2433
+						'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2434
+						'event_espresso'
2435
+					),
2436
+					$trash ? 'trash' : 'restore'
2437
+				),
2438
+				__FILE__, __LINE__, __FUNCTION__
2439
+			);
2440
+			$this->_redirect_after_action(false, '', '', array(), true);
2441
+		}
2442
+		$success = 0;
2443
+		$overwrite_msgs = false;
2444
+		//Checkboxes
2445
+		if ( ! is_array($this->_req_data['_REG_ID'])) {
2446
+			$this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2447
+		}
2448
+		$reg_count = count($this->_req_data['_REG_ID']);
2449
+		// cycle thru checkboxes
2450
+		foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2451
+			/** @var EE_Registration $REG */
2452
+			$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2453
+			$payments = $REG->registration_payments();
2454
+			if (! empty($payments)) {
2455
+				$name = $REG->attendee() instanceof EE_Attendee
2456
+					? $REG->attendee()->full_name()
2457
+					: esc_html__('Unknown Attendee', 'event_espresso');
2458
+				$overwrite_msgs = true;
2459
+				EE_Error::add_error(
2460
+					sprintf(
2461
+						esc_html__(
2462
+							'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2463
+							'event_espresso'
2464
+						),
2465
+						$name
2466
+					),
2467
+					__FILE__, __FUNCTION__, __LINE__
2468
+				);
2469
+				//can't trash this registration because it has payments.
2470
+				continue;
2471
+			}
2472
+			$updated = $trash ? $REG->delete() : $REG->restore();
2473
+			if ($updated) {
2474
+				$success++;
2475
+			}
2476
+		}
2477
+		$this->_redirect_after_action(
2478
+			$success === $reg_count, // were ALL registrations affected?
2479
+			$success > 1
2480
+				? esc_html__('Registrations', 'event_espresso')
2481
+				: esc_html__('Registration', 'event_espresso'),
2482
+			$trash
2483
+				? esc_html__('moved to the trash', 'event_espresso')
2484
+				: esc_html__('restored', 'event_espresso'),
2485
+			array('action' => 'default'),
2486
+			$overwrite_msgs
2487
+		);
2488
+	}
2489
+
2490
+
2491
+	/**
2492
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2493
+	 * registration but also.
2494
+	 * 1. Removing relations to EE_Attendee
2495
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2496
+	 * ALSO trashed.
2497
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2498
+	 * 4. Removing relationships between all tickets and the related registrations
2499
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2500
+	 * 6. Deleting permanently any related Checkins.
2501
+	 *
2502
+	 * @return void
2503
+	 * @throws EE_Error
2504
+	 */
2505
+	protected function _delete_registrations()
2506
+	{
2507
+		$REG_MDL = EEM_Registration::instance();
2508
+		$success = 1;
2509
+		//Checkboxes
2510
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2511
+			// if array has more than one element than success message should be plural
2512
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2513
+			// cycle thru checkboxes
2514
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2515
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2516
+				if ( ! $REG instanceof EE_Registration) {
2517
+					continue;
2518
+				}
2519
+				$deleted = $this->_delete_registration($REG);
2520
+				if ( ! $deleted) {
2521
+					$success = 0;
2522
+				}
2523
+			}
2524
+		} else {
2525
+			// grab single id and delete
2526
+			$REG_ID  = $this->_req_data['_REG_ID'];
2527
+			$REG     = $REG_MDL->get_one_by_ID($REG_ID);
2528
+			$deleted = $this->_delete_registration($REG);
2529
+			if ( ! $deleted) {
2530
+				$success = 0;
2531
+			}
2532
+		}
2533
+		$what        = $success > 1
2534
+			? esc_html__('Registrations', 'event_espresso')
2535
+			: esc_html__('Registration', 'event_espresso');
2536
+		$action_desc = esc_html__('permanently deleted.', 'event_espresso');
2537
+		$this->_redirect_after_action(
2538
+			$success,
2539
+			$what,
2540
+			$action_desc,
2541
+			array('action' => 'default'),
2542
+			true
2543
+		);
2544
+	}
2545
+
2546
+
2547
+	/**
2548
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2549
+	 * models get affected.
2550
+	 *
2551
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2552
+	 * @return bool true = successful deletion, false = fail.
2553
+	 * @throws EE_Error
2554
+	 */
2555
+	protected function _delete_registration(EE_Registration $REG)
2556
+	{
2557
+		//first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2558
+		//registrations on the transaction that are NOT trashed.
2559
+		$TXN         = $REG->get_first_related('Transaction');
2560
+		$REGS        = $TXN->get_many_related('Registration');
2561
+		$all_trashed = true;
2562
+		foreach ($REGS as $registration) {
2563
+			if ( ! $registration->get('REG_deleted')) {
2564
+				$all_trashed = false;
2565
+			}
2566
+		}
2567
+		if ( ! $all_trashed) {
2568
+			EE_Error::add_error(
2569
+				esc_html__(
2570
+					'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2571
+					'event_espresso'
2572
+				),
2573
+				__FILE__, __FUNCTION__, __LINE__
2574
+			);
2575
+			return false;
2576
+		}
2577
+		//k made it here so that means we can delete all the related transactions and their answers (but let's do them
2578
+		//separately from THIS one).
2579
+		foreach ($REGS as $registration) {
2580
+			//delete related answers
2581
+			$registration->delete_related_permanently('Answer');
2582
+			//remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2583
+			$attendee = $registration->get_first_related('Attendee');
2584
+			if ($attendee instanceof EE_Attendee) {
2585
+				$registration->_remove_relation_to($attendee, 'Attendee');
2586
+			}
2587
+			//now remove relationships to tickets on this registration.
2588
+			$registration->_remove_relations('Ticket');
2589
+			//now delete permanently the checkins related to this registration.
2590
+			$registration->delete_related_permanently('Checkin');
2591
+			if ($registration->ID() === $REG->ID()) {
2592
+				continue;
2593
+			} //we don't want to delete permanently the existing registration just yet.
2594
+			//remove relation to transaction for these registrations if NOT the existing registrations
2595
+			$registration->_remove_relations('Transaction');
2596
+			//delete permanently any related messages.
2597
+			$registration->delete_related_permanently('Message');
2598
+			//now delete this registration permanently
2599
+			$registration->delete_permanently();
2600
+		}
2601
+		//now all related registrations on the transaction are handled.  So let's just handle this registration itself
2602
+		// (the transaction and line items should be all that's left).
2603
+		// delete the line items related to the transaction for this registration.
2604
+		$TXN->delete_related_permanently('Line_Item');
2605
+		//we need to remove all the relationships on the transaction
2606
+		$TXN->delete_related_permanently('Payment');
2607
+		$TXN->delete_related_permanently('Extra_Meta');
2608
+		$TXN->delete_related_permanently('Message');
2609
+		//now we can delete this REG permanently (and the transaction of course)
2610
+		$REG->delete_related_permanently('Transaction');
2611
+		return $REG->delete_permanently();
2612
+	}
2613
+
2614
+
2615
+	/**
2616
+	 *    generates HTML for the Register New Attendee Admin page
2617
+	 *
2618
+	 * @access private
2619
+	 * @throws DomainException
2620
+	 * @throws EE_Error
2621
+	 */
2622
+	public function new_registration()
2623
+	{
2624
+		if ( ! $this->_set_reg_event()) {
2625
+			throw new EE_Error(
2626
+				esc_html__(
2627
+					'Unable to continue with registering because there is no Event ID in the request',
2628
+					'event_espresso'
2629
+				)
2630
+			);
2631
+		}
2632
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2633
+		// gotta start with a clean slate if we're not coming here via ajax
2634
+		if ( ! defined('DOING_AJAX')
2635
+			 && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2636
+		) {
2637
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2638
+		}
2639
+		$this->_template_args['event_name'] = '';
2640
+		// event name
2641
+		if ($this->_reg_event) {
2642
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2643
+			$edit_event_url                     = self::add_query_args_and_nonce(array(
2644
+				'action' => 'edit',
2645
+				'post'   => $this->_reg_event->ID(),
2646
+			), EVENTS_ADMIN_URL);
2647
+			$edit_event_lnk                     = '<a href="'
2648
+												  . $edit_event_url
2649
+												  . '" title="'
2650
+												  . esc_attr__('Edit ', 'event_espresso')
2651
+												  . $this->_reg_event->name()
2652
+												  . '">'
2653
+												  . esc_html__('Edit Event', 'event_espresso')
2654
+												  . '</a>';
2655
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2656
+												   . $edit_event_lnk
2657
+												   . '</span>';
2658
+		}
2659
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2660
+		if (defined('DOING_AJAX')) {
2661
+			$this->_return_json();
2662
+		}
2663
+		// grab header
2664
+		$template_path                              =
2665
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2666
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2667
+			$this->_template_args, true);
2668
+		//$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2669
+		// the details template wrapper
2670
+		$this->display_admin_page_with_sidebar();
2671
+	}
2672
+
2673
+
2674
+	/**
2675
+	 * This returns the content for a registration step
2676
+	 *
2677
+	 * @access protected
2678
+	 * @return string html
2679
+	 * @throws DomainException
2680
+	 * @throws EE_Error
2681
+	 */
2682
+	protected function _get_registration_step_content()
2683
+	{
2684
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2685
+			$warning_msg = sprintf(
2686
+				esc_html__(
2687
+					'%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2688
+					'event_espresso'
2689
+				),
2690
+				'<br />',
2691
+				'<h3 class="important-notice">',
2692
+				'</h3>',
2693
+				'<div class="float-right">',
2694
+				'<span id="redirect_timer" class="important-notice">30</span>',
2695
+				'</div>',
2696
+				'<b>',
2697
+				'</b>'
2698
+			);
2699
+			return '
2700 2700
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2701 2701
 	<script >
2702 2702
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -2709,792 +2709,792 @@  discard block
 block discarded – undo
2709 2709
 	        }
2710 2710
 	    }, 800 );
2711 2711
 	</script >';
2712
-        }
2713
-        $template_args = array(
2714
-            'title'                    => '',
2715
-            'content'                  => '',
2716
-            'step_button_text'         => '',
2717
-            'show_notification_toggle' => false,
2718
-        );
2719
-        //to indicate we're processing a new registration
2720
-        $hidden_fields = array(
2721
-            'processing_registration' => array(
2722
-                'type'  => 'hidden',
2723
-                'value' => 0,
2724
-            ),
2725
-            'event_id'                => array(
2726
-                'type'  => 'hidden',
2727
-                'value' => $this->_reg_event->ID(),
2728
-            ),
2729
-        );
2730
-        //if the cart is empty then we know we're at step one so we'll display ticket selector
2731
-        $cart = EE_Registry::instance()->SSN->cart();
2732
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2733
-        switch ($step) {
2734
-            case 'ticket' :
2735
-                $hidden_fields['processing_registration']['value'] = 1;
2736
-                $template_args['title']                            = esc_html__(
2737
-                    'Step One: Select the Ticket for this registration',
2738
-                    'event_espresso'
2739
-                );
2740
-                $template_args['content']                          =
2741
-                    EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2742
-                $template_args['step_button_text']                 = esc_html__(
2743
-                    'Add Tickets and Continue to Registrant Details',
2744
-                    'event_espresso'
2745
-                );
2746
-                $template_args['show_notification_toggle']         = false;
2747
-                break;
2748
-            case 'questions' :
2749
-                $hidden_fields['processing_registration']['value'] = 2;
2750
-                $template_args['title']                            = esc_html__(
2751
-                    'Step Two: Add Registrant Details for this Registration',
2752
-                    'event_espresso'
2753
-                );
2754
-                //in theory we should be able to run EED_SPCO at this point because the cart should have been setup
2755
-                // properly by the first process_reg_step run.
2756
-                $template_args['content']                  =
2757
-                    EED_Single_Page_Checkout::registration_checkout_for_admin();
2758
-                $template_args['step_button_text']         = esc_html__(
2759
-                    'Save Registration and Continue to Details',
2760
-                    'event_espresso'
2761
-                );
2762
-                $template_args['show_notification_toggle'] = true;
2763
-                break;
2764
-        }
2765
-        //we come back to the process_registration_step route.
2766
-        $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
2767
-        return EEH_Template::display_template(
2768
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
2769
-            $template_args,
2770
-            true
2771
-        );
2772
-    }
2773
-
2774
-
2775
-    /**
2776
-     *        set_reg_event
2777
-     *
2778
-     * @access private
2779
-     * @return bool
2780
-     * @throws EE_Error
2781
-     */
2782
-    private function _set_reg_event()
2783
-    {
2784
-        if (is_object($this->_reg_event)) {
2785
-            return true;
2786
-        }
2787
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2788
-        if ( ! $EVT_ID) {
2789
-            return false;
2790
-        }
2791
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2792
-        return true;
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * process_reg_step
2798
-     *
2799
-     * @access        public
2800
-     * @return string
2801
-     * @throws DomainException
2802
-     * @throws EE_Error
2803
-     * @throws RuntimeException
2804
-     */
2805
-    public function process_reg_step()
2806
-    {
2807
-        EE_System::do_not_cache();
2808
-        $this->_set_reg_event();
2809
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2810
-        EE_Registry::instance()->REQ->set('uts', time());
2811
-        //what step are we on?
2812
-        $cart = EE_Registry::instance()->SSN->cart();
2813
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2814
-        //if doing ajax then we need to verify the nonce
2815
-        if (defined('DOING_AJAX')) {
2816
-            $nonce = isset($this->_req_data[$this->_req_nonce])
2817
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2818
-            $this->_verify_nonce($nonce, $this->_req_nonce);
2819
-        }
2820
-        switch ($step) {
2821
-            case 'ticket' :
2822
-                //process ticket selection
2823
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
2824
-                if ($success) {
2825
-                    EE_Error::add_success(
2826
-                        esc_html__(
2827
-                            'Tickets Selected. Now complete the registration.',
2828
-                            'event_espresso'
2829
-                        )
2830
-                    );
2831
-                } else {
2832
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
2833
-                }
2834
-                if (defined('DOING_AJAX')) {
2835
-                    $this->new_registration(); //display next step
2836
-                } else {
2837
-                    $query_args = array(
2838
-                        'action'                  => 'new_registration',
2839
-                        'processing_registration' => 1,
2840
-                        'event_id'                => $this->_reg_event->ID(),
2841
-                        'uts'                     => time(),
2842
-                    );
2843
-                    $this->_redirect_after_action(
2844
-                        false,
2845
-                        '',
2846
-                        '',
2847
-                        $query_args,
2848
-                        true
2849
-                    );
2850
-                }
2851
-                break;
2852
-            case 'questions' :
2853
-                if (! isset(
2854
-                    $this->_req_data['txn_reg_status_change'],
2855
-                    $this->_req_data['txn_reg_status_change']['send_notifications'])
2856
-                ) {
2857
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2858
-                }
2859
-                //process registration
2860
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2861
-                if ($cart instanceof EE_Cart) {
2862
-                    $grand_total = $cart->get_cart_grand_total();
2863
-                    if ($grand_total instanceof EE_Line_Item) {
2864
-                        $grand_total->save_this_and_descendants_to_txn();
2865
-                    }
2866
-                }
2867
-                if ( ! $transaction instanceof EE_Transaction) {
2868
-                    $query_args = array(
2869
-                        'action'                  => 'new_registration',
2870
-                        'processing_registration' => 2,
2871
-                        'event_id'                => $this->_reg_event->ID(),
2872
-                        'uts'                     => time(),
2873
-                    );
2874
-                    if (defined('DOING_AJAX')) {
2875
-                        //display registration form again because there are errors (maybe validation?)
2876
-                        $this->new_registration();
2877
-                        return;
2878
-                    } else {
2879
-                        $this->_redirect_after_action(
2880
-                            false,
2881
-                            '',
2882
-                            '',
2883
-                            $query_args,
2884
-                            true
2885
-                        );
2886
-                        return;
2887
-                    }
2888
-                }
2889
-                // maybe update status, and make sure to save transaction if not done already
2890
-                if ( ! $transaction->update_status_based_on_total_paid()) {
2891
-                    $transaction->save();
2892
-                }
2893
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2894
-                $this->_req_data = array();
2895
-                $query_args      = array(
2896
-                    'action'        => 'redirect_to_txn',
2897
-                    'TXN_ID'        => $transaction->ID(),
2898
-                    'EVT_ID'        => $this->_reg_event->ID(),
2899
-                    'event_name'    => urlencode($this->_reg_event->name()),
2900
-                    'redirect_from' => 'new_registration',
2901
-                );
2902
-                $this->_redirect_after_action(false, '', '', $query_args, true);
2903
-                break;
2904
-        }
2905
-        //what are you looking here for?  Should be nothing to do at this point.
2906
-    }
2907
-
2908
-
2909
-    /**
2910
-     * redirect_to_txn
2911
-     *
2912
-     * @access public
2913
-     * @return void
2914
-     * @throws EE_Error
2915
-     */
2916
-    public function redirect_to_txn()
2917
-    {
2918
-        EE_System::do_not_cache();
2919
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2920
-        $query_args = array(
2921
-            'action' => 'view_transaction',
2922
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2923
-            'page'   => 'espresso_transactions',
2924
-        );
2925
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2926
-            $query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
2927
-            $query_args['event_name']    = urlencode($this->_req_data['event_name']);
2928
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
2929
-        }
2930
-        EE_Error::add_success(
2931
-            esc_html__(
2932
-                'Registration Created.  Please review the transaction and add any payments as necessary',
2933
-                'event_espresso'
2934
-            )
2935
-        );
2936
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2937
-    }
2938
-
2939
-
2940
-    /**
2941
-     *        generates HTML for the Attendee Contact List
2942
-     *
2943
-     * @access protected
2944
-     * @return void
2945
-     */
2946
-    protected function _attendee_contact_list_table()
2947
-    {
2948
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2949
-        $this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
2950
-        $this->display_admin_list_table_page_with_no_sidebar();
2951
-    }
2952
-
2953
-
2954
-    /**
2955
-     *        get_attendees
2956
-     *
2957
-     * @param      $per_page
2958
-     * @param bool $count whether to return count or data.
2959
-     * @param bool $trash
2960
-     * @return array
2961
-     * @throws EE_Error
2962
-     * @access public
2963
-     */
2964
-    public function get_attendees($per_page, $count = false, $trash = false)
2965
-    {
2966
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2967
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2968
-        $ATT_MDL                    = EEM_Attendee::instance();
2969
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2970
-        switch ($this->_req_data['orderby']) {
2971
-            case 'ATT_ID':
2972
-                $orderby = 'ATT_ID';
2973
-                break;
2974
-            case 'ATT_fname':
2975
-                $orderby = 'ATT_fname';
2976
-                break;
2977
-            case 'ATT_email':
2978
-                $orderby = 'ATT_email';
2979
-                break;
2980
-            case 'ATT_city':
2981
-                $orderby = 'ATT_city';
2982
-                break;
2983
-            case 'STA_ID':
2984
-                $orderby = 'STA_ID';
2985
-                break;
2986
-            case 'CNT_ID':
2987
-                $orderby = 'CNT_ID';
2988
-                break;
2989
-            default:
2990
-                $orderby = 'ATT_lname';
2991
-        }
2992
-        $sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
2993
-            ? $this->_req_data['order']
2994
-            : 'ASC';
2995
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2996
-            ? $this->_req_data['paged']
2997
-            : 1;
2998
-        $per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2999
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3000
-            ? $this->_req_data['perpage']
3001
-            : $per_page;
3002
-        $_where       = array();
3003
-        if ( ! empty($this->_req_data['s'])) {
3004
-            $sstr         = '%' . $this->_req_data['s'] . '%';
3005
-            $_where['OR'] = array(
3006
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3007
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3008
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3009
-                'ATT_fname'                         => array('LIKE', $sstr),
3010
-                'ATT_lname'                         => array('LIKE', $sstr),
3011
-                'ATT_short_bio'                     => array('LIKE', $sstr),
3012
-                'ATT_email'                         => array('LIKE', $sstr),
3013
-                'ATT_address'                       => array('LIKE', $sstr),
3014
-                'ATT_address2'                      => array('LIKE', $sstr),
3015
-                'ATT_city'                          => array('LIKE', $sstr),
3016
-                'Country.CNT_name'                  => array('LIKE', $sstr),
3017
-                'State.STA_name'                    => array('LIKE', $sstr),
3018
-                'ATT_phone'                         => array('LIKE', $sstr),
3019
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
3020
-                'Registration.REG_code'             => array('LIKE', $sstr),
3021
-                'Registration.REG_count'            => array('LIKE', $sstr),
3022
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
3023
-            );
3024
-        }
3025
-        $offset = ($current_page - 1) * $per_page;
3026
-        $limit  = $count ? null : array($offset, $per_page);
3027
-        if ($trash) {
3028
-            $_where['status'] = array('!=', 'publish');
3029
-            $all_attendees    = $count
3030
-                ? $ATT_MDL->count(array(
3031
-                    $_where,
3032
-                    'order_by' => array($orderby => $sort),
3033
-                    'limit'    => $limit,
3034
-                ), 'ATT_ID', true)
3035
-                : $ATT_MDL->get_all(array(
3036
-                    $_where,
3037
-                    'order_by' => array($orderby => $sort),
3038
-                    'limit'    => $limit,
3039
-                ));
3040
-        } else {
3041
-            $_where['status'] = array('IN', array('publish'));
3042
-            $all_attendees    = $count
3043
-                ? $ATT_MDL->count(array(
3044
-                    $_where,
3045
-                    'order_by' => array($orderby => $sort),
3046
-                    'limit'    => $limit,
3047
-                ), 'ATT_ID', true)
3048
-                : $ATT_MDL->get_all(array(
3049
-                    $_where,
3050
-                    'order_by' => array($orderby => $sort),
3051
-                    'limit'    => $limit,
3052
-                ));
3053
-        }
3054
-        return $all_attendees;
3055
-    }
3056
-
3057
-
3058
-    /**
3059
-     * This is just taking care of resending the registration confirmation
3060
-     *
3061
-     * @access protected
3062
-     * @return void
3063
-     */
3064
-    protected function _resend_registration()
3065
-    {
3066
-        $this->_process_resend_registration();
3067
-        $query_args = isset($this->_req_data['redirect_to'])
3068
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3069
-            : array('action' => 'default');
3070
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3071
-    }
3072
-
3073
-    /**
3074
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3075
-     * to use when selecting registrations
3076
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3077
-     *                                                     the query parameters from the request
3078
-     * @return void ends the request with a redirect or download
3079
-     */
3080
-    public function _registrations_report_base( $method_name_for_getting_query_params )
3081
-    {
3082
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3083
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(
3084
-                array(
3085
-                    'page'        => 'espresso_batch',
3086
-                    'batch'       => 'file',
3087
-                    'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3088
-                    'filters'     => urlencode(
3089
-                        serialize(
3090
-                            call_user_func(
3091
-                                array( $this, $method_name_for_getting_query_params ),
3092
-                                EEH_Array::is_set(
3093
-                                    $this->_req_data,
3094
-                                    'filters',
3095
-                                    array()
3096
-                                )
3097
-                            )
3098
-                        )
3099
-                ),
3100
-                'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3101
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3102
-                'return_url'  => urlencode($this->_req_data['return_url']),
3103
-            )));
3104
-        } else {
3105
-            $new_request_args = array(
3106
-                'export' => 'report',
3107
-                'action' => 'registrations_report_for_event',
3108
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3109
-            );
3110
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
3111
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3112
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3113
-                $EE_Export = EE_Export::instance($this->_req_data);
3114
-                $EE_Export->export();
3115
-            }
3116
-        }
3117
-    }
3118
-
3119
-
3120
-
3121
-    /**
3122
-     * Creates a registration report using only query parameters in the request
3123
-     * @return void
3124
-     */
3125
-    public function _registrations_report()
3126
-    {
3127
-        $this->_registrations_report_base('_get_registration_query_parameters');
3128
-    }
3129
-
3130
-
3131
-    public function _contact_list_export()
3132
-    {
3133
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3134
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3135
-            $EE_Export = EE_Export::instance($this->_req_data);
3136
-            $EE_Export->export_attendees();
3137
-        }
3138
-    }
3139
-
3140
-
3141
-    public function _contact_list_report()
3142
-    {
3143
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3144
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
3145
-                'page'        => 'espresso_batch',
3146
-                'batch'       => 'file',
3147
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3148
-                'return_url'  => urlencode($this->_req_data['return_url']),
3149
-            )));
3150
-        } else {
3151
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3152
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3153
-                $EE_Export = EE_Export::instance($this->_req_data);
3154
-                $EE_Export->report_attendees();
3155
-            }
3156
-        }
3157
-    }
3158
-
3159
-
3160
-
3161
-
3162
-
3163
-    /***************************************        ATTENDEE DETAILS        ***************************************/
3164
-    /**
3165
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
3166
-     *
3167
-     * @return void
3168
-     * @throws EE_Error
3169
-     */
3170
-    protected function _duplicate_attendee()
3171
-    {
3172
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3173
-        //verify we have necessary info
3174
-        if (empty($this->_req_data['_REG_ID'])) {
3175
-            EE_Error::add_error(
3176
-                esc_html__(
3177
-                    'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3178
-                    'event_espresso'
3179
-                ), __FILE__, __LINE__, __FUNCTION__
3180
-            );
3181
-            $query_args = array('action' => $action);
3182
-            $this->_redirect_after_action('', '', '', $query_args, true);
3183
-        }
3184
-        //okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3185
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3186
-        $attendee     = $registration->attendee();
3187
-        //remove relation of existing attendee on registration
3188
-        $registration->_remove_relation_to($attendee, 'Attendee');
3189
-        //new attendee
3190
-        $new_attendee = clone $attendee;
3191
-        $new_attendee->set('ATT_ID', 0);
3192
-        $new_attendee->save();
3193
-        //add new attendee to reg
3194
-        $registration->_add_relation_to($new_attendee, 'Attendee');
3195
-        EE_Error::add_success(
3196
-            esc_html__(
3197
-                'New Contact record created.  Now make any edits you wish to make for this contact.',
3198
-                'event_espresso'
3199
-            )
3200
-        );
3201
-        //redirect to edit page for attendee
3202
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3203
-        $this->_redirect_after_action('', '', '', $query_args, true);
3204
-    }
3205
-
3206
-
3207
-    //related to cpt routes
3208
-    protected function _insert_update_cpt_item($post_id, $post)
3209
-    {
3210
-        $success  = true;
3211
-        $attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
3212
-        //for attendee updates
3213
-        if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
3214
-            //note we should only be UPDATING attendees at this point.
3215
-            $updated_fields = array(
3216
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
3217
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
3218
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3219
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3220
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3221
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3222
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3223
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3224
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3225
-                'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
3226
-                'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
3227
-            );
3228
-            foreach ($updated_fields as $field => $value) {
3229
-                $attendee->set($field, $value);
3230
-            }
3231
-            $success                   = $attendee->save();
3232
-            $attendee_update_callbacks = apply_filters(
3233
-                'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3234
-                array()
3235
-            );
3236
-            foreach ($attendee_update_callbacks as $a_callback) {
3237
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3238
-                    throw new EE_Error(
3239
-                        sprintf(
3240
-                            esc_html__(
3241
-                                'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3242
-                                'event_espresso'
3243
-                            ),
3244
-                            $a_callback
3245
-                        )
3246
-                    );
3247
-                }
3248
-            }
3249
-        }
3250
-        if ($success === false) {
3251
-            EE_Error::add_error(
3252
-                esc_html__(
3253
-                    'Something went wrong with updating the meta table data for the registration.',
3254
-                    'event_espresso'
3255
-                ),
3256
-                __FILE__, __FUNCTION__, __LINE__
3257
-            );
3258
-        }
3259
-    }
3260
-
3261
-
3262
-    public function trash_cpt_item($post_id)
3263
-    {
3264
-    }
3265
-
3266
-
3267
-    public function delete_cpt_item($post_id)
3268
-    {
3269
-    }
3270
-
3271
-
3272
-    public function restore_cpt_item($post_id)
3273
-    {
3274
-    }
3275
-
3276
-
3277
-    protected function _restore_cpt_item($post_id, $revision_id)
3278
-    {
3279
-    }
3280
-
3281
-
3282
-    public function attendee_editor_metaboxes()
3283
-    {
3284
-        $this->verify_cpt_object();
3285
-        remove_meta_box(
3286
-            'postexcerpt',
3287
-            esc_html__('Excerpt', 'event_espresso'),
3288
-            'post_excerpt_meta_box',
3289
-            $this->_cpt_routes[$this->_req_action],
3290
-            'normal',
3291
-            'core'
3292
-        );
3293
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
3294
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
3295
-            add_meta_box(
3296
-                'postexcerpt',
3297
-                esc_html__('Short Biography', 'event_espresso'),
3298
-                'post_excerpt_meta_box',
3299
-                $this->_cpt_routes[$this->_req_action],
3300
-                'normal'
3301
-            );
3302
-        }
3303
-        if (post_type_supports('espresso_attendees', 'comments')) {
3304
-            add_meta_box(
3305
-                'commentsdiv',
3306
-                esc_html__('Notes on the Contact', 'event_espresso'),
3307
-                'post_comment_meta_box',
3308
-                $this->_cpt_routes[$this->_req_action],
3309
-                'normal',
3310
-                'core'
3311
-            );
3312
-        }
3313
-        add_meta_box(
3314
-            'attendee_contact_info',
3315
-            esc_html__('Contact Info', 'event_espresso'),
3316
-            array($this, 'attendee_contact_info'),
3317
-            $this->_cpt_routes[$this->_req_action],
3318
-            'side',
3319
-            'core'
3320
-        );
3321
-        add_meta_box(
3322
-            'attendee_details_address',
3323
-            esc_html__('Address Details', 'event_espresso'),
3324
-            array($this, 'attendee_address_details'),
3325
-            $this->_cpt_routes[$this->_req_action],
3326
-            'normal',
3327
-            'core'
3328
-        );
3329
-        add_meta_box(
3330
-            'attendee_registrations',
3331
-            esc_html__('Registrations for this Contact', 'event_espresso'),
3332
-            array($this, 'attendee_registrations_meta_box'),
3333
-            $this->_cpt_routes[$this->_req_action],
3334
-            'normal',
3335
-            'high'
3336
-        );
3337
-    }
3338
-
3339
-
3340
-    /**
3341
-     * Metabox for attendee contact info
3342
-     *
3343
-     * @param  WP_Post $post wp post object
3344
-     * @return string attendee contact info ( and form )
3345
-     * @throws DomainException
3346
-     */
3347
-    public function attendee_contact_info($post)
3348
-    {
3349
-        //get attendee object ( should already have it )
3350
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3351
-        $template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
3352
-        EEH_Template::display_template($template, $this->_template_args);
3353
-    }
3354
-
3355
-
3356
-    /**
3357
-     * Metabox for attendee details
3358
-     *
3359
-     * @param  WP_Post $post wp post object
3360
-     * @return string attendee address details (and form)
3361
-     * @throws DomainException
3362
-     */
3363
-    public function attendee_address_details($post)
3364
-    {
3365
-        //get attendee object (should already have it)
3366
-        $this->_template_args['attendee']     = $this->_cpt_model_obj;
3367
-        $this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(
3368
-            new EE_Question_Form_Input(
3369
-                EE_Question::new_instance(
3370
-                    array(
3371
-                        'QST_ID'           => 0,
3372
-                        'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3373
-                        'QST_system'       => 'admin-state',
3374
-                    )
3375
-                ),
3376
-                EE_Answer::new_instance(
3377
-                    array(
3378
-                        'ANS_ID'    => 0,
3379
-                        'ANS_value' => $this->_cpt_model_obj->state_ID(),
3380
-                    )
3381
-                ),
3382
-                array(
3383
-                    'input_id'       => 'STA_ID',
3384
-                    'input_name'     => 'STA_ID',
3385
-                    'input_prefix'   => '',
3386
-                    'append_qstn_id' => false,
3387
-                )
3388
-            )
3389
-        );
3390
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3391
-            new EE_Question_Form_Input(
3392
-                EE_Question::new_instance(
3393
-                    array(
3394
-                        'QST_ID'           => 0,
3395
-                        'QST_display_text' => esc_html__('Country', 'event_espresso'),
3396
-                        'QST_system'       => 'admin-country',
3397
-                    )
3398
-                ),
3399
-                EE_Answer::new_instance(
3400
-                    array(
3401
-                        'ANS_ID'    => 0,
3402
-                        'ANS_value' => $this->_cpt_model_obj->country_ID(),
3403
-                    )
3404
-                ),
3405
-                array(
3406
-                    'input_id'       => 'CNT_ISO',
3407
-                    'input_name'     => 'CNT_ISO',
3408
-                    'input_prefix'   => '',
3409
-                    'append_qstn_id' => false,
3410
-                )
3411
-            )
3412
-        );
3413
-        $template                             =
3414
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3415
-        EEH_Template::display_template($template, $this->_template_args);
3416
-    }
3417
-
3418
-
3419
-    /**
3420
-     *        _attendee_details
3421
-     *
3422
-     * @access protected
3423
-     * @param $post
3424
-     * @return void
3425
-     * @throws DomainException
3426
-     * @throws EE_Error
3427
-     */
3428
-    public function attendee_registrations_meta_box($post)
3429
-    {
3430
-        $this->_template_args['attendee']      = $this->_cpt_model_obj;
3431
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3432
-        $template                              =
3433
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3434
-        EEH_Template::display_template($template, $this->_template_args);
3435
-    }
3436
-
3437
-
3438
-    /**
3439
-     * add in the form fields for the attendee edit
3440
-     *
3441
-     * @param  WP_Post $post wp post object
3442
-     * @return string html for new form.
3443
-     * @throws DomainException
3444
-     */
3445
-    public function after_title_form_fields($post)
3446
-    {
3447
-        if ($post->post_type == 'espresso_attendees') {
3448
-            $template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3449
-            $template_args['attendee'] = $this->_cpt_model_obj;
3450
-            EEH_Template::display_template($template, $template_args);
3451
-        }
3452
-    }
3453
-
3454
-
3455
-    /**
3456
-     *        _trash_or_restore_attendee
3457
-     *
3458
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3459
-     * @return void
3460
-     * @throws EE_Error
3461
-     * @access protected
3462
-     */
3463
-    protected function _trash_or_restore_attendees($trash = true)
3464
-    {
3465
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3466
-        $ATT_MDL = EEM_Attendee::instance();
3467
-        $success = 1;
3468
-        //Checkboxes
3469
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3470
-            // if array has more than one element than success message should be plural
3471
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3472
-            // cycle thru checkboxes
3473
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3474
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3475
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3476
-                if ( ! $updated) {
3477
-                    $success = 0;
3478
-                }
3479
-            }
3480
-        } else {
3481
-            // grab single id and delete
3482
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
3483
-            //get attendee
3484
-            $att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3485
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3486
-            $updated = $att->save();
3487
-            if ( ! $updated) {
3488
-                $success = 0;
3489
-            }
3490
-        }
3491
-        $what        = $success > 1
3492
-            ? esc_html__('Contacts', 'event_espresso')
3493
-            : esc_html__('Contact', 'event_espresso');
3494
-        $action_desc = $trash
3495
-            ? esc_html__('moved to the trash', 'event_espresso')
3496
-            : esc_html__('restored', 'event_espresso');
3497
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3498
-    }
2712
+		}
2713
+		$template_args = array(
2714
+			'title'                    => '',
2715
+			'content'                  => '',
2716
+			'step_button_text'         => '',
2717
+			'show_notification_toggle' => false,
2718
+		);
2719
+		//to indicate we're processing a new registration
2720
+		$hidden_fields = array(
2721
+			'processing_registration' => array(
2722
+				'type'  => 'hidden',
2723
+				'value' => 0,
2724
+			),
2725
+			'event_id'                => array(
2726
+				'type'  => 'hidden',
2727
+				'value' => $this->_reg_event->ID(),
2728
+			),
2729
+		);
2730
+		//if the cart is empty then we know we're at step one so we'll display ticket selector
2731
+		$cart = EE_Registry::instance()->SSN->cart();
2732
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2733
+		switch ($step) {
2734
+			case 'ticket' :
2735
+				$hidden_fields['processing_registration']['value'] = 1;
2736
+				$template_args['title']                            = esc_html__(
2737
+					'Step One: Select the Ticket for this registration',
2738
+					'event_espresso'
2739
+				);
2740
+				$template_args['content']                          =
2741
+					EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2742
+				$template_args['step_button_text']                 = esc_html__(
2743
+					'Add Tickets and Continue to Registrant Details',
2744
+					'event_espresso'
2745
+				);
2746
+				$template_args['show_notification_toggle']         = false;
2747
+				break;
2748
+			case 'questions' :
2749
+				$hidden_fields['processing_registration']['value'] = 2;
2750
+				$template_args['title']                            = esc_html__(
2751
+					'Step Two: Add Registrant Details for this Registration',
2752
+					'event_espresso'
2753
+				);
2754
+				//in theory we should be able to run EED_SPCO at this point because the cart should have been setup
2755
+				// properly by the first process_reg_step run.
2756
+				$template_args['content']                  =
2757
+					EED_Single_Page_Checkout::registration_checkout_for_admin();
2758
+				$template_args['step_button_text']         = esc_html__(
2759
+					'Save Registration and Continue to Details',
2760
+					'event_espresso'
2761
+				);
2762
+				$template_args['show_notification_toggle'] = true;
2763
+				break;
2764
+		}
2765
+		//we come back to the process_registration_step route.
2766
+		$this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
2767
+		return EEH_Template::display_template(
2768
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
2769
+			$template_args,
2770
+			true
2771
+		);
2772
+	}
2773
+
2774
+
2775
+	/**
2776
+	 *        set_reg_event
2777
+	 *
2778
+	 * @access private
2779
+	 * @return bool
2780
+	 * @throws EE_Error
2781
+	 */
2782
+	private function _set_reg_event()
2783
+	{
2784
+		if (is_object($this->_reg_event)) {
2785
+			return true;
2786
+		}
2787
+		$EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2788
+		if ( ! $EVT_ID) {
2789
+			return false;
2790
+		}
2791
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2792
+		return true;
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * process_reg_step
2798
+	 *
2799
+	 * @access        public
2800
+	 * @return string
2801
+	 * @throws DomainException
2802
+	 * @throws EE_Error
2803
+	 * @throws RuntimeException
2804
+	 */
2805
+	public function process_reg_step()
2806
+	{
2807
+		EE_System::do_not_cache();
2808
+		$this->_set_reg_event();
2809
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2810
+		EE_Registry::instance()->REQ->set('uts', time());
2811
+		//what step are we on?
2812
+		$cart = EE_Registry::instance()->SSN->cart();
2813
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2814
+		//if doing ajax then we need to verify the nonce
2815
+		if (defined('DOING_AJAX')) {
2816
+			$nonce = isset($this->_req_data[$this->_req_nonce])
2817
+				? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2818
+			$this->_verify_nonce($nonce, $this->_req_nonce);
2819
+		}
2820
+		switch ($step) {
2821
+			case 'ticket' :
2822
+				//process ticket selection
2823
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
2824
+				if ($success) {
2825
+					EE_Error::add_success(
2826
+						esc_html__(
2827
+							'Tickets Selected. Now complete the registration.',
2828
+							'event_espresso'
2829
+						)
2830
+					);
2831
+				} else {
2832
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
2833
+				}
2834
+				if (defined('DOING_AJAX')) {
2835
+					$this->new_registration(); //display next step
2836
+				} else {
2837
+					$query_args = array(
2838
+						'action'                  => 'new_registration',
2839
+						'processing_registration' => 1,
2840
+						'event_id'                => $this->_reg_event->ID(),
2841
+						'uts'                     => time(),
2842
+					);
2843
+					$this->_redirect_after_action(
2844
+						false,
2845
+						'',
2846
+						'',
2847
+						$query_args,
2848
+						true
2849
+					);
2850
+				}
2851
+				break;
2852
+			case 'questions' :
2853
+				if (! isset(
2854
+					$this->_req_data['txn_reg_status_change'],
2855
+					$this->_req_data['txn_reg_status_change']['send_notifications'])
2856
+				) {
2857
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2858
+				}
2859
+				//process registration
2860
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2861
+				if ($cart instanceof EE_Cart) {
2862
+					$grand_total = $cart->get_cart_grand_total();
2863
+					if ($grand_total instanceof EE_Line_Item) {
2864
+						$grand_total->save_this_and_descendants_to_txn();
2865
+					}
2866
+				}
2867
+				if ( ! $transaction instanceof EE_Transaction) {
2868
+					$query_args = array(
2869
+						'action'                  => 'new_registration',
2870
+						'processing_registration' => 2,
2871
+						'event_id'                => $this->_reg_event->ID(),
2872
+						'uts'                     => time(),
2873
+					);
2874
+					if (defined('DOING_AJAX')) {
2875
+						//display registration form again because there are errors (maybe validation?)
2876
+						$this->new_registration();
2877
+						return;
2878
+					} else {
2879
+						$this->_redirect_after_action(
2880
+							false,
2881
+							'',
2882
+							'',
2883
+							$query_args,
2884
+							true
2885
+						);
2886
+						return;
2887
+					}
2888
+				}
2889
+				// maybe update status, and make sure to save transaction if not done already
2890
+				if ( ! $transaction->update_status_based_on_total_paid()) {
2891
+					$transaction->save();
2892
+				}
2893
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2894
+				$this->_req_data = array();
2895
+				$query_args      = array(
2896
+					'action'        => 'redirect_to_txn',
2897
+					'TXN_ID'        => $transaction->ID(),
2898
+					'EVT_ID'        => $this->_reg_event->ID(),
2899
+					'event_name'    => urlencode($this->_reg_event->name()),
2900
+					'redirect_from' => 'new_registration',
2901
+				);
2902
+				$this->_redirect_after_action(false, '', '', $query_args, true);
2903
+				break;
2904
+		}
2905
+		//what are you looking here for?  Should be nothing to do at this point.
2906
+	}
2907
+
2908
+
2909
+	/**
2910
+	 * redirect_to_txn
2911
+	 *
2912
+	 * @access public
2913
+	 * @return void
2914
+	 * @throws EE_Error
2915
+	 */
2916
+	public function redirect_to_txn()
2917
+	{
2918
+		EE_System::do_not_cache();
2919
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2920
+		$query_args = array(
2921
+			'action' => 'view_transaction',
2922
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2923
+			'page'   => 'espresso_transactions',
2924
+		);
2925
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2926
+			$query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
2927
+			$query_args['event_name']    = urlencode($this->_req_data['event_name']);
2928
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
2929
+		}
2930
+		EE_Error::add_success(
2931
+			esc_html__(
2932
+				'Registration Created.  Please review the transaction and add any payments as necessary',
2933
+				'event_espresso'
2934
+			)
2935
+		);
2936
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2937
+	}
2938
+
2939
+
2940
+	/**
2941
+	 *        generates HTML for the Attendee Contact List
2942
+	 *
2943
+	 * @access protected
2944
+	 * @return void
2945
+	 */
2946
+	protected function _attendee_contact_list_table()
2947
+	{
2948
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2949
+		$this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
2950
+		$this->display_admin_list_table_page_with_no_sidebar();
2951
+	}
2952
+
2953
+
2954
+	/**
2955
+	 *        get_attendees
2956
+	 *
2957
+	 * @param      $per_page
2958
+	 * @param bool $count whether to return count or data.
2959
+	 * @param bool $trash
2960
+	 * @return array
2961
+	 * @throws EE_Error
2962
+	 * @access public
2963
+	 */
2964
+	public function get_attendees($per_page, $count = false, $trash = false)
2965
+	{
2966
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2967
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2968
+		$ATT_MDL                    = EEM_Attendee::instance();
2969
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2970
+		switch ($this->_req_data['orderby']) {
2971
+			case 'ATT_ID':
2972
+				$orderby = 'ATT_ID';
2973
+				break;
2974
+			case 'ATT_fname':
2975
+				$orderby = 'ATT_fname';
2976
+				break;
2977
+			case 'ATT_email':
2978
+				$orderby = 'ATT_email';
2979
+				break;
2980
+			case 'ATT_city':
2981
+				$orderby = 'ATT_city';
2982
+				break;
2983
+			case 'STA_ID':
2984
+				$orderby = 'STA_ID';
2985
+				break;
2986
+			case 'CNT_ID':
2987
+				$orderby = 'CNT_ID';
2988
+				break;
2989
+			default:
2990
+				$orderby = 'ATT_lname';
2991
+		}
2992
+		$sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
2993
+			? $this->_req_data['order']
2994
+			: 'ASC';
2995
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2996
+			? $this->_req_data['paged']
2997
+			: 1;
2998
+		$per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2999
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3000
+			? $this->_req_data['perpage']
3001
+			: $per_page;
3002
+		$_where       = array();
3003
+		if ( ! empty($this->_req_data['s'])) {
3004
+			$sstr         = '%' . $this->_req_data['s'] . '%';
3005
+			$_where['OR'] = array(
3006
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3007
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3008
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3009
+				'ATT_fname'                         => array('LIKE', $sstr),
3010
+				'ATT_lname'                         => array('LIKE', $sstr),
3011
+				'ATT_short_bio'                     => array('LIKE', $sstr),
3012
+				'ATT_email'                         => array('LIKE', $sstr),
3013
+				'ATT_address'                       => array('LIKE', $sstr),
3014
+				'ATT_address2'                      => array('LIKE', $sstr),
3015
+				'ATT_city'                          => array('LIKE', $sstr),
3016
+				'Country.CNT_name'                  => array('LIKE', $sstr),
3017
+				'State.STA_name'                    => array('LIKE', $sstr),
3018
+				'ATT_phone'                         => array('LIKE', $sstr),
3019
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
3020
+				'Registration.REG_code'             => array('LIKE', $sstr),
3021
+				'Registration.REG_count'            => array('LIKE', $sstr),
3022
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
3023
+			);
3024
+		}
3025
+		$offset = ($current_page - 1) * $per_page;
3026
+		$limit  = $count ? null : array($offset, $per_page);
3027
+		if ($trash) {
3028
+			$_where['status'] = array('!=', 'publish');
3029
+			$all_attendees    = $count
3030
+				? $ATT_MDL->count(array(
3031
+					$_where,
3032
+					'order_by' => array($orderby => $sort),
3033
+					'limit'    => $limit,
3034
+				), 'ATT_ID', true)
3035
+				: $ATT_MDL->get_all(array(
3036
+					$_where,
3037
+					'order_by' => array($orderby => $sort),
3038
+					'limit'    => $limit,
3039
+				));
3040
+		} else {
3041
+			$_where['status'] = array('IN', array('publish'));
3042
+			$all_attendees    = $count
3043
+				? $ATT_MDL->count(array(
3044
+					$_where,
3045
+					'order_by' => array($orderby => $sort),
3046
+					'limit'    => $limit,
3047
+				), 'ATT_ID', true)
3048
+				: $ATT_MDL->get_all(array(
3049
+					$_where,
3050
+					'order_by' => array($orderby => $sort),
3051
+					'limit'    => $limit,
3052
+				));
3053
+		}
3054
+		return $all_attendees;
3055
+	}
3056
+
3057
+
3058
+	/**
3059
+	 * This is just taking care of resending the registration confirmation
3060
+	 *
3061
+	 * @access protected
3062
+	 * @return void
3063
+	 */
3064
+	protected function _resend_registration()
3065
+	{
3066
+		$this->_process_resend_registration();
3067
+		$query_args = isset($this->_req_data['redirect_to'])
3068
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3069
+			: array('action' => 'default');
3070
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3071
+	}
3072
+
3073
+	/**
3074
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3075
+	 * to use when selecting registrations
3076
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3077
+	 *                                                     the query parameters from the request
3078
+	 * @return void ends the request with a redirect or download
3079
+	 */
3080
+	public function _registrations_report_base( $method_name_for_getting_query_params )
3081
+	{
3082
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3083
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(
3084
+				array(
3085
+					'page'        => 'espresso_batch',
3086
+					'batch'       => 'file',
3087
+					'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3088
+					'filters'     => urlencode(
3089
+						serialize(
3090
+							call_user_func(
3091
+								array( $this, $method_name_for_getting_query_params ),
3092
+								EEH_Array::is_set(
3093
+									$this->_req_data,
3094
+									'filters',
3095
+									array()
3096
+								)
3097
+							)
3098
+						)
3099
+				),
3100
+				'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3101
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3102
+				'return_url'  => urlencode($this->_req_data['return_url']),
3103
+			)));
3104
+		} else {
3105
+			$new_request_args = array(
3106
+				'export' => 'report',
3107
+				'action' => 'registrations_report_for_event',
3108
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3109
+			);
3110
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
3111
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3112
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3113
+				$EE_Export = EE_Export::instance($this->_req_data);
3114
+				$EE_Export->export();
3115
+			}
3116
+		}
3117
+	}
3118
+
3119
+
3120
+
3121
+	/**
3122
+	 * Creates a registration report using only query parameters in the request
3123
+	 * @return void
3124
+	 */
3125
+	public function _registrations_report()
3126
+	{
3127
+		$this->_registrations_report_base('_get_registration_query_parameters');
3128
+	}
3129
+
3130
+
3131
+	public function _contact_list_export()
3132
+	{
3133
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3134
+			require_once(EE_CLASSES . 'EE_Export.class.php');
3135
+			$EE_Export = EE_Export::instance($this->_req_data);
3136
+			$EE_Export->export_attendees();
3137
+		}
3138
+	}
3139
+
3140
+
3141
+	public function _contact_list_report()
3142
+	{
3143
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3144
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
3145
+				'page'        => 'espresso_batch',
3146
+				'batch'       => 'file',
3147
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3148
+				'return_url'  => urlencode($this->_req_data['return_url']),
3149
+			)));
3150
+		} else {
3151
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3152
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3153
+				$EE_Export = EE_Export::instance($this->_req_data);
3154
+				$EE_Export->report_attendees();
3155
+			}
3156
+		}
3157
+	}
3158
+
3159
+
3160
+
3161
+
3162
+
3163
+	/***************************************        ATTENDEE DETAILS        ***************************************/
3164
+	/**
3165
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
3166
+	 *
3167
+	 * @return void
3168
+	 * @throws EE_Error
3169
+	 */
3170
+	protected function _duplicate_attendee()
3171
+	{
3172
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3173
+		//verify we have necessary info
3174
+		if (empty($this->_req_data['_REG_ID'])) {
3175
+			EE_Error::add_error(
3176
+				esc_html__(
3177
+					'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3178
+					'event_espresso'
3179
+				), __FILE__, __LINE__, __FUNCTION__
3180
+			);
3181
+			$query_args = array('action' => $action);
3182
+			$this->_redirect_after_action('', '', '', $query_args, true);
3183
+		}
3184
+		//okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3185
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3186
+		$attendee     = $registration->attendee();
3187
+		//remove relation of existing attendee on registration
3188
+		$registration->_remove_relation_to($attendee, 'Attendee');
3189
+		//new attendee
3190
+		$new_attendee = clone $attendee;
3191
+		$new_attendee->set('ATT_ID', 0);
3192
+		$new_attendee->save();
3193
+		//add new attendee to reg
3194
+		$registration->_add_relation_to($new_attendee, 'Attendee');
3195
+		EE_Error::add_success(
3196
+			esc_html__(
3197
+				'New Contact record created.  Now make any edits you wish to make for this contact.',
3198
+				'event_espresso'
3199
+			)
3200
+		);
3201
+		//redirect to edit page for attendee
3202
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3203
+		$this->_redirect_after_action('', '', '', $query_args, true);
3204
+	}
3205
+
3206
+
3207
+	//related to cpt routes
3208
+	protected function _insert_update_cpt_item($post_id, $post)
3209
+	{
3210
+		$success  = true;
3211
+		$attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
3212
+		//for attendee updates
3213
+		if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
3214
+			//note we should only be UPDATING attendees at this point.
3215
+			$updated_fields = array(
3216
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
3217
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
3218
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3219
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3220
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3221
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3222
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3223
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3224
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3225
+				'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
3226
+				'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
3227
+			);
3228
+			foreach ($updated_fields as $field => $value) {
3229
+				$attendee->set($field, $value);
3230
+			}
3231
+			$success                   = $attendee->save();
3232
+			$attendee_update_callbacks = apply_filters(
3233
+				'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3234
+				array()
3235
+			);
3236
+			foreach ($attendee_update_callbacks as $a_callback) {
3237
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3238
+					throw new EE_Error(
3239
+						sprintf(
3240
+							esc_html__(
3241
+								'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3242
+								'event_espresso'
3243
+							),
3244
+							$a_callback
3245
+						)
3246
+					);
3247
+				}
3248
+			}
3249
+		}
3250
+		if ($success === false) {
3251
+			EE_Error::add_error(
3252
+				esc_html__(
3253
+					'Something went wrong with updating the meta table data for the registration.',
3254
+					'event_espresso'
3255
+				),
3256
+				__FILE__, __FUNCTION__, __LINE__
3257
+			);
3258
+		}
3259
+	}
3260
+
3261
+
3262
+	public function trash_cpt_item($post_id)
3263
+	{
3264
+	}
3265
+
3266
+
3267
+	public function delete_cpt_item($post_id)
3268
+	{
3269
+	}
3270
+
3271
+
3272
+	public function restore_cpt_item($post_id)
3273
+	{
3274
+	}
3275
+
3276
+
3277
+	protected function _restore_cpt_item($post_id, $revision_id)
3278
+	{
3279
+	}
3280
+
3281
+
3282
+	public function attendee_editor_metaboxes()
3283
+	{
3284
+		$this->verify_cpt_object();
3285
+		remove_meta_box(
3286
+			'postexcerpt',
3287
+			esc_html__('Excerpt', 'event_espresso'),
3288
+			'post_excerpt_meta_box',
3289
+			$this->_cpt_routes[$this->_req_action],
3290
+			'normal',
3291
+			'core'
3292
+		);
3293
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
3294
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
3295
+			add_meta_box(
3296
+				'postexcerpt',
3297
+				esc_html__('Short Biography', 'event_espresso'),
3298
+				'post_excerpt_meta_box',
3299
+				$this->_cpt_routes[$this->_req_action],
3300
+				'normal'
3301
+			);
3302
+		}
3303
+		if (post_type_supports('espresso_attendees', 'comments')) {
3304
+			add_meta_box(
3305
+				'commentsdiv',
3306
+				esc_html__('Notes on the Contact', 'event_espresso'),
3307
+				'post_comment_meta_box',
3308
+				$this->_cpt_routes[$this->_req_action],
3309
+				'normal',
3310
+				'core'
3311
+			);
3312
+		}
3313
+		add_meta_box(
3314
+			'attendee_contact_info',
3315
+			esc_html__('Contact Info', 'event_espresso'),
3316
+			array($this, 'attendee_contact_info'),
3317
+			$this->_cpt_routes[$this->_req_action],
3318
+			'side',
3319
+			'core'
3320
+		);
3321
+		add_meta_box(
3322
+			'attendee_details_address',
3323
+			esc_html__('Address Details', 'event_espresso'),
3324
+			array($this, 'attendee_address_details'),
3325
+			$this->_cpt_routes[$this->_req_action],
3326
+			'normal',
3327
+			'core'
3328
+		);
3329
+		add_meta_box(
3330
+			'attendee_registrations',
3331
+			esc_html__('Registrations for this Contact', 'event_espresso'),
3332
+			array($this, 'attendee_registrations_meta_box'),
3333
+			$this->_cpt_routes[$this->_req_action],
3334
+			'normal',
3335
+			'high'
3336
+		);
3337
+	}
3338
+
3339
+
3340
+	/**
3341
+	 * Metabox for attendee contact info
3342
+	 *
3343
+	 * @param  WP_Post $post wp post object
3344
+	 * @return string attendee contact info ( and form )
3345
+	 * @throws DomainException
3346
+	 */
3347
+	public function attendee_contact_info($post)
3348
+	{
3349
+		//get attendee object ( should already have it )
3350
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3351
+		$template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
3352
+		EEH_Template::display_template($template, $this->_template_args);
3353
+	}
3354
+
3355
+
3356
+	/**
3357
+	 * Metabox for attendee details
3358
+	 *
3359
+	 * @param  WP_Post $post wp post object
3360
+	 * @return string attendee address details (and form)
3361
+	 * @throws DomainException
3362
+	 */
3363
+	public function attendee_address_details($post)
3364
+	{
3365
+		//get attendee object (should already have it)
3366
+		$this->_template_args['attendee']     = $this->_cpt_model_obj;
3367
+		$this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(
3368
+			new EE_Question_Form_Input(
3369
+				EE_Question::new_instance(
3370
+					array(
3371
+						'QST_ID'           => 0,
3372
+						'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3373
+						'QST_system'       => 'admin-state',
3374
+					)
3375
+				),
3376
+				EE_Answer::new_instance(
3377
+					array(
3378
+						'ANS_ID'    => 0,
3379
+						'ANS_value' => $this->_cpt_model_obj->state_ID(),
3380
+					)
3381
+				),
3382
+				array(
3383
+					'input_id'       => 'STA_ID',
3384
+					'input_name'     => 'STA_ID',
3385
+					'input_prefix'   => '',
3386
+					'append_qstn_id' => false,
3387
+				)
3388
+			)
3389
+		);
3390
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3391
+			new EE_Question_Form_Input(
3392
+				EE_Question::new_instance(
3393
+					array(
3394
+						'QST_ID'           => 0,
3395
+						'QST_display_text' => esc_html__('Country', 'event_espresso'),
3396
+						'QST_system'       => 'admin-country',
3397
+					)
3398
+				),
3399
+				EE_Answer::new_instance(
3400
+					array(
3401
+						'ANS_ID'    => 0,
3402
+						'ANS_value' => $this->_cpt_model_obj->country_ID(),
3403
+					)
3404
+				),
3405
+				array(
3406
+					'input_id'       => 'CNT_ISO',
3407
+					'input_name'     => 'CNT_ISO',
3408
+					'input_prefix'   => '',
3409
+					'append_qstn_id' => false,
3410
+				)
3411
+			)
3412
+		);
3413
+		$template                             =
3414
+			REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3415
+		EEH_Template::display_template($template, $this->_template_args);
3416
+	}
3417
+
3418
+
3419
+	/**
3420
+	 *        _attendee_details
3421
+	 *
3422
+	 * @access protected
3423
+	 * @param $post
3424
+	 * @return void
3425
+	 * @throws DomainException
3426
+	 * @throws EE_Error
3427
+	 */
3428
+	public function attendee_registrations_meta_box($post)
3429
+	{
3430
+		$this->_template_args['attendee']      = $this->_cpt_model_obj;
3431
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3432
+		$template                              =
3433
+			REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3434
+		EEH_Template::display_template($template, $this->_template_args);
3435
+	}
3436
+
3437
+
3438
+	/**
3439
+	 * add in the form fields for the attendee edit
3440
+	 *
3441
+	 * @param  WP_Post $post wp post object
3442
+	 * @return string html for new form.
3443
+	 * @throws DomainException
3444
+	 */
3445
+	public function after_title_form_fields($post)
3446
+	{
3447
+		if ($post->post_type == 'espresso_attendees') {
3448
+			$template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3449
+			$template_args['attendee'] = $this->_cpt_model_obj;
3450
+			EEH_Template::display_template($template, $template_args);
3451
+		}
3452
+	}
3453
+
3454
+
3455
+	/**
3456
+	 *        _trash_or_restore_attendee
3457
+	 *
3458
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3459
+	 * @return void
3460
+	 * @throws EE_Error
3461
+	 * @access protected
3462
+	 */
3463
+	protected function _trash_or_restore_attendees($trash = true)
3464
+	{
3465
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3466
+		$ATT_MDL = EEM_Attendee::instance();
3467
+		$success = 1;
3468
+		//Checkboxes
3469
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3470
+			// if array has more than one element than success message should be plural
3471
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3472
+			// cycle thru checkboxes
3473
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3474
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3475
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3476
+				if ( ! $updated) {
3477
+					$success = 0;
3478
+				}
3479
+			}
3480
+		} else {
3481
+			// grab single id and delete
3482
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
3483
+			//get attendee
3484
+			$att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3485
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3486
+			$updated = $att->save();
3487
+			if ( ! $updated) {
3488
+				$success = 0;
3489
+			}
3490
+		}
3491
+		$what        = $success > 1
3492
+			? esc_html__('Contacts', 'event_espresso')
3493
+			: esc_html__('Contact', 'event_espresso');
3494
+		$action_desc = $trash
3495
+			? esc_html__('moved to the trash', 'event_espresso')
3496
+			: esc_html__('restored', 'event_espresso');
3497
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3498
+	}
3499 3499
 
3500 3500
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.021');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.021');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
core/services/loaders/CachingLoader.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -99,23 +99,23 @@
 block discarded – undo
99 99
         $fqcn = ltrim($fqcn, '\\');
100 100
         // caching can be turned off via the following code:
101 101
         // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
102
-        if(
102
+        if (
103 103
             apply_filters(
104 104
                 'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
105 105
                 false,
106 106
                 $this
107 107
             )
108
-        ){
108
+        ) {
109 109
             // even though $shared might be true, caching should be bypassed for whatever reason,
110 110
             // so we don't want the core loader to cache anything, therefore caching is turned off
111 111
             return $this->loader->load($fqcn, $arguments, false);
112 112
         }
113
-        $identifier = md5($fqcn . serialize($arguments));
114
-        if($this->cache->has($identifier)){
113
+        $identifier = md5($fqcn.serialize($arguments));
114
+        if ($this->cache->has($identifier)) {
115 115
             return $this->cache->get($identifier);
116 116
         }
117 117
         $object = $this->loader->load($fqcn, $arguments, $shared);
118
-        if($object instanceof $fqcn){
118
+        if ($object instanceof $fqcn) {
119 119
             $this->cache->add($object, $identifier);
120 120
         }
121 121
         return $object;
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -20,117 +20,117 @@
 block discarded – undo
20 20
 class CachingLoader extends LoaderDecorator
21 21
 {
22 22
 
23
-    /**
24
-     * @var CollectionInterface $cache
25
-     */
26
-    protected $cache;
27
-
28
-    /**
29
-     * @var string $identifier
30
-     */
31
-    protected $identifier;
32
-
33
-
34
-
35
-    /**
36
-     * CachingLoader constructor.
37
-     *
38
-     * @param LoaderDecoratorInterface $loader
39
-     * @param CollectionInterface      $cache
40
-     * @param string                   $identifier
41
-     * @throws InvalidDataTypeException
42
-     */
43
-    public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
44
-    {
45
-        parent::__construct($loader);
46
-        $this->cache = $cache;
47
-        $this->setIdentifier($identifier);
48
-        if ($this->identifier !== '') {
49
-            // to only clear this cache, and assuming an identifier has been set, simply do the following:
50
-            // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
51
-            // where "IDENTIFIER" = the string that was set during construction
52
-            add_action(
53
-                "AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
54
-                array($this, 'reset')
55
-            );
56
-        }
57
-        // to clear ALL caches, simply do the following:
58
-        // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
59
-        add_action(
60
-            'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
61
-            array($this, 'reset')
62
-        );
63
-    }
64
-
65
-
66
-
67
-    /**
68
-     * @return string
69
-     */
70
-    public function identifier()
71
-    {
72
-        return $this->identifier;
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     * @param string $identifier
79
-     * @throws InvalidDataTypeException
80
-     */
81
-    private function setIdentifier($identifier)
82
-    {
83
-        if ( ! is_string($identifier)) {
84
-            throw new InvalidDataTypeException('$identifier', $identifier, 'string');
85
-        }
86
-        $this->identifier = $identifier;
87
-    }
88
-
89
-
90
-
91
-    /**
92
-     * @param string $fqcn
93
-     * @param array  $arguments
94
-     * @param bool   $shared
95
-     * @return mixed
96
-     */
97
-    public function load($fqcn, $arguments = array(), $shared = true)
98
-    {
99
-        $fqcn = ltrim($fqcn, '\\');
100
-        // caching can be turned off via the following code:
101
-        // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
102
-        if(
103
-            apply_filters(
104
-                'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
105
-                false,
106
-                $this
107
-            )
108
-        ){
109
-            // even though $shared might be true, caching should be bypassed for whatever reason,
110
-            // so we don't want the core loader to cache anything, therefore caching is turned off
111
-            return $this->loader->load($fqcn, $arguments, false);
112
-        }
113
-        $identifier = md5($fqcn . serialize($arguments));
114
-        if($this->cache->has($identifier)){
115
-            return $this->cache->get($identifier);
116
-        }
117
-        $object = $this->loader->load($fqcn, $arguments, $shared);
118
-        if($object instanceof $fqcn){
119
-            $this->cache->add($object, $identifier);
120
-        }
121
-        return $object;
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * empties cache and calls reset() on loader if method exists
128
-     */
129
-    public function reset()
130
-    {
131
-        $this->cache->trashAndDetachAll();
132
-        $this->loader->reset();
133
-    }
23
+	/**
24
+	 * @var CollectionInterface $cache
25
+	 */
26
+	protected $cache;
27
+
28
+	/**
29
+	 * @var string $identifier
30
+	 */
31
+	protected $identifier;
32
+
33
+
34
+
35
+	/**
36
+	 * CachingLoader constructor.
37
+	 *
38
+	 * @param LoaderDecoratorInterface $loader
39
+	 * @param CollectionInterface      $cache
40
+	 * @param string                   $identifier
41
+	 * @throws InvalidDataTypeException
42
+	 */
43
+	public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
44
+	{
45
+		parent::__construct($loader);
46
+		$this->cache = $cache;
47
+		$this->setIdentifier($identifier);
48
+		if ($this->identifier !== '') {
49
+			// to only clear this cache, and assuming an identifier has been set, simply do the following:
50
+			// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
51
+			// where "IDENTIFIER" = the string that was set during construction
52
+			add_action(
53
+				"AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
54
+				array($this, 'reset')
55
+			);
56
+		}
57
+		// to clear ALL caches, simply do the following:
58
+		// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
59
+		add_action(
60
+			'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
61
+			array($this, 'reset')
62
+		);
63
+	}
64
+
65
+
66
+
67
+	/**
68
+	 * @return string
69
+	 */
70
+	public function identifier()
71
+	{
72
+		return $this->identifier;
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 * @param string $identifier
79
+	 * @throws InvalidDataTypeException
80
+	 */
81
+	private function setIdentifier($identifier)
82
+	{
83
+		if ( ! is_string($identifier)) {
84
+			throw new InvalidDataTypeException('$identifier', $identifier, 'string');
85
+		}
86
+		$this->identifier = $identifier;
87
+	}
88
+
89
+
90
+
91
+	/**
92
+	 * @param string $fqcn
93
+	 * @param array  $arguments
94
+	 * @param bool   $shared
95
+	 * @return mixed
96
+	 */
97
+	public function load($fqcn, $arguments = array(), $shared = true)
98
+	{
99
+		$fqcn = ltrim($fqcn, '\\');
100
+		// caching can be turned off via the following code:
101
+		// add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
102
+		if(
103
+			apply_filters(
104
+				'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
105
+				false,
106
+				$this
107
+			)
108
+		){
109
+			// even though $shared might be true, caching should be bypassed for whatever reason,
110
+			// so we don't want the core loader to cache anything, therefore caching is turned off
111
+			return $this->loader->load($fqcn, $arguments, false);
112
+		}
113
+		$identifier = md5($fqcn . serialize($arguments));
114
+		if($this->cache->has($identifier)){
115
+			return $this->cache->get($identifier);
116
+		}
117
+		$object = $this->loader->load($fqcn, $arguments, $shared);
118
+		if($object instanceof $fqcn){
119
+			$this->cache->add($object, $identifier);
120
+		}
121
+		return $object;
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * empties cache and calls reset() on loader if method exists
128
+	 */
129
+	public function reset()
130
+	{
131
+		$this->cache->trashAndDetachAll();
132
+		$this->loader->reset();
133
+	}
134 134
 
135 135
 
136 136
 }
Please login to merge, or discard this patch.
core/services/loaders/CoreLoader.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -26,68 +26,68 @@
 block discarded – undo
26 26
 class CoreLoader implements LoaderDecoratorInterface
27 27
 {
28 28
 
29
-    /**
30
-     * @var EE_Registry|CoffeeShop $generator
31
-     */
32
-    private $generator;
33
-
34
-
35
-
36
-    /**
37
-     * CoreLoader constructor.
38
-     *
39
-     * @param EE_Registry|CoffeeShop $generator
40
-     * @throws InvalidArgumentException
41
-     */
42
-    public function __construct($generator)
43
-    {
44
-        if(!($generator instanceof EE_Registry || $generator instanceof CoffeeShop)) {
45
-            throw new InvalidArgumentException(
46
-                esc_html__(
47
-                    'The CoreLoader class must receive an instance of EE_Registry or the CoffeeShop DI container.',
48
-                    'event_espresso'
49
-                )
50
-            );
51
-        }
52
-        $this->generator = $generator;
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * @param string $fqcn
59
-     * @param array  $arguments
60
-     * @param bool   $shared
61
-     * @return mixed
62
-     * @throws EE_Error
63
-     * @throws ServiceNotFoundException
64
-     * @throws ReflectionException
65
-     */
66
-    public function load($fqcn, $arguments = array(), $shared = true)
67
-    {
68
-        if ($this->generator instanceof EE_Registry) {
69
-            return $this->generator->create($fqcn, $arguments, $shared);
70
-        }
71
-        $shared = $shared
72
-            ? CoffeeMaker::BREW_SHARED
73
-            : CoffeeMaker::BREW_NEW;
74
-        return $this->generator->brew($fqcn, $arguments, $shared);
75
-    }
76
-
77
-
78
-
79
-    /**
80
-     * calls reset() on generator if method exists
81
-     *
82
-     * @throws EE_Error
83
-     * @throws ReflectionException
84
-     */
85
-    public function reset()
86
-    {
87
-        if (method_exists($this->generator, 'reset')) {
88
-            $this->generator->reset();
89
-        }
90
-    }
29
+	/**
30
+	 * @var EE_Registry|CoffeeShop $generator
31
+	 */
32
+	private $generator;
33
+
34
+
35
+
36
+	/**
37
+	 * CoreLoader constructor.
38
+	 *
39
+	 * @param EE_Registry|CoffeeShop $generator
40
+	 * @throws InvalidArgumentException
41
+	 */
42
+	public function __construct($generator)
43
+	{
44
+		if(!($generator instanceof EE_Registry || $generator instanceof CoffeeShop)) {
45
+			throw new InvalidArgumentException(
46
+				esc_html__(
47
+					'The CoreLoader class must receive an instance of EE_Registry or the CoffeeShop DI container.',
48
+					'event_espresso'
49
+				)
50
+			);
51
+		}
52
+		$this->generator = $generator;
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * @param string $fqcn
59
+	 * @param array  $arguments
60
+	 * @param bool   $shared
61
+	 * @return mixed
62
+	 * @throws EE_Error
63
+	 * @throws ServiceNotFoundException
64
+	 * @throws ReflectionException
65
+	 */
66
+	public function load($fqcn, $arguments = array(), $shared = true)
67
+	{
68
+		if ($this->generator instanceof EE_Registry) {
69
+			return $this->generator->create($fqcn, $arguments, $shared);
70
+		}
71
+		$shared = $shared
72
+			? CoffeeMaker::BREW_SHARED
73
+			: CoffeeMaker::BREW_NEW;
74
+		return $this->generator->brew($fqcn, $arguments, $shared);
75
+	}
76
+
77
+
78
+
79
+	/**
80
+	 * calls reset() on generator if method exists
81
+	 *
82
+	 * @throws EE_Error
83
+	 * @throws ReflectionException
84
+	 */
85
+	public function reset()
86
+	{
87
+		if (method_exists($this->generator, 'reset')) {
88
+			$this->generator->reset();
89
+		}
90
+	}
91 91
 
92 92
 }
93 93
 // End of file CoreLoader.php
Please login to merge, or discard this patch.
core/services/loaders/LoaderDecoratorInterface.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -9,20 +9,20 @@
 block discarded – undo
9 9
 interface LoaderDecoratorInterface
10 10
 {
11 11
 
12
-    /**
13
-     * @param string $fqcn
14
-     * @param array  $arguments
15
-     * @param bool   $shared
16
-     * @return mixed
17
-     */
18
-    public function load($fqcn, $arguments = array(), $shared = true);
12
+	/**
13
+	 * @param string $fqcn
14
+	 * @param array  $arguments
15
+	 * @param bool   $shared
16
+	 * @return mixed
17
+	 */
18
+	public function load($fqcn, $arguments = array(), $shared = true);
19 19
 
20 20
 
21 21
 
22
-    /**
23
-     * calls reset() on loader if method exists
24
-     */
25
-    public function reset();
22
+	/**
23
+	 * calls reset() on loader if method exists
24
+	 */
25
+	public function reset();
26 26
 
27 27
 }
28 28
 // End of file LoaderInterface.php
Please login to merge, or discard this patch.
core/services/loaders/Loader.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -22,103 +22,103 @@
 block discarded – undo
22 22
 {
23 23
 
24 24
 
25
-    /**
26
-     * @var LoaderDecoratorInterface $new_loader
27
-     */
28
-    private $new_loader;
29
-
30
-
31
-    /**
32
-     * @var LoaderDecoratorInterface $shared_loader
33
-     */
34
-    private $shared_loader;
35
-
36
-
37
-
38
-    /**
39
-     * Loader constructor.
40
-     *
41
-     * @param LoaderDecoratorInterface|null $new_loader
42
-     * @param LoaderDecoratorInterface|null $shared_loader
43
-     * @throws InvalidInterfaceException
44
-     * @throws InvalidArgumentException
45
-     * @throws InvalidDataTypeException
46
-     */
47
-    public function __construct(LoaderDecoratorInterface $new_loader, LoaderDecoratorInterface $shared_loader)
48
-    {
49
-        $this->new_loader = $new_loader;
50
-        $this->shared_loader = $shared_loader;
51
-    }
52
-
53
-
54
-
55
-    /**
56
-     * @return LoaderDecoratorInterface
57
-     */
58
-    public function getNewLoader()
59
-    {
60
-        return $this->new_loader;
61
-    }
62
-
63
-
64
-
65
-    /**
66
-     * @return LoaderDecoratorInterface
67
-     */
68
-    public function getSharedLoader()
69
-    {
70
-        return $this->shared_loader;
71
-    }
72
-
73
-
74
-
75
-    /**
76
-     * @param string $fqcn
77
-     * @param array  $arguments
78
-     * @param bool   $shared
79
-     * @return mixed
80
-     */
81
-    public function load($fqcn, $arguments = array(), $shared = true)
82
-    {
83
-        return $shared
84
-            ? $this->getSharedLoader()->load($fqcn, $arguments)
85
-            : $this->getNewLoader()->load($fqcn, $arguments, false);
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * @param string $fqcn
92
-     * @param array  $arguments
93
-     * @return mixed
94
-     */
95
-    public function getNew($fqcn, $arguments = array())
96
-    {
97
-        return $this->getNewLoader()->load($fqcn, $arguments, false);
98
-    }
99
-
100
-
101
-
102
-    /**
103
-     * @param string $fqcn
104
-     * @param array  $arguments
105
-     * @return mixed
106
-     */
107
-    public function getShared($fqcn, $arguments = array())
108
-    {
109
-        return $this->getSharedLoader()->load($fqcn, $arguments);
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * calls reset() on loaders if that method exists
116
-     */
117
-    public function reset()
118
-    {
119
-        $this->new_loader->reset();
120
-        $this->shared_loader->reset();
121
-    }
25
+	/**
26
+	 * @var LoaderDecoratorInterface $new_loader
27
+	 */
28
+	private $new_loader;
29
+
30
+
31
+	/**
32
+	 * @var LoaderDecoratorInterface $shared_loader
33
+	 */
34
+	private $shared_loader;
35
+
36
+
37
+
38
+	/**
39
+	 * Loader constructor.
40
+	 *
41
+	 * @param LoaderDecoratorInterface|null $new_loader
42
+	 * @param LoaderDecoratorInterface|null $shared_loader
43
+	 * @throws InvalidInterfaceException
44
+	 * @throws InvalidArgumentException
45
+	 * @throws InvalidDataTypeException
46
+	 */
47
+	public function __construct(LoaderDecoratorInterface $new_loader, LoaderDecoratorInterface $shared_loader)
48
+	{
49
+		$this->new_loader = $new_loader;
50
+		$this->shared_loader = $shared_loader;
51
+	}
52
+
53
+
54
+
55
+	/**
56
+	 * @return LoaderDecoratorInterface
57
+	 */
58
+	public function getNewLoader()
59
+	{
60
+		return $this->new_loader;
61
+	}
62
+
63
+
64
+
65
+	/**
66
+	 * @return LoaderDecoratorInterface
67
+	 */
68
+	public function getSharedLoader()
69
+	{
70
+		return $this->shared_loader;
71
+	}
72
+
73
+
74
+
75
+	/**
76
+	 * @param string $fqcn
77
+	 * @param array  $arguments
78
+	 * @param bool   $shared
79
+	 * @return mixed
80
+	 */
81
+	public function load($fqcn, $arguments = array(), $shared = true)
82
+	{
83
+		return $shared
84
+			? $this->getSharedLoader()->load($fqcn, $arguments)
85
+			: $this->getNewLoader()->load($fqcn, $arguments, false);
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * @param string $fqcn
92
+	 * @param array  $arguments
93
+	 * @return mixed
94
+	 */
95
+	public function getNew($fqcn, $arguments = array())
96
+	{
97
+		return $this->getNewLoader()->load($fqcn, $arguments, false);
98
+	}
99
+
100
+
101
+
102
+	/**
103
+	 * @param string $fqcn
104
+	 * @param array  $arguments
105
+	 * @return mixed
106
+	 */
107
+	public function getShared($fqcn, $arguments = array())
108
+	{
109
+		return $this->getSharedLoader()->load($fqcn, $arguments);
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * calls reset() on loaders if that method exists
116
+	 */
117
+	public function reset()
118
+	{
119
+		$this->new_loader->reset();
120
+		$this->shared_loader->reset();
121
+	}
122 122
 
123 123
 }
124 124
 // End of file Loader.php
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +16 added lines, -14 removed lines patch added patch discarded remove patch
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 
703 703
 
704 704
     /**
705
-     * @param $model_field_factory
705
+     * @param null|ModelFieldFactory $model_field_factory
706 706
      * @return ModelFieldFactory
707 707
      * @throws InvalidArgumentException
708 708
      * @throws InvalidDataTypeException
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
982 982
      * foreign key to the WP_User table)
983 983
      *
984
-     * @return string|boolean string on success, boolean false when there is no
984
+     * @return string|false string on success, boolean false when there is no
985 985
      * foreign key to the WP_User table
986 986
      */
987 987
     public function wp_user_field_name()
@@ -1086,7 +1086,7 @@  discard block
 block discarded – undo
1086 1086
      *
1087 1087
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1088 1088
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1089
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1089
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1090 1090
      *                                  fields on the model, and the models we joined to in the query. However, you can
1091 1091
      *                                  override this and set the select to "*", or a specific column name, like
1092 1092
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1500,7 +1500,7 @@  discard block
 block discarded – undo
1500 1500
      * @param string $field_name The name of the field the formats are being retrieved for.
1501 1501
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1502 1502
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1503
-     * @return array formats in an array with the date format first, and the time format last.
1503
+     * @return string[] formats in an array with the date format first, and the time format last.
1504 1504
      */
1505 1505
     public function get_formats_for($field_name, $pretty = false)
1506 1506
     {
@@ -1535,7 +1535,7 @@  discard block
 block discarded – undo
1535 1535
      *                                 be returned.
1536 1536
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1537 1537
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1538
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1538
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1539 1539
      *                                 exception is triggered.
1540 1540
      */
1541 1541
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1575,7 +1575,7 @@  discard block
 block discarded – undo
1575 1575
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1576 1576
      *                                format is
1577 1577
      *                                'U', this is ignored.
1578
-     * @return DateTime
1578
+     * @return string
1579 1579
      * @throws EE_Error
1580 1580
      */
1581 1581
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2440,7 +2440,7 @@  discard block
 block discarded – undo
2440 2440
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2441 2441
      * EEM_Base::$_db_verification_level
2442 2442
      *
2443
-     * @param $wpdb_method
2443
+     * @param string $wpdb_method
2444 2444
      * @param $arguments_to_provide
2445 2445
      * @return string
2446 2446
      */
@@ -2564,6 +2564,7 @@  discard block
 block discarded – undo
2564 2564
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565 2565
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566 2566
      *                             because these will be inserted in any new rows created as well.
2567
+     * @param EE_Base_Class $id_or_obj
2567 2568
      */
2568 2569
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569 2570
     {
@@ -2574,7 +2575,7 @@  discard block
 block discarded – undo
2574 2575
 
2575 2576
 
2576 2577
     /**
2577
-     * @param mixed           $id_or_obj
2578
+     * @param EE_Base_Class           $id_or_obj
2578 2579
      * @param string          $relationName
2579 2580
      * @param array           $where_query_params
2580 2581
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2615,7 +2616,7 @@  discard block
 block discarded – undo
2615 2616
      * However, if the model objects can't be deleted because of blocking related model objects, then
2616 2617
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617 2618
      *
2618
-     * @param EE_Base_Class|int|string $id_or_obj
2619
+     * @param EE_Base_Class $id_or_obj
2619 2620
      * @param string                   $model_name
2620 2621
      * @param array                    $query_params
2621 2622
      * @return int how many deleted
@@ -2636,7 +2637,7 @@  discard block
 block discarded – undo
2636 2637
      * the model objects can't be hard deleted because of blocking related model objects,
2637 2638
      * just does a soft-delete on them instead.
2638 2639
      *
2639
-     * @param EE_Base_Class|int|string $id_or_obj
2640
+     * @param EE_Base_Class $id_or_obj
2640 2641
      * @param string                   $model_name
2641 2642
      * @param array                    $query_params
2642 2643
      * @return int how many deleted
@@ -2693,6 +2694,7 @@  discard block
 block discarded – undo
2693 2694
      * @param string $model_name   like 'Event', or 'Registration'
2694 2695
      * @param array  $query_params like EEM_Base::get_all's
2695 2696
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
+     * @param EE_Base_Class $id_or_obj
2696 2698
      * @return float
2697 2699
      * @throws EE_Error
2698 2700
      */
@@ -3653,7 +3655,7 @@  discard block
 block discarded – undo
3653 3655
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3654 3656
      * We should use default where conditions on related models when they requested to use default where conditions
3655 3657
      * on all models, or specifically just on other related models
3656
-     * @param      $default_where_conditions_value
3658
+     * @param      string $default_where_conditions_value
3657 3659
      * @param bool $for_this_model false means this is for OTHER related models
3658 3660
      * @return bool
3659 3661
      */
@@ -3691,7 +3693,7 @@  discard block
 block discarded – undo
3691 3693
      * where conditions.
3692 3694
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3693 3695
      * on this model or others
3694
-     * @param      $default_where_conditions_value
3696
+     * @param      string $default_where_conditions_value
3695 3697
      * @param bool $for_this_model false means this is for OTHER related models
3696 3698
      * @return bool
3697 3699
      */
@@ -4746,7 +4748,7 @@  discard block
 block discarded – undo
4746 4748
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747 4749
      * Eg, on EE_Answer that would be ANS_ID field object
4748 4750
      *
4749
-     * @param $field_obj
4751
+     * @param EE_Model_Field_Base $field_obj
4750 4752
      * @return boolean
4751 4753
      */
4752 4754
     public function is_primary_key_field($field_obj)
@@ -5464,7 +5466,7 @@  discard block
 block discarded – undo
5464 5466
     /**
5465 5467
      * Read comments for assume_values_already_prepared_by_model_object()
5466 5468
      *
5467
-     * @return int
5469
+     * @return boolean
5468 5470
      */
5469 5471
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5470 5472
     {
Please login to merge, or discard this patch.
Indentation   +6017 added lines, -6017 removed lines patch added patch discarded remove patch
@@ -32,6028 +32,6028 @@
 block discarded – undo
32 32
 abstract class EEM_Base extends EE_Base implements ResettableInterface
33 33
 {
34 34
 
35
-    /**
36
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
37
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
38
-     * They almost always WILL NOT, but it's not necessarily a requirement.
39
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
40
-     *
41
-     * @var boolean
42
-     */
43
-    private $_values_already_prepared_by_model_object = 0;
44
-
45
-    /**
46
-     * when $_values_already_prepared_by_model_object equals this, we assume
47
-     * the data is just like form input that needs to have the model fields'
48
-     * prepare_for_set and prepare_for_use_in_db called on it
49
-     */
50
-    const not_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we
54
-     * assume this value is coming from a model object and doesn't need to have
55
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
56
-     */
57
-    const prepared_by_model_object = 1;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we assume
61
-     * the values are already to be used in the database (ie no processing is done
62
-     * on them by the model's fields)
63
-     */
64
-    const prepared_for_use_in_db = 2;
65
-
66
-
67
-    protected $singular_item = 'Item';
68
-
69
-    protected $plural_item   = 'Items';
70
-
71
-    /**
72
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
73
-     */
74
-    protected $_tables;
75
-
76
-    /**
77
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
78
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
79
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
80
-     *
81
-     * @var \EE_Model_Field_Base[][] $_fields
82
-     */
83
-    protected $_fields;
84
-
85
-    /**
86
-     * array of different kinds of relations
87
-     *
88
-     * @var \EE_Model_Relation_Base[] $_model_relations
89
-     */
90
-    protected $_model_relations;
91
-
92
-    /**
93
-     * @var \EE_Index[] $_indexes
94
-     */
95
-    protected $_indexes = array();
96
-
97
-    /**
98
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
99
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
100
-     * by setting the same columns as used in these queries in the query yourself.
101
-     *
102
-     * @var EE_Default_Where_Conditions
103
-     */
104
-    protected $_default_where_conditions_strategy;
105
-
106
-    /**
107
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
108
-     * This is particularly useful when you want something between 'none' and 'default'
109
-     *
110
-     * @var EE_Default_Where_Conditions
111
-     */
112
-    protected $_minimum_where_conditions_strategy;
113
-
114
-    /**
115
-     * String describing how to find the "owner" of this model's objects.
116
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
117
-     * But when there isn't, this indicates which related model, or transiently-related model,
118
-     * has the foreign key to the wp_users table.
119
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
120
-     * related to events, and events have a foreign key to wp_users.
121
-     * On EEM_Transaction, this would be 'Transaction.Event'
122
-     *
123
-     * @var string
124
-     */
125
-    protected $_model_chain_to_wp_user = '';
126
-
127
-    /**
128
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
129
-     * don't need it (particularly CPT models)
130
-     *
131
-     * @var bool
132
-     */
133
-    protected $_ignore_where_strategy = false;
134
-
135
-    /**
136
-     * String used in caps relating to this model. Eg, if the caps relating to this
137
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
138
-     *
139
-     * @var string. If null it hasn't been initialized yet. If false then we
140
-     * have indicated capabilities don't apply to this
141
-     */
142
-    protected $_caps_slug = null;
143
-
144
-    /**
145
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
146
-     * and next-level keys are capability names, and each's value is a
147
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
148
-     * they specify which context to use (ie, frontend, backend, edit or delete)
149
-     * and then each capability in the corresponding sub-array that they're missing
150
-     * adds the where conditions onto the query.
151
-     *
152
-     * @var array
153
-     */
154
-    protected $_cap_restrictions = array(
155
-        self::caps_read       => array(),
156
-        self::caps_read_admin => array(),
157
-        self::caps_edit       => array(),
158
-        self::caps_delete     => array(),
159
-    );
160
-
161
-    /**
162
-     * Array defining which cap restriction generators to use to create default
163
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
164
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
165
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
166
-     * automatically set this to false (not just null).
167
-     *
168
-     * @var EE_Restriction_Generator_Base[]
169
-     */
170
-    protected $_cap_restriction_generators = array();
171
-
172
-    /**
173
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
174
-     */
175
-    const caps_read       = 'read';
176
-
177
-    const caps_read_admin = 'read_admin';
178
-
179
-    const caps_edit       = 'edit';
180
-
181
-    const caps_delete     = 'delete';
182
-
183
-    /**
184
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
185
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
186
-     * maps to 'read' because when looking for relevant permissions we're going to use
187
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
188
-     *
189
-     * @var array
190
-     */
191
-    protected $_cap_contexts_to_cap_action_map = array(
192
-        self::caps_read       => 'read',
193
-        self::caps_read_admin => 'read',
194
-        self::caps_edit       => 'edit',
195
-        self::caps_delete     => 'delete',
196
-    );
197
-
198
-    /**
199
-     * Timezone
200
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
201
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
202
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
203
-     * EE_Datetime_Field data type will have access to it.
204
-     *
205
-     * @var string
206
-     */
207
-    protected $_timezone;
208
-
209
-
210
-    /**
211
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
212
-     * multisite.
213
-     *
214
-     * @var int
215
-     */
216
-    protected static $_model_query_blog_id;
217
-
218
-    /**
219
-     * A copy of _fields, except the array keys are the model names pointed to by
220
-     * the field
221
-     *
222
-     * @var EE_Model_Field_Base[]
223
-     */
224
-    private $_cache_foreign_key_to_fields = array();
225
-
226
-    /**
227
-     * Cached list of all the fields on the model, indexed by their name
228
-     *
229
-     * @var EE_Model_Field_Base[]
230
-     */
231
-    private $_cached_fields = null;
232
-
233
-    /**
234
-     * Cached list of all the fields on the model, except those that are
235
-     * marked as only pertinent to the database
236
-     *
237
-     * @var EE_Model_Field_Base[]
238
-     */
239
-    private $_cached_fields_non_db_only = null;
240
-
241
-    /**
242
-     * A cached reference to the primary key for quick lookup
243
-     *
244
-     * @var EE_Model_Field_Base
245
-     */
246
-    private $_primary_key_field = null;
247
-
248
-    /**
249
-     * Flag indicating whether this model has a primary key or not
250
-     *
251
-     * @var boolean
252
-     */
253
-    protected $_has_primary_key_field = null;
254
-
255
-    /**
256
-     * Whether or not this model is based off a table in WP core only (CPTs should set
257
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
258
-     * This should be true for models that deal with data that should exist independent of EE.
259
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
260
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
261
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
262
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
263
-     * @var boolean
264
-     */
265
-    protected $_wp_core_model = false;
266
-
267
-    /**
268
-     *    List of valid operators that can be used for querying.
269
-     * The keys are all operators we'll accept, the values are the real SQL
270
-     * operators used
271
-     *
272
-     * @var array
273
-     */
274
-    protected $_valid_operators = array(
275
-        '='           => '=',
276
-        '<='          => '<=',
277
-        '<'           => '<',
278
-        '>='          => '>=',
279
-        '>'           => '>',
280
-        '!='          => '!=',
281
-        'LIKE'        => 'LIKE',
282
-        'like'        => 'LIKE',
283
-        'NOT_LIKE'    => 'NOT LIKE',
284
-        'not_like'    => 'NOT LIKE',
285
-        'NOT LIKE'    => 'NOT LIKE',
286
-        'not like'    => 'NOT LIKE',
287
-        'IN'          => 'IN',
288
-        'in'          => 'IN',
289
-        'NOT_IN'      => 'NOT IN',
290
-        'not_in'      => 'NOT IN',
291
-        'NOT IN'      => 'NOT IN',
292
-        'not in'      => 'NOT IN',
293
-        'between'     => 'BETWEEN',
294
-        'BETWEEN'     => 'BETWEEN',
295
-        'IS_NOT_NULL' => 'IS NOT NULL',
296
-        'is_not_null' => 'IS NOT NULL',
297
-        'IS NOT NULL' => 'IS NOT NULL',
298
-        'is not null' => 'IS NOT NULL',
299
-        'IS_NULL'     => 'IS NULL',
300
-        'is_null'     => 'IS NULL',
301
-        'IS NULL'     => 'IS NULL',
302
-        'is null'     => 'IS NULL',
303
-        'REGEXP'      => 'REGEXP',
304
-        'regexp'      => 'REGEXP',
305
-        'NOT_REGEXP'  => 'NOT REGEXP',
306
-        'not_regexp'  => 'NOT REGEXP',
307
-        'NOT REGEXP'  => 'NOT REGEXP',
308
-        'not regexp'  => 'NOT REGEXP',
309
-    );
310
-
311
-    /**
312
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
313
-     *
314
-     * @var array
315
-     */
316
-    protected $_in_style_operators = array('IN', 'NOT IN');
317
-
318
-    /**
319
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
320
-     * '12-31-2012'"
321
-     *
322
-     * @var array
323
-     */
324
-    protected $_between_style_operators = array('BETWEEN');
325
-
326
-    /**
327
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
328
-     * @var array
329
-     */
330
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
331
-    /**
332
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
333
-     * on a join table.
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
338
-
339
-    /**
340
-     * Allowed values for $query_params['order'] for ordering in queries
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
345
-
346
-    /**
347
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
348
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
349
-     *
350
-     * @var array
351
-     */
352
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
353
-
354
-    /**
355
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
356
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
357
-     *
358
-     * @var array
359
-     */
360
-    private $_allowed_query_params = array(
361
-        0,
362
-        'limit',
363
-        'order_by',
364
-        'group_by',
365
-        'having',
366
-        'force_join',
367
-        'order',
368
-        'on_join_limit',
369
-        'default_where_conditions',
370
-        'caps',
371
-    );
372
-
373
-    /**
374
-     * All the data types that can be used in $wpdb->prepare statements.
375
-     *
376
-     * @var array
377
-     */
378
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
379
-
380
-    /**
381
-     * @var EE_Registry $EE
382
-     */
383
-    protected $EE = null;
384
-
385
-
386
-    /**
387
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
-     *
389
-     * @var int
390
-     */
391
-    protected $_show_next_x_db_queries = 0;
392
-
393
-    /**
394
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
-     *
397
-     * @var array
398
-     */
399
-    protected $_custom_selections = array();
400
-
401
-    /**
402
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
-     * caches every model object we've fetched from the DB on this request
404
-     *
405
-     * @var array
406
-     */
407
-    protected $_entity_map;
408
-
409
-    /**
410
-     * @var LoaderInterface $loader
411
-     */
412
-    private static $loader;
413
-
414
-
415
-    /**
416
-     * constant used to show EEM_Base has not yet verified the db on this http request
417
-     */
418
-    const db_verified_none = 0;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has verified the EE core db on this http request,
422
-     * but not the addons' dbs
423
-     */
424
-    const db_verified_core = 1;
425
-
426
-    /**
427
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
428
-     * the EE core db too)
429
-     */
430
-    const db_verified_addons = 2;
431
-
432
-    /**
433
-     * indicates whether an EEM_Base child has already re-verified the DB
434
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
435
-     * looking like EEM_Base::db_verified_*
436
-     *
437
-     * @var int - 0 = none, 1 = core, 2 = addons
438
-     */
439
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
440
-
441
-    /**
442
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
443
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
444
-     *        registrations for non-trashed tickets for non-trashed datetimes)
445
-     */
446
-    const default_where_conditions_all = 'all';
447
-
448
-    /**
449
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
450
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
451
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
452
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
453
-     *        models which share tables with other models, this can return data for the wrong model.
454
-     */
455
-    const default_where_conditions_this_only = 'this_model_only';
456
-
457
-    /**
458
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
459
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
460
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
461
-     */
462
-    const default_where_conditions_others_only = 'other_models_only';
463
-
464
-    /**
465
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
466
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
467
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
468
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
469
-     *        (regardless of whether those events and venues are trashed)
470
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
471
-     *        events.
472
-     */
473
-    const default_where_conditions_minimum_all = 'minimum';
474
-
475
-    /**
476
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
477
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
478
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
479
-     *        not)
480
-     */
481
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
-
483
-    /**
484
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
485
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
486
-     *        it's possible it will return table entries for other models. You should use
487
-     *        EEM_Base::default_where_conditions_minimum_all instead.
488
-     */
489
-    const default_where_conditions_none = 'none';
490
-
491
-
492
-
493
-    /**
494
-     * About all child constructors:
495
-     * they should define the _tables, _fields and _model_relations arrays.
496
-     * Should ALWAYS be called after child constructor.
497
-     * In order to make the child constructors to be as simple as possible, this parent constructor
498
-     * finalizes constructing all the object's attributes.
499
-     * Generally, rather than requiring a child to code
500
-     * $this->_tables = array(
501
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
502
-     *        ...);
503
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
504
-     * each EE_Table has a function to set the table's alias after the constructor, using
505
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
506
-     * do something similar.
507
-     *
508
-     * @param null $timezone
509
-     * @throws EE_Error
510
-     */
511
-    protected function __construct($timezone = null)
512
-    {
513
-        // check that the model has not been loaded too soon
514
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
-            throw new EE_Error (
516
-                sprintf(
517
-                    __('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.',
518
-                        'event_espresso'),
519
-                    get_class($this)
520
-                )
521
-            );
522
-        }
523
-        /**
524
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
525
-         */
526
-        if (empty(EEM_Base::$_model_query_blog_id)) {
527
-            EEM_Base::set_model_query_blog_id();
528
-        }
529
-        /**
530
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
531
-         * just use EE_Register_Model_Extension
532
-         *
533
-         * @var EE_Table_Base[] $_tables
534
-         */
535
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
536
-        foreach ($this->_tables as $table_alias => $table_obj) {
537
-            /** @var $table_obj EE_Table_Base */
538
-            $table_obj->_construct_finalize_with_alias($table_alias);
539
-            if ($table_obj instanceof EE_Secondary_Table) {
540
-                /** @var $table_obj EE_Secondary_Table */
541
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
542
-            }
543
-        }
544
-        /**
545
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
546
-         * EE_Register_Model_Extension
547
-         *
548
-         * @param EE_Model_Field_Base[] $_fields
549
-         */
550
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
551
-        $this->_invalidate_field_caches();
552
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
553
-            if (! array_key_exists($table_alias, $this->_tables)) {
554
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
556
-            }
557
-            foreach ($fields_for_table as $field_name => $field_obj) {
558
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
559
-                //primary key field base has a slightly different _construct_finalize
560
-                /** @var $field_obj EE_Model_Field_Base */
561
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
562
-            }
563
-        }
564
-        // everything is related to Extra_Meta
565
-        if (get_class($this) !== 'EEM_Extra_Meta') {
566
-            //make extra meta related to everything, but don't block deleting things just
567
-            //because they have related extra meta info. For now just orphan those extra meta
568
-            //in the future we should automatically delete them
569
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
570
-        }
571
-        //and change logs
572
-        if (get_class($this) !== 'EEM_Change_Log') {
573
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        /**
576
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
577
-         * EE_Register_Model_Extension
578
-         *
579
-         * @param EE_Model_Relation_Base[] $_model_relations
580
-         */
581
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
582
-            $this->_model_relations);
583
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
584
-            /** @var $relation_obj EE_Model_Relation_Base */
585
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
586
-        }
587
-        foreach ($this->_indexes as $index_name => $index_obj) {
588
-            /** @var $index_obj EE_Index */
589
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
590
-        }
591
-        $this->set_timezone($timezone);
592
-        //finalize default where condition strategy, or set default
593
-        if (! $this->_default_where_conditions_strategy) {
594
-            //nothing was set during child constructor, so set default
595
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596
-        }
597
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
598
-        if (! $this->_minimum_where_conditions_strategy) {
599
-            //nothing was set during child constructor, so set default
600
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601
-        }
602
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
603
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
604
-        //to indicate to NOT set it, set it to the logical default
605
-        if ($this->_caps_slug === null) {
606
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
607
-        }
608
-        //initialize the standard cap restriction generators if none were specified by the child constructor
609
-        if ($this->_cap_restriction_generators !== false) {
610
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
612
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
613
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614
-                        new EE_Restriction_Generator_Protected(),
615
-                        $cap_context,
616
-                        $this
617
-                    );
618
-                }
619
-            }
620
-        }
621
-        //if there are cap restriction generators, use them to make the default cap restrictions
622
-        if ($this->_cap_restriction_generators !== false) {
623
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
-                if (! $generator_object) {
625
-                    continue;
626
-                }
627
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
628
-                    throw new EE_Error(
629
-                        sprintf(
630
-                            __('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.',
631
-                                'event_espresso'),
632
-                            $context,
633
-                            $this->get_this_model_name()
634
-                        )
635
-                    );
636
-                }
637
-                $action = $this->cap_action_for_context($context);
638
-                if (! $generator_object->construction_finalized()) {
639
-                    $generator_object->_construct_finalize($this, $action);
640
-                }
641
-            }
642
-        }
643
-        do_action('AHEE__' . get_class($this) . '__construct__end');
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * Used to set the $_model_query_blog_id static property.
650
-     *
651
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
652
-     *                      value for get_current_blog_id() will be used.
653
-     */
654
-    public static function set_model_query_blog_id($blog_id = 0)
655
-    {
656
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
657
-    }
658
-
659
-
660
-
661
-    /**
662
-     * Returns whatever is set as the internal $model_query_blog_id.
663
-     *
664
-     * @return int
665
-     */
666
-    public static function get_model_query_blog_id()
667
-    {
668
-        return EEM_Base::$_model_query_blog_id;
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * This function is a singleton method used to instantiate the Espresso_model object
675
-     *
676
-     * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
677
-     *                                    (and any incoming timezone data that gets saved).
678
-     *                                    Note this just sends the timezone info to the date time model field objects.
679
-     *                                    Default is NULL
680
-     *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
681
-     * @param ModelFieldFactory $model_field_factory
682
-     * @return static (as in the concrete child class)
683
-     * @throws EE_Error
684
-     * @throws InvalidArgumentException
685
-     * @throws InvalidDataTypeException
686
-     * @throws InvalidInterfaceException
687
-     */
688
-    public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
689
-    {
690
-        // check if instance of Espresso_model already exists
691
-        if (! static::$_instance instanceof static) {
692
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
693
-            // instantiate Espresso_model
694
-            static::$_instance = new static($timezone, $model_field_factory);
695
-        }
696
-        //we might have a timezone set, let set_timezone decide what to do with it
697
-        static::$_instance->set_timezone($timezone);
698
-        // Espresso_model object
699
-        return static::$_instance;
700
-    }
701
-
702
-
703
-
704
-    /**
705
-     * @param $model_field_factory
706
-     * @return ModelFieldFactory
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidDataTypeException
709
-     * @throws InvalidInterfaceException
710
-     */
711
-    private static function getModelFieldFactory($model_field_factory)
712
-    {
713
-        return $model_field_factory instanceof ModelFieldFactory
714
-            ? $model_field_factory
715
-            : LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory');
716
-    }
717
-
718
-
719
-
720
-    /**
721
-     * resets the model and returns it
722
-     *
723
-     * @param null | string          $timezone
724
-     * @param ModelFieldFactory|null $model_field_factory
725
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
726
-     * all its properties reset; if it wasn't instantiated, returns null)
727
-     * @throws EE_Error
728
-     * @throws ReflectionException
729
-     * @throws InvalidArgumentException
730
-     * @throws InvalidDataTypeException
731
-     * @throws InvalidInterfaceException
732
-     */
733
-    public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
734
-    {
735
-        if (static::$_instance instanceof EEM_Base) {
736
-            //let's try to NOT swap out the current instance for a new one
737
-            //because if someone has a reference to it, we can't remove their reference
738
-            //so it's best to keep using the same reference, but change the original object
739
-            //reset all its properties to their original values as defined in the class
740
-            $r = new ReflectionClass(get_class(static::$_instance));
741
-            $static_properties = $r->getStaticProperties();
742
-            foreach ($r->getDefaultProperties() as $property => $value) {
743
-                //don't set instance to null like it was originally,
744
-                //but it's static anyways, and we're ignoring static properties (for now at least)
745
-                if (! isset($static_properties[$property])) {
746
-                    static::$_instance->{$property} = $value;
747
-                }
748
-            }
749
-            //and then directly call its constructor again, like we would if we were creating a new one
750
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
751
-            static::$_instance->__construct($timezone, $model_field_factory);
752
-            return self::instance();
753
-        }
754
-        return null;
755
-    }
756
-
757
-
758
-
759
-    /**
760
-     * @return LoaderInterface
761
-     * @throws InvalidArgumentException
762
-     * @throws InvalidDataTypeException
763
-     * @throws InvalidInterfaceException
764
-     */
765
-    private static function getLoader()
766
-    {
767
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
768
-            EEM_Base::$loader = LoaderFactory::getLoader();
769
-        }
770
-        return EEM_Base::$loader;
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
-     *
778
-     * @param  boolean $translated return localized strings or JUST the array.
779
-     * @return array
780
-     * @throws EE_Error
781
-     * @throws InvalidArgumentException
782
-     * @throws InvalidDataTypeException
783
-     * @throws InvalidInterfaceException
784
-     */
785
-    public function status_array($translated = false)
786
-    {
787
-        if (! array_key_exists('Status', $this->_model_relations)) {
788
-            return array();
789
-        }
790
-        $model_name = $this->get_this_model_name();
791
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
792
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
793
-        $status_array = array();
794
-        foreach ($stati as $status) {
795
-            $status_array[$status->ID()] = $status->get('STS_code');
796
-        }
797
-        return $translated
798
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
799
-            : $status_array;
800
-    }
801
-
802
-
803
-
804
-    /**
805
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
806
-     *
807
-     * @param array $query_params             {
808
-     * @var array $0 (where) array {
809
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
810
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
811
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
812
-     *                                        conditions based on related models (and even
813
-     *                                        models-related-to-related-models) prepend the model's name onto the field
814
-     *                                        name. Eg,
815
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
816
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
817
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
818
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
819
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
820
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
821
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
822
-     *                                        to Venues (even when each of those models actually consisted of two
823
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
824
-     *                                        just having
825
-     *                                        "Venue.VNU_ID", you could have
826
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
827
-     *                                        events are related to Registrations, which are related to Attendees). You
828
-     *                                        can take it even further with
829
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
830
-     *                                        (from the default of '='), change the value to an numerically-indexed
831
-     *                                        array, where the first item in the list is the operator. eg: array(
832
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
833
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
834
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
835
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
836
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
837
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
838
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
839
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
840
-     *                                        the value is a field, simply provide a third array item (true) to the
841
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
842
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
843
-     *                                        Note: you can also use related model field names like you would any other
844
-     *                                        field name. eg:
845
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
846
-     *                                        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__>' =>
847
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
848
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
849
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
850
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
851
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
852
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
853
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
854
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
855
-     *                                        "stick" until you specify an AND. eg
856
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
857
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
858
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
859
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
860
-     *                                        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 >>
861
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
862
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
863
-     *                                        too, eg:
864
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
865
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
866
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
867
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
868
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
869
-     *                                        the OFFSET, the 2nd is the LIMIT
870
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
871
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
872
-     *                                        following format array('on_join_limit'
873
-     *                                        => array( 'table_alias', array(1,2) ) ).
874
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
875
-     *                                        values are either 'ASC' or 'DESC'.
876
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
877
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
878
-     *                                        DESC..." respectively. Like the
879
-     *                                        'where' conditions, these fields can be on related models. Eg
880
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
881
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
882
-     *                                        Attendee, Price, Datetime, etc.)
883
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
884
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
885
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
886
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
887
-     *                                        order by the primary key. Eg,
888
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
889
-     *                                        //(will join with the Datetime model's table(s) and order by its field
890
-     *                                        DTT_EVT_start) or
891
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
892
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
893
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
894
-     *                                        'group_by'=>'VNU_ID', or
895
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
896
-     *                                        if no
897
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
898
-     *                                        model's primary key (or combined primary keys). This avoids some
899
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
900
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
901
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
902
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
903
-     *                                        results)
904
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
905
-     *                                        array where values are models to be joined in the query.Eg
906
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
907
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
908
-     *                                        probably only want to do this in hopes of increasing efficiency, as
909
-     *                                        related models which belongs to the current model
910
-     *                                        (ie, the current model has a foreign key to them, like how Registration
911
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
912
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
913
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
914
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
915
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
916
-     *                                        default where conditions set it to 'other_models_only'. If you only want
917
-     *                                        this model's default where conditions added to the query, use
918
-     *                                        'this_model_only'. If you want to use all default where conditions
919
-     *                                        (default), set to 'all'.
920
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
921
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
922
-     *                                        everything? Or should we only show the current user items they should be
923
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
924
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
925
-     *                                        }
926
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
927
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
928
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
929
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
930
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
931
-     *                                        array( array(
932
-     *                                        'OR'=>array(
933
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
934
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
935
-     *                                        )
936
-     *                                        ),
937
-     *                                        'limit'=>10,
938
-     *                                        'group_by'=>'TXN_ID'
939
-     *                                        ));
940
-     *                                        get all the answers to the question titled "shirt size" for event with id
941
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
942
-     *                                        'Question.QST_display_text'=>'shirt size',
943
-     *                                        'Registration.Event.EVT_ID'=>12
944
-     *                                        ),
945
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
946
-     *                                        ));
947
-     * @throws EE_Error
948
-     */
949
-    public function get_all($query_params = array())
950
-    {
951
-        if (isset($query_params['limit'])
952
-            && ! isset($query_params['group_by'])
953
-        ) {
954
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
955
-        }
956
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
957
-    }
958
-
959
-
960
-
961
-    /**
962
-     * Modifies the query parameters so we only get back model objects
963
-     * that "belong" to the current user
964
-     *
965
-     * @param array $query_params @see EEM_Base::get_all()
966
-     * @return array like EEM_Base::get_all
967
-     */
968
-    public function alter_query_params_to_only_include_mine($query_params = array())
969
-    {
970
-        $wp_user_field_name = $this->wp_user_field_name();
971
-        if ($wp_user_field_name) {
972
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
973
-        }
974
-        return $query_params;
975
-    }
976
-
977
-
978
-
979
-    /**
980
-     * Returns the name of the field's name that points to the WP_User table
981
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
982
-     * foreign key to the WP_User table)
983
-     *
984
-     * @return string|boolean string on success, boolean false when there is no
985
-     * foreign key to the WP_User table
986
-     */
987
-    public function wp_user_field_name()
988
-    {
989
-        try {
990
-            if (! empty($this->_model_chain_to_wp_user)) {
991
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
992
-                $last_model_name = end($models_to_follow_to_wp_users);
993
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
994
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
995
-            } else {
996
-                $model_with_fk_to_wp_users = $this;
997
-                $model_chain_to_wp_user = '';
998
-            }
999
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1000
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1001
-        } catch (EE_Error $e) {
1002
-            return false;
1003
-        }
1004
-    }
1005
-
1006
-
1007
-
1008
-    /**
1009
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1010
-     * (or transiently-related model) has a foreign key to the wp_users table;
1011
-     * useful for finding if model objects of this type are 'owned' by the current user.
1012
-     * This is an empty string when the foreign key is on this model and when it isn't,
1013
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1014
-     * (or transiently-related model)
1015
-     *
1016
-     * @return string
1017
-     */
1018
-    public function model_chain_to_wp_user()
1019
-    {
1020
-        return $this->_model_chain_to_wp_user;
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1027
-     * like how registrations don't have a foreign key to wp_users, but the
1028
-     * events they are for are), or is unrelated to wp users.
1029
-     * generally available
1030
-     *
1031
-     * @return boolean
1032
-     */
1033
-    public function is_owned()
1034
-    {
1035
-        if ($this->model_chain_to_wp_user()) {
1036
-            return true;
1037
-        }
1038
-        try {
1039
-            $this->get_foreign_key_to('WP_User');
1040
-            return true;
1041
-        } catch (EE_Error $e) {
1042
-            return false;
1043
-        }
1044
-    }
1045
-
1046
-
1047
-
1048
-    /**
1049
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1050
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1051
-     * the model)
1052
-     *
1053
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1054
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1055
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1056
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1057
-     *                                  override this and set the select to "*", or a specific column name, like
1058
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1059
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1060
-     *                                  the aliases used to refer to this selection, and values are to be
1061
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1062
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1063
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1064
-     * @throws EE_Error
1065
-     */
1066
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1067
-    {
1068
-        // remember the custom selections, if any, and type cast as array
1069
-        // (unless $columns_to_select is an object, then just set as an empty array)
1070
-        // Note: (array) 'some string' === array( 'some string' )
1071
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1072
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1073
-        $select_expressions = $columns_to_select !== null
1074
-            ? $this->_construct_select_from_input($columns_to_select)
1075
-            : $this->_construct_default_select_sql($model_query_info);
1076
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1077
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1078
-    }
1079
-
1080
-
1081
-
1082
-    /**
1083
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1084
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1085
-     * take care of joins, field preparation etc.
1086
-     *
1087
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1088
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1089
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1090
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1091
-     *                                  override this and set the select to "*", or a specific column name, like
1092
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1093
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1094
-     *                                  the aliases used to refer to this selection, and values are to be
1095
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1096
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1097
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1098
-     * @throws EE_Error
1099
-     */
1100
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1101
-    {
1102
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1103
-    }
1104
-
1105
-
1106
-
1107
-    /**
1108
-     * For creating a custom select statement
1109
-     *
1110
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1111
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1112
-     *                                 SQL, and 1=>is the datatype
1113
-     * @throws EE_Error
1114
-     * @return string
1115
-     */
1116
-    private function _construct_select_from_input($columns_to_select)
1117
-    {
1118
-        if (is_array($columns_to_select)) {
1119
-            $select_sql_array = array();
1120
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1121
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1122
-                    throw new EE_Error(
1123
-                        sprintf(
1124
-                            __(
1125
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1126
-                                'event_espresso'
1127
-                            ),
1128
-                            $selection_and_datatype,
1129
-                            $alias
1130
-                        )
1131
-                    );
1132
-                }
1133
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1134
-                    throw new EE_Error(
1135
-                        sprintf(
1136
-                            esc_html__(
1137
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1138
-                                'event_espresso'
1139
-                            ),
1140
-                            $selection_and_datatype[1],
1141
-                            $selection_and_datatype[0],
1142
-                            $alias,
1143
-                            implode(', ', $this->_valid_wpdb_data_types)
1144
-                        )
1145
-                    );
1146
-                }
1147
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1148
-            }
1149
-            $columns_to_select_string = implode(', ', $select_sql_array);
1150
-        } else {
1151
-            $columns_to_select_string = $columns_to_select;
1152
-        }
1153
-        return $columns_to_select_string;
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1160
-     *
1161
-     * @return string
1162
-     * @throws EE_Error
1163
-     */
1164
-    public function primary_key_name()
1165
-    {
1166
-        return $this->get_primary_key_field()->get_name();
1167
-    }
1168
-
1169
-
1170
-
1171
-    /**
1172
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1173
-     * If there is no primary key on this model, $id is treated as primary key string
1174
-     *
1175
-     * @param mixed $id int or string, depending on the type of the model's primary key
1176
-     * @return EE_Base_Class
1177
-     */
1178
-    public function get_one_by_ID($id)
1179
-    {
1180
-        if ($this->get_from_entity_map($id)) {
1181
-            return $this->get_from_entity_map($id);
1182
-        }
1183
-        return $this->get_one(
1184
-            $this->alter_query_params_to_restrict_by_ID(
1185
-                $id,
1186
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1187
-            )
1188
-        );
1189
-    }
1190
-
1191
-
1192
-
1193
-    /**
1194
-     * Alters query parameters to only get items with this ID are returned.
1195
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1196
-     * or could just be a simple primary key ID
1197
-     *
1198
-     * @param int   $id
1199
-     * @param array $query_params
1200
-     * @return array of normal query params, @see EEM_Base::get_all
1201
-     * @throws EE_Error
1202
-     */
1203
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1204
-    {
1205
-        if (! isset($query_params[0])) {
1206
-            $query_params[0] = array();
1207
-        }
1208
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1209
-        if ($conditions_from_id === null) {
1210
-            $query_params[0][$this->primary_key_name()] = $id;
1211
-        } else {
1212
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1213
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1214
-        }
1215
-        return $query_params;
1216
-    }
1217
-
1218
-
1219
-
1220
-    /**
1221
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1222
-     * array. If no item is found, null is returned.
1223
-     *
1224
-     * @param array $query_params like EEM_Base's $query_params variable.
1225
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1226
-     * @throws EE_Error
1227
-     */
1228
-    public function get_one($query_params = array())
1229
-    {
1230
-        if (! is_array($query_params)) {
1231
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1232
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1233
-                    gettype($query_params)), '4.6.0');
1234
-            $query_params = array();
1235
-        }
1236
-        $query_params['limit'] = 1;
1237
-        $items = $this->get_all($query_params);
1238
-        if (empty($items)) {
1239
-            return null;
1240
-        }
1241
-        return array_shift($items);
1242
-    }
1243
-
1244
-
1245
-
1246
-    /**
1247
-     * Returns the next x number of items in sequence from the given value as
1248
-     * found in the database matching the given query conditions.
1249
-     *
1250
-     * @param mixed $current_field_value    Value used for the reference point.
1251
-     * @param null  $field_to_order_by      What field is used for the
1252
-     *                                      reference point.
1253
-     * @param int   $limit                  How many to return.
1254
-     * @param array $query_params           Extra conditions on the query.
1255
-     * @param null  $columns_to_select      If left null, then an array of
1256
-     *                                      EE_Base_Class objects is returned,
1257
-     *                                      otherwise you can indicate just the
1258
-     *                                      columns you want returned.
1259
-     * @return EE_Base_Class[]|array
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function next_x(
1263
-        $current_field_value,
1264
-        $field_to_order_by = null,
1265
-        $limit = 1,
1266
-        $query_params = array(),
1267
-        $columns_to_select = null
1268
-    ) {
1269
-        return $this->_get_consecutive(
1270
-            $current_field_value,
1271
-            '>',
1272
-            $field_to_order_by,
1273
-            $limit,
1274
-            $query_params,
1275
-            $columns_to_select
1276
-        );
1277
-    }
1278
-
1279
-
1280
-
1281
-    /**
1282
-     * Returns the previous x number of items in sequence from the given value
1283
-     * as found in the database matching the given query conditions.
1284
-     *
1285
-     * @param mixed $current_field_value    Value used for the reference point.
1286
-     * @param null  $field_to_order_by      What field is used for the
1287
-     *                                      reference point.
1288
-     * @param int   $limit                  How many to return.
1289
-     * @param array $query_params           Extra conditions on the query.
1290
-     * @param null  $columns_to_select      If left null, then an array of
1291
-     *                                      EE_Base_Class objects is returned,
1292
-     *                                      otherwise you can indicate just the
1293
-     *                                      columns you want returned.
1294
-     * @return EE_Base_Class[]|array
1295
-     * @throws EE_Error
1296
-     */
1297
-    public function previous_x(
1298
-        $current_field_value,
1299
-        $field_to_order_by = null,
1300
-        $limit = 1,
1301
-        $query_params = array(),
1302
-        $columns_to_select = null
1303
-    ) {
1304
-        return $this->_get_consecutive(
1305
-            $current_field_value,
1306
-            '<',
1307
-            $field_to_order_by,
1308
-            $limit,
1309
-            $query_params,
1310
-            $columns_to_select
1311
-        );
1312
-    }
1313
-
1314
-
1315
-
1316
-    /**
1317
-     * Returns the next item in sequence from the given value as found in the
1318
-     * database matching the given query conditions.
1319
-     *
1320
-     * @param mixed $current_field_value    Value used for the reference point.
1321
-     * @param null  $field_to_order_by      What field is used for the
1322
-     *                                      reference point.
1323
-     * @param array $query_params           Extra conditions on the query.
1324
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1325
-     *                                      object is returned, otherwise you
1326
-     *                                      can indicate just the columns you
1327
-     *                                      want and a single array indexed by
1328
-     *                                      the columns will be returned.
1329
-     * @return EE_Base_Class|null|array()
1330
-     * @throws EE_Error
1331
-     */
1332
-    public function next(
1333
-        $current_field_value,
1334
-        $field_to_order_by = null,
1335
-        $query_params = array(),
1336
-        $columns_to_select = null
1337
-    ) {
1338
-        $results = $this->_get_consecutive(
1339
-            $current_field_value,
1340
-            '>',
1341
-            $field_to_order_by,
1342
-            1,
1343
-            $query_params,
1344
-            $columns_to_select
1345
-        );
1346
-        return empty($results) ? null : reset($results);
1347
-    }
1348
-
1349
-
1350
-
1351
-    /**
1352
-     * Returns the previous item in sequence from the given value as found in
1353
-     * the database matching the given query conditions.
1354
-     *
1355
-     * @param mixed $current_field_value    Value used for the reference point.
1356
-     * @param null  $field_to_order_by      What field is used for the
1357
-     *                                      reference point.
1358
-     * @param array $query_params           Extra conditions on the query.
1359
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1360
-     *                                      object is returned, otherwise you
1361
-     *                                      can indicate just the columns you
1362
-     *                                      want and a single array indexed by
1363
-     *                                      the columns will be returned.
1364
-     * @return EE_Base_Class|null|array()
1365
-     * @throws EE_Error
1366
-     */
1367
-    public function previous(
1368
-        $current_field_value,
1369
-        $field_to_order_by = null,
1370
-        $query_params = array(),
1371
-        $columns_to_select = null
1372
-    ) {
1373
-        $results = $this->_get_consecutive(
1374
-            $current_field_value,
1375
-            '<',
1376
-            $field_to_order_by,
1377
-            1,
1378
-            $query_params,
1379
-            $columns_to_select
1380
-        );
1381
-        return empty($results) ? null : reset($results);
1382
-    }
1383
-
1384
-
1385
-
1386
-    /**
1387
-     * Returns the a consecutive number of items in sequence from the given
1388
-     * value as found in the database matching the given query conditions.
1389
-     *
1390
-     * @param mixed  $current_field_value   Value used for the reference point.
1391
-     * @param string $operand               What operand is used for the sequence.
1392
-     * @param string $field_to_order_by     What field is used for the reference point.
1393
-     * @param int    $limit                 How many to return.
1394
-     * @param array  $query_params          Extra conditions on the query.
1395
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1396
-     *                                      otherwise you can indicate just the columns you want returned.
1397
-     * @return EE_Base_Class[]|array
1398
-     * @throws EE_Error
1399
-     */
1400
-    protected function _get_consecutive(
1401
-        $current_field_value,
1402
-        $operand = '>',
1403
-        $field_to_order_by = null,
1404
-        $limit = 1,
1405
-        $query_params = array(),
1406
-        $columns_to_select = null
1407
-    ) {
1408
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1409
-        if (empty($field_to_order_by)) {
1410
-            if ($this->has_primary_key_field()) {
1411
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1412
-            } else {
1413
-                if (WP_DEBUG) {
1414
-                    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).',
1415
-                        'event_espresso'));
1416
-                }
1417
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1418
-                return array();
1419
-            }
1420
-        }
1421
-        if (! is_array($query_params)) {
1422
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1423
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1424
-                    gettype($query_params)), '4.6.0');
1425
-            $query_params = array();
1426
-        }
1427
-        //let's add the where query param for consecutive look up.
1428
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1429
-        $query_params['limit'] = $limit;
1430
-        //set direction
1431
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1432
-        $query_params['order_by'] = $operand === '>'
1433
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1434
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1435
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1436
-        if (empty($columns_to_select)) {
1437
-            return $this->get_all($query_params);
1438
-        }
1439
-        //getting just the fields
1440
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1441
-    }
1442
-
1443
-
1444
-
1445
-    /**
1446
-     * This sets the _timezone property after model object has been instantiated.
1447
-     *
1448
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1449
-     */
1450
-    public function set_timezone($timezone)
1451
-    {
1452
-        if ($timezone !== null) {
1453
-            $this->_timezone = $timezone;
1454
-        }
1455
-        //note we need to loop through relations and set the timezone on those objects as well.
1456
-        foreach ($this->_model_relations as $relation) {
1457
-            $relation->set_timezone($timezone);
1458
-        }
1459
-        //and finally we do the same for any datetime fields
1460
-        foreach ($this->_fields as $field) {
1461
-            if ($field instanceof EE_Datetime_Field) {
1462
-                $field->set_timezone($timezone);
1463
-            }
1464
-        }
1465
-    }
1466
-
1467
-
1468
-
1469
-    /**
1470
-     * This just returns whatever is set for the current timezone.
1471
-     *
1472
-     * @access public
1473
-     * @return string
1474
-     */
1475
-    public function get_timezone()
1476
-    {
1477
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1478
-        if (empty($this->_timezone)) {
1479
-            foreach ($this->_fields as $field) {
1480
-                if ($field instanceof EE_Datetime_Field) {
1481
-                    $this->set_timezone($field->get_timezone());
1482
-                    break;
1483
-                }
1484
-            }
1485
-        }
1486
-        //if timezone STILL empty then return the default timezone for the site.
1487
-        if (empty($this->_timezone)) {
1488
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1489
-        }
1490
-        return $this->_timezone;
1491
-    }
1492
-
1493
-
1494
-
1495
-    /**
1496
-     * This returns the date formats set for the given field name and also ensures that
1497
-     * $this->_timezone property is set correctly.
1498
-     *
1499
-     * @since 4.6.x
1500
-     * @param string $field_name The name of the field the formats are being retrieved for.
1501
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1502
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1503
-     * @return array formats in an array with the date format first, and the time format last.
1504
-     */
1505
-    public function get_formats_for($field_name, $pretty = false)
1506
-    {
1507
-        $field_settings = $this->field_settings_for($field_name);
1508
-        //if not a valid EE_Datetime_Field then throw error
1509
-        if (! $field_settings instanceof EE_Datetime_Field) {
1510
-            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.',
1511
-                'event_espresso'), $field_name));
1512
-        }
1513
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1514
-        //the field.
1515
-        $this->_timezone = $field_settings->get_timezone();
1516
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * This returns the current time in a format setup for a query on this model.
1523
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
-     * it will return:
1525
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1526
-     *  NOW
1527
-     *  - or a unix timestamp (equivalent to time())
1528
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
-     * @since 4.6.x
1532
-     * @param string $field_name       The field the current time is needed for.
1533
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1534
-     *                                 formatted string matching the set format for the field in the set timezone will
1535
-     *                                 be returned.
1536
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1537
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1538
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1539
-     *                                 exception is triggered.
1540
-     */
1541
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1542
-    {
1543
-        $formats = $this->get_formats_for($field_name);
1544
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1545
-        if ($timestamp) {
1546
-            return $DateTime->format('U');
1547
-        }
1548
-        //not returning timestamp, so return formatted string in timezone.
1549
-        switch ($what) {
1550
-            case 'time' :
1551
-                return $DateTime->format($formats[1]);
1552
-                break;
1553
-            case 'date' :
1554
-                return $DateTime->format($formats[0]);
1555
-                break;
1556
-            default :
1557
-                return $DateTime->format(implode(' ', $formats));
1558
-                break;
1559
-        }
1560
-    }
1561
-
1562
-
1563
-
1564
-    /**
1565
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1566
-     * for the model are.  Returns a DateTime object.
1567
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1568
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1569
-     * ignored.
1570
-     *
1571
-     * @param string $field_name      The field being setup.
1572
-     * @param string $timestring      The date time string being used.
1573
-     * @param string $incoming_format The format for the time string.
1574
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1575
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1576
-     *                                format is
1577
-     *                                'U', this is ignored.
1578
-     * @return DateTime
1579
-     * @throws EE_Error
1580
-     */
1581
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1582
-    {
1583
-        //just using this to ensure the timezone is set correctly internally
1584
-        $this->get_formats_for($field_name);
1585
-        //load EEH_DTT_Helper
1586
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1587
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1588
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1589
-    }
1590
-
1591
-
1592
-
1593
-    /**
1594
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1595
-     *
1596
-     * @return EE_Table_Base[]
1597
-     */
1598
-    public function get_tables()
1599
-    {
1600
-        return $this->_tables;
1601
-    }
1602
-
1603
-
1604
-
1605
-    /**
1606
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1607
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1608
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1609
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1610
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1611
-     * model object with EVT_ID = 1
1612
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1613
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1614
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1615
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1616
-     * are not specified)
1617
-     *
1618
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1619
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1620
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1621
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1622
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1623
-     *                                         ID=34, we'd use this method as follows:
1624
-     *                                         EEM_Transaction::instance()->update(
1625
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1626
-     *                                         array(array('TXN_ID'=>34)));
1627
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1628
-     *                                         in client code into what's expected to be stored on each field. Eg,
1629
-     *                                         consider updating Question's QST_admin_label field is of type
1630
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1631
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1632
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1633
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1634
-     *                                         TRUE, it is assumed that you've already called
1635
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1636
-     *                                         malicious javascript. However, if
1637
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1638
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1639
-     *                                         and every other field, before insertion. We provide this parameter
1640
-     *                                         because model objects perform their prepare_for_set function on all
1641
-     *                                         their values, and so don't need to be called again (and in many cases,
1642
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1643
-     *                                         prepare_for_set method...)
1644
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1645
-     *                                         in this model's entity map according to $fields_n_values that match
1646
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1647
-     *                                         by setting this to FALSE, but be aware that model objects being used
1648
-     *                                         could get out-of-sync with the database
1649
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1650
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1651
-     *                                         bad)
1652
-     * @throws EE_Error
1653
-     */
1654
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1655
-    {
1656
-        if (! is_array($query_params)) {
1657
-            EE_Error::doing_it_wrong('EEM_Base::update',
1658
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1659
-                    gettype($query_params)), '4.6.0');
1660
-            $query_params = array();
1661
-        }
1662
-        /**
1663
-         * Action called before a model update call has been made.
1664
-         *
1665
-         * @param EEM_Base $model
1666
-         * @param array    $fields_n_values the updated fields and their new values
1667
-         * @param array    $query_params    @see EEM_Base::get_all()
1668
-         */
1669
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1670
-        /**
1671
-         * Filters the fields about to be updated given the query parameters. You can provide the
1672
-         * $query_params to $this->get_all() to find exactly which records will be updated
1673
-         *
1674
-         * @param array    $fields_n_values fields and their new values
1675
-         * @param EEM_Base $model           the model being queried
1676
-         * @param array    $query_params    see EEM_Base::get_all()
1677
-         */
1678
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1679
-            $query_params);
1680
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1681
-        //to do that, for each table, verify that it's PK isn't null.
1682
-        $tables = $this->get_tables();
1683
-        //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
1684
-        //NOTE: we should make this code more efficient by NOT querying twice
1685
-        //before the real update, but that needs to first go through ALPHA testing
1686
-        //as it's dangerous. says Mike August 8 2014
1687
-        //we want to make sure the default_where strategy is ignored
1688
-        $this->_ignore_where_strategy = true;
1689
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1690
-        foreach ($wpdb_select_results as $wpdb_result) {
1691
-            // type cast stdClass as array
1692
-            $wpdb_result = (array)$wpdb_result;
1693
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1694
-            if ($this->has_primary_key_field()) {
1695
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1696
-            } else {
1697
-                //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)
1698
-                $main_table_pk_value = null;
1699
-            }
1700
-            //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
1701
-            //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
1702
-            if (count($tables) > 1) {
1703
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1704
-                //in that table, and so we'll want to insert one
1705
-                foreach ($tables as $table_obj) {
1706
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1707
-                    //if there is no private key for this table on the results, it means there's no entry
1708
-                    //in this table, right? so insert a row in the current table, using any fields available
1709
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1710
-                           && $wpdb_result[$this_table_pk_column])
1711
-                    ) {
1712
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1713
-                            $main_table_pk_value);
1714
-                        //if we died here, report the error
1715
-                        if (! $success) {
1716
-                            return false;
1717
-                        }
1718
-                    }
1719
-                }
1720
-            }
1721
-            //				//and now check that if we have cached any models by that ID on the model, that
1722
-            //				//they also get updated properly
1723
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1724
-            //				if( $model_object ){
1725
-            //					foreach( $fields_n_values as $field => $value ){
1726
-            //						$model_object->set($field, $value);
1727
-            //let's make sure default_where strategy is followed now
1728
-            $this->_ignore_where_strategy = false;
1729
-        }
1730
-        //if we want to keep model objects in sync, AND
1731
-        //if this wasn't called from a model object (to update itself)
1732
-        //then we want to make sure we keep all the existing
1733
-        //model objects in sync with the db
1734
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1735
-            if ($this->has_primary_key_field()) {
1736
-                $model_objs_affected_ids = $this->get_col($query_params);
1737
-            } else {
1738
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1739
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1740
-                $model_objs_affected_ids = array();
1741
-                foreach ($models_affected_key_columns as $row) {
1742
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1743
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1744
-                }
1745
-            }
1746
-            if (! $model_objs_affected_ids) {
1747
-                //wait wait wait- if nothing was affected let's stop here
1748
-                return 0;
1749
-            }
1750
-            foreach ($model_objs_affected_ids as $id) {
1751
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1752
-                if ($model_obj_in_entity_map) {
1753
-                    foreach ($fields_n_values as $field => $new_value) {
1754
-                        $model_obj_in_entity_map->set($field, $new_value);
1755
-                    }
1756
-                }
1757
-            }
1758
-            //if there is a primary key on this model, we can now do a slight optimization
1759
-            if ($this->has_primary_key_field()) {
1760
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1761
-                $query_params = array(
1762
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1763
-                    'limit'                    => count($model_objs_affected_ids),
1764
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1765
-                );
1766
-            }
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $SQL = "UPDATE "
1770
-               . $model_query_info->get_full_join_sql()
1771
-               . " SET "
1772
-               . $this->_construct_update_sql($fields_n_values)
1773
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1774
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1775
-        /**
1776
-         * Action called after a model update call has been made.
1777
-         *
1778
-         * @param EEM_Base $model
1779
-         * @param array    $fields_n_values the updated fields and their new values
1780
-         * @param array    $query_params    @see EEM_Base::get_all()
1781
-         * @param int      $rows_affected
1782
-         */
1783
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1784
-        return $rows_affected;//how many supposedly got updated
1785
-    }
1786
-
1787
-
1788
-
1789
-    /**
1790
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1791
-     * are teh values of the field specified (or by default the primary key field)
1792
-     * that matched the query params. Note that you should pass the name of the
1793
-     * model FIELD, not the database table's column name.
1794
-     *
1795
-     * @param array  $query_params @see EEM_Base::get_all()
1796
-     * @param string $field_to_select
1797
-     * @return array just like $wpdb->get_col()
1798
-     * @throws EE_Error
1799
-     */
1800
-    public function get_col($query_params = array(), $field_to_select = null)
1801
-    {
1802
-        if ($field_to_select) {
1803
-            $field = $this->field_settings_for($field_to_select);
1804
-        } elseif ($this->has_primary_key_field()) {
1805
-            $field = $this->get_primary_key_field();
1806
-        } else {
1807
-            //no primary key, just grab the first column
1808
-            $field = reset($this->field_settings());
1809
-        }
1810
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1811
-        $select_expressions = $field->get_qualified_column();
1812
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1813
-        return $this->_do_wpdb_query('get_col', array($SQL));
1814
-    }
1815
-
1816
-
1817
-
1818
-    /**
1819
-     * Returns a single column value for a single row from the database
1820
-     *
1821
-     * @param array  $query_params    @see EEM_Base::get_all()
1822
-     * @param string $field_to_select @see EEM_Base::get_col()
1823
-     * @return string
1824
-     * @throws EE_Error
1825
-     */
1826
-    public function get_var($query_params = array(), $field_to_select = null)
1827
-    {
1828
-        $query_params['limit'] = 1;
1829
-        $col = $this->get_col($query_params, $field_to_select);
1830
-        if (! empty($col)) {
1831
-            return reset($col);
1832
-        }
1833
-        return null;
1834
-    }
1835
-
1836
-
1837
-
1838
-    /**
1839
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1840
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1841
-     * injection, but currently no further filtering is done
1842
-     *
1843
-     * @global      $wpdb
1844
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1845
-     *                               be updated to in the DB
1846
-     * @return string of SQL
1847
-     * @throws EE_Error
1848
-     */
1849
-    public function _construct_update_sql($fields_n_values)
1850
-    {
1851
-        /** @type WPDB $wpdb */
1852
-        global $wpdb;
1853
-        $cols_n_values = array();
1854
-        foreach ($fields_n_values as $field_name => $value) {
1855
-            $field_obj = $this->field_settings_for($field_name);
1856
-            //if the value is NULL, we want to assign the value to that.
1857
-            //wpdb->prepare doesn't really handle that properly
1858
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1859
-            $value_sql = $prepared_value === null ? 'NULL'
1860
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1861
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1862
-        }
1863
-        return implode(",", $cols_n_values);
1864
-    }
1865
-
1866
-
1867
-
1868
-    /**
1869
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1870
-     * Performs a HARD delete, meaning the database row should always be removed,
1871
-     * not just have a flag field on it switched
1872
-     * Wrapper for EEM_Base::delete_permanently()
1873
-     *
1874
-     * @param mixed $id
1875
-     * @param boolean $allow_blocking
1876
-     * @return int the number of rows deleted
1877
-     * @throws EE_Error
1878
-     */
1879
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1880
-    {
1881
-        return $this->delete_permanently(
1882
-            array(
1883
-                array($this->get_primary_key_field()->get_name() => $id),
1884
-                'limit' => 1,
1885
-            ),
1886
-            $allow_blocking
1887
-        );
1888
-    }
1889
-
1890
-
1891
-
1892
-    /**
1893
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1894
-     * Wrapper for EEM_Base::delete()
1895
-     *
1896
-     * @param mixed $id
1897
-     * @param boolean $allow_blocking
1898
-     * @return int the number of rows deleted
1899
-     * @throws EE_Error
1900
-     */
1901
-    public function delete_by_ID($id, $allow_blocking = true)
1902
-    {
1903
-        return $this->delete(
1904
-            array(
1905
-                array($this->get_primary_key_field()->get_name() => $id),
1906
-                'limit' => 1,
1907
-            ),
1908
-            $allow_blocking
1909
-        );
1910
-    }
1911
-
1912
-
1913
-
1914
-    /**
1915
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1916
-     * meaning if the model has a field that indicates its been "trashed" or
1917
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1918
-     *
1919
-     * @see EEM_Base::delete_permanently
1920
-     * @param array   $query_params
1921
-     * @param boolean $allow_blocking
1922
-     * @return int how many rows got deleted
1923
-     * @throws EE_Error
1924
-     */
1925
-    public function delete($query_params, $allow_blocking = true)
1926
-    {
1927
-        return $this->delete_permanently($query_params, $allow_blocking);
1928
-    }
1929
-
1930
-
1931
-
1932
-    /**
1933
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1934
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1935
-     * as archived, not actually deleted
1936
-     *
1937
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1938
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1939
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1940
-     *                                deletes regardless of other objects which may depend on it. Its generally
1941
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1942
-     *                                DB
1943
-     * @return int how many rows got deleted
1944
-     * @throws EE_Error
1945
-     */
1946
-    public function delete_permanently($query_params, $allow_blocking = true)
1947
-    {
1948
-        /**
1949
-         * Action called just before performing a real deletion query. You can use the
1950
-         * model and its $query_params to find exactly which items will be deleted
1951
-         *
1952
-         * @param EEM_Base $model
1953
-         * @param array    $query_params   @see EEM_Base::get_all()
1954
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1955
-         *                                 to block (prevent) this deletion
1956
-         */
1957
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1958
-        //some MySQL databases may be running safe mode, which may restrict
1959
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1960
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1961
-        //to delete them
1962
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1963
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1964
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1965
-            $columns_and_ids_for_deleting
1966
-        );
1967
-        /**
1968
-         * Allows client code to act on the items being deleted before the query is actually executed.
1969
-         *
1970
-         * @param EEM_Base $this  The model instance being acted on.
1971
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1972
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1973
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1974
-         *                                                  derived from the incoming query parameters.
1975
-         *                                                  @see details on the structure of this array in the phpdocs
1976
-         *                                                  for the `_get_ids_for_delete_method`
1977
-         *
1978
-         */
1979
-        do_action('AHEE__EEM_Base__delete__before_query',
1980
-            $this,
1981
-            $query_params,
1982
-            $allow_blocking,
1983
-            $columns_and_ids_for_deleting
1984
-        );
1985
-        if ($deletion_where_query_part) {
1986
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1987
-            $table_aliases = array_keys($this->_tables);
1988
-            $SQL = "DELETE "
1989
-                   . implode(", ", $table_aliases)
1990
-                   . " FROM "
1991
-                   . $model_query_info->get_full_join_sql()
1992
-                   . " WHERE "
1993
-                   . $deletion_where_query_part;
1994
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1995
-        } else {
1996
-            $rows_deleted = 0;
1997
-        }
1998
-
1999
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2000
-        //there was no error with the delete query.
2001
-        if ($this->has_primary_key_field()
2002
-            && $rows_deleted !== false
2003
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2004
-        ) {
2005
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2006
-            foreach ($ids_for_removal as $id) {
2007
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2008
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2009
-                }
2010
-            }
2011
-
2012
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2013
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2014
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2015
-            // (although it is possible).
2016
-            //Note this can be skipped by using the provided filter and returning false.
2017
-            if (apply_filters(
2018
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2019
-                ! $this instanceof EEM_Extra_Meta,
2020
-                $this
2021
-            )) {
2022
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2023
-                    0 => array(
2024
-                        'EXM_type' => $this->get_this_model_name(),
2025
-                        'OBJ_ID'   => array(
2026
-                            'IN',
2027
-                            $ids_for_removal
2028
-                        )
2029
-                    )
2030
-                ));
2031
-            }
2032
-        }
2033
-
2034
-        /**
2035
-         * Action called just after performing a real deletion query. Although at this point the
2036
-         * items should have been deleted
2037
-         *
2038
-         * @param EEM_Base $model
2039
-         * @param array    $query_params @see EEM_Base::get_all()
2040
-         * @param int      $rows_deleted
2041
-         */
2042
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2043
-        return $rows_deleted;//how many supposedly got deleted
2044
-    }
2045
-
2046
-
2047
-
2048
-    /**
2049
-     * Checks all the relations that throw error messages when there are blocking related objects
2050
-     * for related model objects. If there are any related model objects on those relations,
2051
-     * adds an EE_Error, and return true
2052
-     *
2053
-     * @param EE_Base_Class|int $this_model_obj_or_id
2054
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2055
-     *                                                 should be ignored when determining whether there are related
2056
-     *                                                 model objects which block this model object's deletion. Useful
2057
-     *                                                 if you know A is related to B and are considering deleting A,
2058
-     *                                                 but want to see if A has any other objects blocking its deletion
2059
-     *                                                 before removing the relation between A and B
2060
-     * @return boolean
2061
-     * @throws EE_Error
2062
-     */
2063
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2064
-    {
2065
-        //first, if $ignore_this_model_obj was supplied, get its model
2066
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2067
-            $ignored_model = $ignore_this_model_obj->get_model();
2068
-        } else {
2069
-            $ignored_model = null;
2070
-        }
2071
-        //now check all the relations of $this_model_obj_or_id and see if there
2072
-        //are any related model objects blocking it?
2073
-        $is_blocked = false;
2074
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2075
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2076
-                //if $ignore_this_model_obj was supplied, then for the query
2077
-                //on that model needs to be told to ignore $ignore_this_model_obj
2078
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2079
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2080
-                        array(
2081
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2082
-                                '!=',
2083
-                                $ignore_this_model_obj->ID(),
2084
-                            ),
2085
-                        ),
2086
-                    ));
2087
-                } else {
2088
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2089
-                }
2090
-                if ($related_model_objects) {
2091
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2092
-                    $is_blocked = true;
2093
-                }
2094
-            }
2095
-        }
2096
-        return $is_blocked;
2097
-    }
2098
-
2099
-
2100
-    /**
2101
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2102
-     * @param array $row_results_for_deleting
2103
-     * @param bool  $allow_blocking
2104
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2105
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2106
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2107
-     *                 deleted. Example:
2108
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2109
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2110
-     *                 where each element is a group of columns and values that get deleted. Example:
2111
-     *                      array(
2112
-     *                          0 => array(
2113
-     *                              'Term_Relationship.object_id' => 1
2114
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2115
-     *                          ),
2116
-     *                          1 => array(
2117
-     *                              'Term_Relationship.object_id' => 1
2118
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2119
-     *                          )
2120
-     *                      )
2121
-     * @throws EE_Error
2122
-     */
2123
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2124
-    {
2125
-        $ids_to_delete_indexed_by_column = array();
2126
-        if ($this->has_primary_key_field()) {
2127
-            $primary_table = $this->_get_main_table();
2128
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2129
-            $other_tables = $this->_get_other_tables();
2130
-            $ids_to_delete_indexed_by_column = $query = array();
2131
-            foreach ($row_results_for_deleting as $item_to_delete) {
2132
-                //before we mark this item for deletion,
2133
-                //make sure there's no related entities blocking its deletion (if we're checking)
2134
-                if (
2135
-                    $allow_blocking
2136
-                    && $this->delete_is_blocked_by_related_models(
2137
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2138
-                    )
2139
-                ) {
2140
-                    continue;
2141
-                }
2142
-                //primary table deletes
2143
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2144
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2145
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2146
-                }
2147
-            }
2148
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2149
-            $fields = $this->get_combined_primary_key_fields();
2150
-            foreach ($row_results_for_deleting as $item_to_delete) {
2151
-                $ids_to_delete_indexed_by_column_for_row = array();
2152
-                foreach ($fields as $cpk_field) {
2153
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2154
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2155
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2156
-                    }
2157
-                }
2158
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2159
-            }
2160
-        } else {
2161
-            //so there's no primary key and no combined key...
2162
-            //sorry, can't help you
2163
-            throw new EE_Error(
2164
-                sprintf(
2165
-                    __(
2166
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2167
-                        "event_espresso"
2168
-                    ), get_class($this)
2169
-                )
2170
-            );
2171
-        }    
2172
-        return $ids_to_delete_indexed_by_column;
2173
-    }
2174
-
2175
-
2176
-    /**
2177
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2178
-     * the corresponding query_part for the query performing the delete.
2179
-     *
2180
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2181
-     * @return string
2182
-     * @throws EE_Error
2183
-     */
2184
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2185
-        $query_part = '';
2186
-        if (empty($ids_to_delete_indexed_by_column)) {
2187
-            return $query_part;
2188
-        } elseif ($this->has_primary_key_field()) {
2189
-            $query = array();
2190
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2191
-                //make sure we have unique $ids
2192
-                $ids = array_unique($ids);
2193
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2194
-            }
2195
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2196
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2197
-            $ways_to_identify_a_row = array();
2198
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2199
-                $values_for_each_combined_primary_key_for_a_row = array();
2200
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2201
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2202
-                }
2203
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2204
-            }
2205
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2206
-        }
2207
-        return $query_part;
2208
-    }
35
+	/**
36
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
37
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
38
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
39
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
40
+	 *
41
+	 * @var boolean
42
+	 */
43
+	private $_values_already_prepared_by_model_object = 0;
44
+
45
+	/**
46
+	 * when $_values_already_prepared_by_model_object equals this, we assume
47
+	 * the data is just like form input that needs to have the model fields'
48
+	 * prepare_for_set and prepare_for_use_in_db called on it
49
+	 */
50
+	const not_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we
54
+	 * assume this value is coming from a model object and doesn't need to have
55
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
56
+	 */
57
+	const prepared_by_model_object = 1;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we assume
61
+	 * the values are already to be used in the database (ie no processing is done
62
+	 * on them by the model's fields)
63
+	 */
64
+	const prepared_for_use_in_db = 2;
65
+
66
+
67
+	protected $singular_item = 'Item';
68
+
69
+	protected $plural_item   = 'Items';
70
+
71
+	/**
72
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
73
+	 */
74
+	protected $_tables;
75
+
76
+	/**
77
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
78
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
79
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
80
+	 *
81
+	 * @var \EE_Model_Field_Base[][] $_fields
82
+	 */
83
+	protected $_fields;
84
+
85
+	/**
86
+	 * array of different kinds of relations
87
+	 *
88
+	 * @var \EE_Model_Relation_Base[] $_model_relations
89
+	 */
90
+	protected $_model_relations;
91
+
92
+	/**
93
+	 * @var \EE_Index[] $_indexes
94
+	 */
95
+	protected $_indexes = array();
96
+
97
+	/**
98
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
99
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
100
+	 * by setting the same columns as used in these queries in the query yourself.
101
+	 *
102
+	 * @var EE_Default_Where_Conditions
103
+	 */
104
+	protected $_default_where_conditions_strategy;
105
+
106
+	/**
107
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
108
+	 * This is particularly useful when you want something between 'none' and 'default'
109
+	 *
110
+	 * @var EE_Default_Where_Conditions
111
+	 */
112
+	protected $_minimum_where_conditions_strategy;
113
+
114
+	/**
115
+	 * String describing how to find the "owner" of this model's objects.
116
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
117
+	 * But when there isn't, this indicates which related model, or transiently-related model,
118
+	 * has the foreign key to the wp_users table.
119
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
120
+	 * related to events, and events have a foreign key to wp_users.
121
+	 * On EEM_Transaction, this would be 'Transaction.Event'
122
+	 *
123
+	 * @var string
124
+	 */
125
+	protected $_model_chain_to_wp_user = '';
126
+
127
+	/**
128
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
129
+	 * don't need it (particularly CPT models)
130
+	 *
131
+	 * @var bool
132
+	 */
133
+	protected $_ignore_where_strategy = false;
134
+
135
+	/**
136
+	 * String used in caps relating to this model. Eg, if the caps relating to this
137
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
138
+	 *
139
+	 * @var string. If null it hasn't been initialized yet. If false then we
140
+	 * have indicated capabilities don't apply to this
141
+	 */
142
+	protected $_caps_slug = null;
143
+
144
+	/**
145
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
146
+	 * and next-level keys are capability names, and each's value is a
147
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
148
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
149
+	 * and then each capability in the corresponding sub-array that they're missing
150
+	 * adds the where conditions onto the query.
151
+	 *
152
+	 * @var array
153
+	 */
154
+	protected $_cap_restrictions = array(
155
+		self::caps_read       => array(),
156
+		self::caps_read_admin => array(),
157
+		self::caps_edit       => array(),
158
+		self::caps_delete     => array(),
159
+	);
160
+
161
+	/**
162
+	 * Array defining which cap restriction generators to use to create default
163
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
164
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
165
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
166
+	 * automatically set this to false (not just null).
167
+	 *
168
+	 * @var EE_Restriction_Generator_Base[]
169
+	 */
170
+	protected $_cap_restriction_generators = array();
171
+
172
+	/**
173
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
174
+	 */
175
+	const caps_read       = 'read';
176
+
177
+	const caps_read_admin = 'read_admin';
178
+
179
+	const caps_edit       = 'edit';
180
+
181
+	const caps_delete     = 'delete';
182
+
183
+	/**
184
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
185
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
186
+	 * maps to 'read' because when looking for relevant permissions we're going to use
187
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
188
+	 *
189
+	 * @var array
190
+	 */
191
+	protected $_cap_contexts_to_cap_action_map = array(
192
+		self::caps_read       => 'read',
193
+		self::caps_read_admin => 'read',
194
+		self::caps_edit       => 'edit',
195
+		self::caps_delete     => 'delete',
196
+	);
197
+
198
+	/**
199
+	 * Timezone
200
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
201
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
202
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
203
+	 * EE_Datetime_Field data type will have access to it.
204
+	 *
205
+	 * @var string
206
+	 */
207
+	protected $_timezone;
208
+
209
+
210
+	/**
211
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
212
+	 * multisite.
213
+	 *
214
+	 * @var int
215
+	 */
216
+	protected static $_model_query_blog_id;
217
+
218
+	/**
219
+	 * A copy of _fields, except the array keys are the model names pointed to by
220
+	 * the field
221
+	 *
222
+	 * @var EE_Model_Field_Base[]
223
+	 */
224
+	private $_cache_foreign_key_to_fields = array();
225
+
226
+	/**
227
+	 * Cached list of all the fields on the model, indexed by their name
228
+	 *
229
+	 * @var EE_Model_Field_Base[]
230
+	 */
231
+	private $_cached_fields = null;
232
+
233
+	/**
234
+	 * Cached list of all the fields on the model, except those that are
235
+	 * marked as only pertinent to the database
236
+	 *
237
+	 * @var EE_Model_Field_Base[]
238
+	 */
239
+	private $_cached_fields_non_db_only = null;
240
+
241
+	/**
242
+	 * A cached reference to the primary key for quick lookup
243
+	 *
244
+	 * @var EE_Model_Field_Base
245
+	 */
246
+	private $_primary_key_field = null;
247
+
248
+	/**
249
+	 * Flag indicating whether this model has a primary key or not
250
+	 *
251
+	 * @var boolean
252
+	 */
253
+	protected $_has_primary_key_field = null;
254
+
255
+	/**
256
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
257
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
258
+	 * This should be true for models that deal with data that should exist independent of EE.
259
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
260
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
261
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
262
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
263
+	 * @var boolean
264
+	 */
265
+	protected $_wp_core_model = false;
266
+
267
+	/**
268
+	 *    List of valid operators that can be used for querying.
269
+	 * The keys are all operators we'll accept, the values are the real SQL
270
+	 * operators used
271
+	 *
272
+	 * @var array
273
+	 */
274
+	protected $_valid_operators = array(
275
+		'='           => '=',
276
+		'<='          => '<=',
277
+		'<'           => '<',
278
+		'>='          => '>=',
279
+		'>'           => '>',
280
+		'!='          => '!=',
281
+		'LIKE'        => 'LIKE',
282
+		'like'        => 'LIKE',
283
+		'NOT_LIKE'    => 'NOT LIKE',
284
+		'not_like'    => 'NOT LIKE',
285
+		'NOT LIKE'    => 'NOT LIKE',
286
+		'not like'    => 'NOT LIKE',
287
+		'IN'          => 'IN',
288
+		'in'          => 'IN',
289
+		'NOT_IN'      => 'NOT IN',
290
+		'not_in'      => 'NOT IN',
291
+		'NOT IN'      => 'NOT IN',
292
+		'not in'      => 'NOT IN',
293
+		'between'     => 'BETWEEN',
294
+		'BETWEEN'     => 'BETWEEN',
295
+		'IS_NOT_NULL' => 'IS NOT NULL',
296
+		'is_not_null' => 'IS NOT NULL',
297
+		'IS NOT NULL' => 'IS NOT NULL',
298
+		'is not null' => 'IS NOT NULL',
299
+		'IS_NULL'     => 'IS NULL',
300
+		'is_null'     => 'IS NULL',
301
+		'IS NULL'     => 'IS NULL',
302
+		'is null'     => 'IS NULL',
303
+		'REGEXP'      => 'REGEXP',
304
+		'regexp'      => 'REGEXP',
305
+		'NOT_REGEXP'  => 'NOT REGEXP',
306
+		'not_regexp'  => 'NOT REGEXP',
307
+		'NOT REGEXP'  => 'NOT REGEXP',
308
+		'not regexp'  => 'NOT REGEXP',
309
+	);
310
+
311
+	/**
312
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
313
+	 *
314
+	 * @var array
315
+	 */
316
+	protected $_in_style_operators = array('IN', 'NOT IN');
317
+
318
+	/**
319
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
320
+	 * '12-31-2012'"
321
+	 *
322
+	 * @var array
323
+	 */
324
+	protected $_between_style_operators = array('BETWEEN');
325
+
326
+	/**
327
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
328
+	 * @var array
329
+	 */
330
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
331
+	/**
332
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
333
+	 * on a join table.
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
338
+
339
+	/**
340
+	 * Allowed values for $query_params['order'] for ordering in queries
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
345
+
346
+	/**
347
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
348
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
349
+	 *
350
+	 * @var array
351
+	 */
352
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
353
+
354
+	/**
355
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
356
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_allowed_query_params = array(
361
+		0,
362
+		'limit',
363
+		'order_by',
364
+		'group_by',
365
+		'having',
366
+		'force_join',
367
+		'order',
368
+		'on_join_limit',
369
+		'default_where_conditions',
370
+		'caps',
371
+	);
372
+
373
+	/**
374
+	 * All the data types that can be used in $wpdb->prepare statements.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
379
+
380
+	/**
381
+	 * @var EE_Registry $EE
382
+	 */
383
+	protected $EE = null;
384
+
385
+
386
+	/**
387
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
+	 *
389
+	 * @var int
390
+	 */
391
+	protected $_show_next_x_db_queries = 0;
392
+
393
+	/**
394
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
+	 *
397
+	 * @var array
398
+	 */
399
+	protected $_custom_selections = array();
400
+
401
+	/**
402
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
+	 * caches every model object we've fetched from the DB on this request
404
+	 *
405
+	 * @var array
406
+	 */
407
+	protected $_entity_map;
408
+
409
+	/**
410
+	 * @var LoaderInterface $loader
411
+	 */
412
+	private static $loader;
413
+
414
+
415
+	/**
416
+	 * constant used to show EEM_Base has not yet verified the db on this http request
417
+	 */
418
+	const db_verified_none = 0;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
422
+	 * but not the addons' dbs
423
+	 */
424
+	const db_verified_core = 1;
425
+
426
+	/**
427
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
428
+	 * the EE core db too)
429
+	 */
430
+	const db_verified_addons = 2;
431
+
432
+	/**
433
+	 * indicates whether an EEM_Base child has already re-verified the DB
434
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
435
+	 * looking like EEM_Base::db_verified_*
436
+	 *
437
+	 * @var int - 0 = none, 1 = core, 2 = addons
438
+	 */
439
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
440
+
441
+	/**
442
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
443
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
444
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
445
+	 */
446
+	const default_where_conditions_all = 'all';
447
+
448
+	/**
449
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
450
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
451
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
452
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
453
+	 *        models which share tables with other models, this can return data for the wrong model.
454
+	 */
455
+	const default_where_conditions_this_only = 'this_model_only';
456
+
457
+	/**
458
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
459
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
460
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
461
+	 */
462
+	const default_where_conditions_others_only = 'other_models_only';
463
+
464
+	/**
465
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
466
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
467
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
468
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
469
+	 *        (regardless of whether those events and venues are trashed)
470
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
471
+	 *        events.
472
+	 */
473
+	const default_where_conditions_minimum_all = 'minimum';
474
+
475
+	/**
476
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
477
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
478
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
479
+	 *        not)
480
+	 */
481
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
+
483
+	/**
484
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
485
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
486
+	 *        it's possible it will return table entries for other models. You should use
487
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
488
+	 */
489
+	const default_where_conditions_none = 'none';
490
+
491
+
492
+
493
+	/**
494
+	 * About all child constructors:
495
+	 * they should define the _tables, _fields and _model_relations arrays.
496
+	 * Should ALWAYS be called after child constructor.
497
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
498
+	 * finalizes constructing all the object's attributes.
499
+	 * Generally, rather than requiring a child to code
500
+	 * $this->_tables = array(
501
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
502
+	 *        ...);
503
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
504
+	 * each EE_Table has a function to set the table's alias after the constructor, using
505
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
506
+	 * do something similar.
507
+	 *
508
+	 * @param null $timezone
509
+	 * @throws EE_Error
510
+	 */
511
+	protected function __construct($timezone = null)
512
+	{
513
+		// check that the model has not been loaded too soon
514
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
+			throw new EE_Error (
516
+				sprintf(
517
+					__('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.',
518
+						'event_espresso'),
519
+					get_class($this)
520
+				)
521
+			);
522
+		}
523
+		/**
524
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
525
+		 */
526
+		if (empty(EEM_Base::$_model_query_blog_id)) {
527
+			EEM_Base::set_model_query_blog_id();
528
+		}
529
+		/**
530
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
531
+		 * just use EE_Register_Model_Extension
532
+		 *
533
+		 * @var EE_Table_Base[] $_tables
534
+		 */
535
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
536
+		foreach ($this->_tables as $table_alias => $table_obj) {
537
+			/** @var $table_obj EE_Table_Base */
538
+			$table_obj->_construct_finalize_with_alias($table_alias);
539
+			if ($table_obj instanceof EE_Secondary_Table) {
540
+				/** @var $table_obj EE_Secondary_Table */
541
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
542
+			}
543
+		}
544
+		/**
545
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
546
+		 * EE_Register_Model_Extension
547
+		 *
548
+		 * @param EE_Model_Field_Base[] $_fields
549
+		 */
550
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
551
+		$this->_invalidate_field_caches();
552
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
553
+			if (! array_key_exists($table_alias, $this->_tables)) {
554
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
556
+			}
557
+			foreach ($fields_for_table as $field_name => $field_obj) {
558
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
559
+				//primary key field base has a slightly different _construct_finalize
560
+				/** @var $field_obj EE_Model_Field_Base */
561
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
562
+			}
563
+		}
564
+		// everything is related to Extra_Meta
565
+		if (get_class($this) !== 'EEM_Extra_Meta') {
566
+			//make extra meta related to everything, but don't block deleting things just
567
+			//because they have related extra meta info. For now just orphan those extra meta
568
+			//in the future we should automatically delete them
569
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
570
+		}
571
+		//and change logs
572
+		if (get_class($this) !== 'EEM_Change_Log') {
573
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		/**
576
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
577
+		 * EE_Register_Model_Extension
578
+		 *
579
+		 * @param EE_Model_Relation_Base[] $_model_relations
580
+		 */
581
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
582
+			$this->_model_relations);
583
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
584
+			/** @var $relation_obj EE_Model_Relation_Base */
585
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
586
+		}
587
+		foreach ($this->_indexes as $index_name => $index_obj) {
588
+			/** @var $index_obj EE_Index */
589
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
590
+		}
591
+		$this->set_timezone($timezone);
592
+		//finalize default where condition strategy, or set default
593
+		if (! $this->_default_where_conditions_strategy) {
594
+			//nothing was set during child constructor, so set default
595
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596
+		}
597
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
598
+		if (! $this->_minimum_where_conditions_strategy) {
599
+			//nothing was set during child constructor, so set default
600
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601
+		}
602
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
603
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
604
+		//to indicate to NOT set it, set it to the logical default
605
+		if ($this->_caps_slug === null) {
606
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
607
+		}
608
+		//initialize the standard cap restriction generators if none were specified by the child constructor
609
+		if ($this->_cap_restriction_generators !== false) {
610
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
612
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
613
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614
+						new EE_Restriction_Generator_Protected(),
615
+						$cap_context,
616
+						$this
617
+					);
618
+				}
619
+			}
620
+		}
621
+		//if there are cap restriction generators, use them to make the default cap restrictions
622
+		if ($this->_cap_restriction_generators !== false) {
623
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
+				if (! $generator_object) {
625
+					continue;
626
+				}
627
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
628
+					throw new EE_Error(
629
+						sprintf(
630
+							__('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.',
631
+								'event_espresso'),
632
+							$context,
633
+							$this->get_this_model_name()
634
+						)
635
+					);
636
+				}
637
+				$action = $this->cap_action_for_context($context);
638
+				if (! $generator_object->construction_finalized()) {
639
+					$generator_object->_construct_finalize($this, $action);
640
+				}
641
+			}
642
+		}
643
+		do_action('AHEE__' . get_class($this) . '__construct__end');
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * Used to set the $_model_query_blog_id static property.
650
+	 *
651
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
652
+	 *                      value for get_current_blog_id() will be used.
653
+	 */
654
+	public static function set_model_query_blog_id($blog_id = 0)
655
+	{
656
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
657
+	}
658
+
659
+
660
+
661
+	/**
662
+	 * Returns whatever is set as the internal $model_query_blog_id.
663
+	 *
664
+	 * @return int
665
+	 */
666
+	public static function get_model_query_blog_id()
667
+	{
668
+		return EEM_Base::$_model_query_blog_id;
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * This function is a singleton method used to instantiate the Espresso_model object
675
+	 *
676
+	 * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
677
+	 *                                    (and any incoming timezone data that gets saved).
678
+	 *                                    Note this just sends the timezone info to the date time model field objects.
679
+	 *                                    Default is NULL
680
+	 *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
681
+	 * @param ModelFieldFactory $model_field_factory
682
+	 * @return static (as in the concrete child class)
683
+	 * @throws EE_Error
684
+	 * @throws InvalidArgumentException
685
+	 * @throws InvalidDataTypeException
686
+	 * @throws InvalidInterfaceException
687
+	 */
688
+	public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
689
+	{
690
+		// check if instance of Espresso_model already exists
691
+		if (! static::$_instance instanceof static) {
692
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
693
+			// instantiate Espresso_model
694
+			static::$_instance = new static($timezone, $model_field_factory);
695
+		}
696
+		//we might have a timezone set, let set_timezone decide what to do with it
697
+		static::$_instance->set_timezone($timezone);
698
+		// Espresso_model object
699
+		return static::$_instance;
700
+	}
701
+
702
+
703
+
704
+	/**
705
+	 * @param $model_field_factory
706
+	 * @return ModelFieldFactory
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidDataTypeException
709
+	 * @throws InvalidInterfaceException
710
+	 */
711
+	private static function getModelFieldFactory($model_field_factory)
712
+	{
713
+		return $model_field_factory instanceof ModelFieldFactory
714
+			? $model_field_factory
715
+			: LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory');
716
+	}
717
+
718
+
719
+
720
+	/**
721
+	 * resets the model and returns it
722
+	 *
723
+	 * @param null | string          $timezone
724
+	 * @param ModelFieldFactory|null $model_field_factory
725
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
726
+	 * all its properties reset; if it wasn't instantiated, returns null)
727
+	 * @throws EE_Error
728
+	 * @throws ReflectionException
729
+	 * @throws InvalidArgumentException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws InvalidInterfaceException
732
+	 */
733
+	public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
734
+	{
735
+		if (static::$_instance instanceof EEM_Base) {
736
+			//let's try to NOT swap out the current instance for a new one
737
+			//because if someone has a reference to it, we can't remove their reference
738
+			//so it's best to keep using the same reference, but change the original object
739
+			//reset all its properties to their original values as defined in the class
740
+			$r = new ReflectionClass(get_class(static::$_instance));
741
+			$static_properties = $r->getStaticProperties();
742
+			foreach ($r->getDefaultProperties() as $property => $value) {
743
+				//don't set instance to null like it was originally,
744
+				//but it's static anyways, and we're ignoring static properties (for now at least)
745
+				if (! isset($static_properties[$property])) {
746
+					static::$_instance->{$property} = $value;
747
+				}
748
+			}
749
+			//and then directly call its constructor again, like we would if we were creating a new one
750
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
751
+			static::$_instance->__construct($timezone, $model_field_factory);
752
+			return self::instance();
753
+		}
754
+		return null;
755
+	}
756
+
757
+
758
+
759
+	/**
760
+	 * @return LoaderInterface
761
+	 * @throws InvalidArgumentException
762
+	 * @throws InvalidDataTypeException
763
+	 * @throws InvalidInterfaceException
764
+	 */
765
+	private static function getLoader()
766
+	{
767
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
768
+			EEM_Base::$loader = LoaderFactory::getLoader();
769
+		}
770
+		return EEM_Base::$loader;
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
+	 *
778
+	 * @param  boolean $translated return localized strings or JUST the array.
779
+	 * @return array
780
+	 * @throws EE_Error
781
+	 * @throws InvalidArgumentException
782
+	 * @throws InvalidDataTypeException
783
+	 * @throws InvalidInterfaceException
784
+	 */
785
+	public function status_array($translated = false)
786
+	{
787
+		if (! array_key_exists('Status', $this->_model_relations)) {
788
+			return array();
789
+		}
790
+		$model_name = $this->get_this_model_name();
791
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
792
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
793
+		$status_array = array();
794
+		foreach ($stati as $status) {
795
+			$status_array[$status->ID()] = $status->get('STS_code');
796
+		}
797
+		return $translated
798
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
799
+			: $status_array;
800
+	}
801
+
802
+
803
+
804
+	/**
805
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
806
+	 *
807
+	 * @param array $query_params             {
808
+	 * @var array $0 (where) array {
809
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
810
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
811
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
812
+	 *                                        conditions based on related models (and even
813
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
814
+	 *                                        name. Eg,
815
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
816
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
817
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
818
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
819
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
820
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
821
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
822
+	 *                                        to Venues (even when each of those models actually consisted of two
823
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
824
+	 *                                        just having
825
+	 *                                        "Venue.VNU_ID", you could have
826
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
827
+	 *                                        events are related to Registrations, which are related to Attendees). You
828
+	 *                                        can take it even further with
829
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
830
+	 *                                        (from the default of '='), change the value to an numerically-indexed
831
+	 *                                        array, where the first item in the list is the operator. eg: array(
832
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
833
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
834
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
835
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
836
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
837
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
838
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
839
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
840
+	 *                                        the value is a field, simply provide a third array item (true) to the
841
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
842
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
843
+	 *                                        Note: you can also use related model field names like you would any other
844
+	 *                                        field name. eg:
845
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
846
+	 *                                        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__>' =>
847
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
848
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
849
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
850
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
851
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
852
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
853
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
854
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
855
+	 *                                        "stick" until you specify an AND. eg
856
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
857
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
858
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
859
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
860
+	 *                                        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 >>
861
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
862
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
863
+	 *                                        too, eg:
864
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
865
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
866
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
867
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
868
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
869
+	 *                                        the OFFSET, the 2nd is the LIMIT
870
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
871
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
872
+	 *                                        following format array('on_join_limit'
873
+	 *                                        => array( 'table_alias', array(1,2) ) ).
874
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
875
+	 *                                        values are either 'ASC' or 'DESC'.
876
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
877
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
878
+	 *                                        DESC..." respectively. Like the
879
+	 *                                        'where' conditions, these fields can be on related models. Eg
880
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
881
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
882
+	 *                                        Attendee, Price, Datetime, etc.)
883
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
884
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
885
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
886
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
887
+	 *                                        order by the primary key. Eg,
888
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
889
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
890
+	 *                                        DTT_EVT_start) or
891
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
892
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
893
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
894
+	 *                                        'group_by'=>'VNU_ID', or
895
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
896
+	 *                                        if no
897
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
898
+	 *                                        model's primary key (or combined primary keys). This avoids some
899
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
900
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
901
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
902
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
903
+	 *                                        results)
904
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
905
+	 *                                        array where values are models to be joined in the query.Eg
906
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
907
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
908
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
909
+	 *                                        related models which belongs to the current model
910
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
911
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
912
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
913
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
914
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
915
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
916
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
917
+	 *                                        this model's default where conditions added to the query, use
918
+	 *                                        'this_model_only'. If you want to use all default where conditions
919
+	 *                                        (default), set to 'all'.
920
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
921
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
922
+	 *                                        everything? Or should we only show the current user items they should be
923
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
924
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
925
+	 *                                        }
926
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
927
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
928
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
929
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
930
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
931
+	 *                                        array( array(
932
+	 *                                        'OR'=>array(
933
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
934
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
935
+	 *                                        )
936
+	 *                                        ),
937
+	 *                                        'limit'=>10,
938
+	 *                                        'group_by'=>'TXN_ID'
939
+	 *                                        ));
940
+	 *                                        get all the answers to the question titled "shirt size" for event with id
941
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
942
+	 *                                        'Question.QST_display_text'=>'shirt size',
943
+	 *                                        'Registration.Event.EVT_ID'=>12
944
+	 *                                        ),
945
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
946
+	 *                                        ));
947
+	 * @throws EE_Error
948
+	 */
949
+	public function get_all($query_params = array())
950
+	{
951
+		if (isset($query_params['limit'])
952
+			&& ! isset($query_params['group_by'])
953
+		) {
954
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
955
+		}
956
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
957
+	}
958
+
959
+
960
+
961
+	/**
962
+	 * Modifies the query parameters so we only get back model objects
963
+	 * that "belong" to the current user
964
+	 *
965
+	 * @param array $query_params @see EEM_Base::get_all()
966
+	 * @return array like EEM_Base::get_all
967
+	 */
968
+	public function alter_query_params_to_only_include_mine($query_params = array())
969
+	{
970
+		$wp_user_field_name = $this->wp_user_field_name();
971
+		if ($wp_user_field_name) {
972
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
973
+		}
974
+		return $query_params;
975
+	}
976
+
977
+
978
+
979
+	/**
980
+	 * Returns the name of the field's name that points to the WP_User table
981
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
982
+	 * foreign key to the WP_User table)
983
+	 *
984
+	 * @return string|boolean string on success, boolean false when there is no
985
+	 * foreign key to the WP_User table
986
+	 */
987
+	public function wp_user_field_name()
988
+	{
989
+		try {
990
+			if (! empty($this->_model_chain_to_wp_user)) {
991
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
992
+				$last_model_name = end($models_to_follow_to_wp_users);
993
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
994
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
995
+			} else {
996
+				$model_with_fk_to_wp_users = $this;
997
+				$model_chain_to_wp_user = '';
998
+			}
999
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1000
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
1001
+		} catch (EE_Error $e) {
1002
+			return false;
1003
+		}
1004
+	}
1005
+
1006
+
1007
+
1008
+	/**
1009
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1010
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1011
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1012
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1013
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1014
+	 * (or transiently-related model)
1015
+	 *
1016
+	 * @return string
1017
+	 */
1018
+	public function model_chain_to_wp_user()
1019
+	{
1020
+		return $this->_model_chain_to_wp_user;
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1027
+	 * like how registrations don't have a foreign key to wp_users, but the
1028
+	 * events they are for are), or is unrelated to wp users.
1029
+	 * generally available
1030
+	 *
1031
+	 * @return boolean
1032
+	 */
1033
+	public function is_owned()
1034
+	{
1035
+		if ($this->model_chain_to_wp_user()) {
1036
+			return true;
1037
+		}
1038
+		try {
1039
+			$this->get_foreign_key_to('WP_User');
1040
+			return true;
1041
+		} catch (EE_Error $e) {
1042
+			return false;
1043
+		}
1044
+	}
1045
+
1046
+
1047
+
1048
+	/**
1049
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1050
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1051
+	 * the model)
1052
+	 *
1053
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1054
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1055
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1056
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1057
+	 *                                  override this and set the select to "*", or a specific column name, like
1058
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1059
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1060
+	 *                                  the aliases used to refer to this selection, and values are to be
1061
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1062
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1063
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1064
+	 * @throws EE_Error
1065
+	 */
1066
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1067
+	{
1068
+		// remember the custom selections, if any, and type cast as array
1069
+		// (unless $columns_to_select is an object, then just set as an empty array)
1070
+		// Note: (array) 'some string' === array( 'some string' )
1071
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1072
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1073
+		$select_expressions = $columns_to_select !== null
1074
+			? $this->_construct_select_from_input($columns_to_select)
1075
+			: $this->_construct_default_select_sql($model_query_info);
1076
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1077
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1078
+	}
1079
+
1080
+
1081
+
1082
+	/**
1083
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1084
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1085
+	 * take care of joins, field preparation etc.
1086
+	 *
1087
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1088
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1089
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1090
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1091
+	 *                                  override this and set the select to "*", or a specific column name, like
1092
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1093
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1094
+	 *                                  the aliases used to refer to this selection, and values are to be
1095
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1096
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1097
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1098
+	 * @throws EE_Error
1099
+	 */
1100
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1101
+	{
1102
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1103
+	}
1104
+
1105
+
1106
+
1107
+	/**
1108
+	 * For creating a custom select statement
1109
+	 *
1110
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1111
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1112
+	 *                                 SQL, and 1=>is the datatype
1113
+	 * @throws EE_Error
1114
+	 * @return string
1115
+	 */
1116
+	private function _construct_select_from_input($columns_to_select)
1117
+	{
1118
+		if (is_array($columns_to_select)) {
1119
+			$select_sql_array = array();
1120
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1121
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1122
+					throw new EE_Error(
1123
+						sprintf(
1124
+							__(
1125
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1126
+								'event_espresso'
1127
+							),
1128
+							$selection_and_datatype,
1129
+							$alias
1130
+						)
1131
+					);
1132
+				}
1133
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1134
+					throw new EE_Error(
1135
+						sprintf(
1136
+							esc_html__(
1137
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1138
+								'event_espresso'
1139
+							),
1140
+							$selection_and_datatype[1],
1141
+							$selection_and_datatype[0],
1142
+							$alias,
1143
+							implode(', ', $this->_valid_wpdb_data_types)
1144
+						)
1145
+					);
1146
+				}
1147
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1148
+			}
1149
+			$columns_to_select_string = implode(', ', $select_sql_array);
1150
+		} else {
1151
+			$columns_to_select_string = $columns_to_select;
1152
+		}
1153
+		return $columns_to_select_string;
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1160
+	 *
1161
+	 * @return string
1162
+	 * @throws EE_Error
1163
+	 */
1164
+	public function primary_key_name()
1165
+	{
1166
+		return $this->get_primary_key_field()->get_name();
1167
+	}
1168
+
1169
+
1170
+
1171
+	/**
1172
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1173
+	 * If there is no primary key on this model, $id is treated as primary key string
1174
+	 *
1175
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1176
+	 * @return EE_Base_Class
1177
+	 */
1178
+	public function get_one_by_ID($id)
1179
+	{
1180
+		if ($this->get_from_entity_map($id)) {
1181
+			return $this->get_from_entity_map($id);
1182
+		}
1183
+		return $this->get_one(
1184
+			$this->alter_query_params_to_restrict_by_ID(
1185
+				$id,
1186
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1187
+			)
1188
+		);
1189
+	}
1190
+
1191
+
1192
+
1193
+	/**
1194
+	 * Alters query parameters to only get items with this ID are returned.
1195
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1196
+	 * or could just be a simple primary key ID
1197
+	 *
1198
+	 * @param int   $id
1199
+	 * @param array $query_params
1200
+	 * @return array of normal query params, @see EEM_Base::get_all
1201
+	 * @throws EE_Error
1202
+	 */
1203
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1204
+	{
1205
+		if (! isset($query_params[0])) {
1206
+			$query_params[0] = array();
1207
+		}
1208
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1209
+		if ($conditions_from_id === null) {
1210
+			$query_params[0][$this->primary_key_name()] = $id;
1211
+		} else {
1212
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1213
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1214
+		}
1215
+		return $query_params;
1216
+	}
1217
+
1218
+
1219
+
1220
+	/**
1221
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1222
+	 * array. If no item is found, null is returned.
1223
+	 *
1224
+	 * @param array $query_params like EEM_Base's $query_params variable.
1225
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1226
+	 * @throws EE_Error
1227
+	 */
1228
+	public function get_one($query_params = array())
1229
+	{
1230
+		if (! is_array($query_params)) {
1231
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1232
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1233
+					gettype($query_params)), '4.6.0');
1234
+			$query_params = array();
1235
+		}
1236
+		$query_params['limit'] = 1;
1237
+		$items = $this->get_all($query_params);
1238
+		if (empty($items)) {
1239
+			return null;
1240
+		}
1241
+		return array_shift($items);
1242
+	}
1243
+
1244
+
1245
+
1246
+	/**
1247
+	 * Returns the next x number of items in sequence from the given value as
1248
+	 * found in the database matching the given query conditions.
1249
+	 *
1250
+	 * @param mixed $current_field_value    Value used for the reference point.
1251
+	 * @param null  $field_to_order_by      What field is used for the
1252
+	 *                                      reference point.
1253
+	 * @param int   $limit                  How many to return.
1254
+	 * @param array $query_params           Extra conditions on the query.
1255
+	 * @param null  $columns_to_select      If left null, then an array of
1256
+	 *                                      EE_Base_Class objects is returned,
1257
+	 *                                      otherwise you can indicate just the
1258
+	 *                                      columns you want returned.
1259
+	 * @return EE_Base_Class[]|array
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function next_x(
1263
+		$current_field_value,
1264
+		$field_to_order_by = null,
1265
+		$limit = 1,
1266
+		$query_params = array(),
1267
+		$columns_to_select = null
1268
+	) {
1269
+		return $this->_get_consecutive(
1270
+			$current_field_value,
1271
+			'>',
1272
+			$field_to_order_by,
1273
+			$limit,
1274
+			$query_params,
1275
+			$columns_to_select
1276
+		);
1277
+	}
1278
+
1279
+
1280
+
1281
+	/**
1282
+	 * Returns the previous x number of items in sequence from the given value
1283
+	 * as found in the database matching the given query conditions.
1284
+	 *
1285
+	 * @param mixed $current_field_value    Value used for the reference point.
1286
+	 * @param null  $field_to_order_by      What field is used for the
1287
+	 *                                      reference point.
1288
+	 * @param int   $limit                  How many to return.
1289
+	 * @param array $query_params           Extra conditions on the query.
1290
+	 * @param null  $columns_to_select      If left null, then an array of
1291
+	 *                                      EE_Base_Class objects is returned,
1292
+	 *                                      otherwise you can indicate just the
1293
+	 *                                      columns you want returned.
1294
+	 * @return EE_Base_Class[]|array
1295
+	 * @throws EE_Error
1296
+	 */
1297
+	public function previous_x(
1298
+		$current_field_value,
1299
+		$field_to_order_by = null,
1300
+		$limit = 1,
1301
+		$query_params = array(),
1302
+		$columns_to_select = null
1303
+	) {
1304
+		return $this->_get_consecutive(
1305
+			$current_field_value,
1306
+			'<',
1307
+			$field_to_order_by,
1308
+			$limit,
1309
+			$query_params,
1310
+			$columns_to_select
1311
+		);
1312
+	}
1313
+
1314
+
1315
+
1316
+	/**
1317
+	 * Returns the next item in sequence from the given value as found in the
1318
+	 * database matching the given query conditions.
1319
+	 *
1320
+	 * @param mixed $current_field_value    Value used for the reference point.
1321
+	 * @param null  $field_to_order_by      What field is used for the
1322
+	 *                                      reference point.
1323
+	 * @param array $query_params           Extra conditions on the query.
1324
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1325
+	 *                                      object is returned, otherwise you
1326
+	 *                                      can indicate just the columns you
1327
+	 *                                      want and a single array indexed by
1328
+	 *                                      the columns will be returned.
1329
+	 * @return EE_Base_Class|null|array()
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	public function next(
1333
+		$current_field_value,
1334
+		$field_to_order_by = null,
1335
+		$query_params = array(),
1336
+		$columns_to_select = null
1337
+	) {
1338
+		$results = $this->_get_consecutive(
1339
+			$current_field_value,
1340
+			'>',
1341
+			$field_to_order_by,
1342
+			1,
1343
+			$query_params,
1344
+			$columns_to_select
1345
+		);
1346
+		return empty($results) ? null : reset($results);
1347
+	}
1348
+
1349
+
1350
+
1351
+	/**
1352
+	 * Returns the previous item in sequence from the given value as found in
1353
+	 * the database matching the given query conditions.
1354
+	 *
1355
+	 * @param mixed $current_field_value    Value used for the reference point.
1356
+	 * @param null  $field_to_order_by      What field is used for the
1357
+	 *                                      reference point.
1358
+	 * @param array $query_params           Extra conditions on the query.
1359
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1360
+	 *                                      object is returned, otherwise you
1361
+	 *                                      can indicate just the columns you
1362
+	 *                                      want and a single array indexed by
1363
+	 *                                      the columns will be returned.
1364
+	 * @return EE_Base_Class|null|array()
1365
+	 * @throws EE_Error
1366
+	 */
1367
+	public function previous(
1368
+		$current_field_value,
1369
+		$field_to_order_by = null,
1370
+		$query_params = array(),
1371
+		$columns_to_select = null
1372
+	) {
1373
+		$results = $this->_get_consecutive(
1374
+			$current_field_value,
1375
+			'<',
1376
+			$field_to_order_by,
1377
+			1,
1378
+			$query_params,
1379
+			$columns_to_select
1380
+		);
1381
+		return empty($results) ? null : reset($results);
1382
+	}
1383
+
1384
+
1385
+
1386
+	/**
1387
+	 * Returns the a consecutive number of items in sequence from the given
1388
+	 * value as found in the database matching the given query conditions.
1389
+	 *
1390
+	 * @param mixed  $current_field_value   Value used for the reference point.
1391
+	 * @param string $operand               What operand is used for the sequence.
1392
+	 * @param string $field_to_order_by     What field is used for the reference point.
1393
+	 * @param int    $limit                 How many to return.
1394
+	 * @param array  $query_params          Extra conditions on the query.
1395
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1396
+	 *                                      otherwise you can indicate just the columns you want returned.
1397
+	 * @return EE_Base_Class[]|array
1398
+	 * @throws EE_Error
1399
+	 */
1400
+	protected function _get_consecutive(
1401
+		$current_field_value,
1402
+		$operand = '>',
1403
+		$field_to_order_by = null,
1404
+		$limit = 1,
1405
+		$query_params = array(),
1406
+		$columns_to_select = null
1407
+	) {
1408
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1409
+		if (empty($field_to_order_by)) {
1410
+			if ($this->has_primary_key_field()) {
1411
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1412
+			} else {
1413
+				if (WP_DEBUG) {
1414
+					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).',
1415
+						'event_espresso'));
1416
+				}
1417
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1418
+				return array();
1419
+			}
1420
+		}
1421
+		if (! is_array($query_params)) {
1422
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1423
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1424
+					gettype($query_params)), '4.6.0');
1425
+			$query_params = array();
1426
+		}
1427
+		//let's add the where query param for consecutive look up.
1428
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1429
+		$query_params['limit'] = $limit;
1430
+		//set direction
1431
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1432
+		$query_params['order_by'] = $operand === '>'
1433
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1434
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1435
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1436
+		if (empty($columns_to_select)) {
1437
+			return $this->get_all($query_params);
1438
+		}
1439
+		//getting just the fields
1440
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1441
+	}
1442
+
1443
+
1444
+
1445
+	/**
1446
+	 * This sets the _timezone property after model object has been instantiated.
1447
+	 *
1448
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1449
+	 */
1450
+	public function set_timezone($timezone)
1451
+	{
1452
+		if ($timezone !== null) {
1453
+			$this->_timezone = $timezone;
1454
+		}
1455
+		//note we need to loop through relations and set the timezone on those objects as well.
1456
+		foreach ($this->_model_relations as $relation) {
1457
+			$relation->set_timezone($timezone);
1458
+		}
1459
+		//and finally we do the same for any datetime fields
1460
+		foreach ($this->_fields as $field) {
1461
+			if ($field instanceof EE_Datetime_Field) {
1462
+				$field->set_timezone($timezone);
1463
+			}
1464
+		}
1465
+	}
1466
+
1467
+
1468
+
1469
+	/**
1470
+	 * This just returns whatever is set for the current timezone.
1471
+	 *
1472
+	 * @access public
1473
+	 * @return string
1474
+	 */
1475
+	public function get_timezone()
1476
+	{
1477
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1478
+		if (empty($this->_timezone)) {
1479
+			foreach ($this->_fields as $field) {
1480
+				if ($field instanceof EE_Datetime_Field) {
1481
+					$this->set_timezone($field->get_timezone());
1482
+					break;
1483
+				}
1484
+			}
1485
+		}
1486
+		//if timezone STILL empty then return the default timezone for the site.
1487
+		if (empty($this->_timezone)) {
1488
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1489
+		}
1490
+		return $this->_timezone;
1491
+	}
1492
+
1493
+
1494
+
1495
+	/**
1496
+	 * This returns the date formats set for the given field name and also ensures that
1497
+	 * $this->_timezone property is set correctly.
1498
+	 *
1499
+	 * @since 4.6.x
1500
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1501
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1502
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1503
+	 * @return array formats in an array with the date format first, and the time format last.
1504
+	 */
1505
+	public function get_formats_for($field_name, $pretty = false)
1506
+	{
1507
+		$field_settings = $this->field_settings_for($field_name);
1508
+		//if not a valid EE_Datetime_Field then throw error
1509
+		if (! $field_settings instanceof EE_Datetime_Field) {
1510
+			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.',
1511
+				'event_espresso'), $field_name));
1512
+		}
1513
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1514
+		//the field.
1515
+		$this->_timezone = $field_settings->get_timezone();
1516
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * This returns the current time in a format setup for a query on this model.
1523
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
+	 * it will return:
1525
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1526
+	 *  NOW
1527
+	 *  - or a unix timestamp (equivalent to time())
1528
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
+	 * @since 4.6.x
1532
+	 * @param string $field_name       The field the current time is needed for.
1533
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1534
+	 *                                 formatted string matching the set format for the field in the set timezone will
1535
+	 *                                 be returned.
1536
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1537
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1538
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1539
+	 *                                 exception is triggered.
1540
+	 */
1541
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1542
+	{
1543
+		$formats = $this->get_formats_for($field_name);
1544
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1545
+		if ($timestamp) {
1546
+			return $DateTime->format('U');
1547
+		}
1548
+		//not returning timestamp, so return formatted string in timezone.
1549
+		switch ($what) {
1550
+			case 'time' :
1551
+				return $DateTime->format($formats[1]);
1552
+				break;
1553
+			case 'date' :
1554
+				return $DateTime->format($formats[0]);
1555
+				break;
1556
+			default :
1557
+				return $DateTime->format(implode(' ', $formats));
1558
+				break;
1559
+		}
1560
+	}
1561
+
1562
+
1563
+
1564
+	/**
1565
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1566
+	 * for the model are.  Returns a DateTime object.
1567
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1568
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1569
+	 * ignored.
1570
+	 *
1571
+	 * @param string $field_name      The field being setup.
1572
+	 * @param string $timestring      The date time string being used.
1573
+	 * @param string $incoming_format The format for the time string.
1574
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1575
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1576
+	 *                                format is
1577
+	 *                                'U', this is ignored.
1578
+	 * @return DateTime
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1582
+	{
1583
+		//just using this to ensure the timezone is set correctly internally
1584
+		$this->get_formats_for($field_name);
1585
+		//load EEH_DTT_Helper
1586
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1587
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1588
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1589
+	}
1590
+
1591
+
1592
+
1593
+	/**
1594
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1595
+	 *
1596
+	 * @return EE_Table_Base[]
1597
+	 */
1598
+	public function get_tables()
1599
+	{
1600
+		return $this->_tables;
1601
+	}
1602
+
1603
+
1604
+
1605
+	/**
1606
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1607
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1608
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1609
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1610
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1611
+	 * model object with EVT_ID = 1
1612
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1613
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1614
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1615
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1616
+	 * are not specified)
1617
+	 *
1618
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1619
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1620
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1621
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1622
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1623
+	 *                                         ID=34, we'd use this method as follows:
1624
+	 *                                         EEM_Transaction::instance()->update(
1625
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1626
+	 *                                         array(array('TXN_ID'=>34)));
1627
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1628
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1629
+	 *                                         consider updating Question's QST_admin_label field is of type
1630
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1631
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1632
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1633
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1634
+	 *                                         TRUE, it is assumed that you've already called
1635
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1636
+	 *                                         malicious javascript. However, if
1637
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1638
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1639
+	 *                                         and every other field, before insertion. We provide this parameter
1640
+	 *                                         because model objects perform their prepare_for_set function on all
1641
+	 *                                         their values, and so don't need to be called again (and in many cases,
1642
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1643
+	 *                                         prepare_for_set method...)
1644
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1645
+	 *                                         in this model's entity map according to $fields_n_values that match
1646
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1647
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1648
+	 *                                         could get out-of-sync with the database
1649
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1650
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1651
+	 *                                         bad)
1652
+	 * @throws EE_Error
1653
+	 */
1654
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1655
+	{
1656
+		if (! is_array($query_params)) {
1657
+			EE_Error::doing_it_wrong('EEM_Base::update',
1658
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1659
+					gettype($query_params)), '4.6.0');
1660
+			$query_params = array();
1661
+		}
1662
+		/**
1663
+		 * Action called before a model update call has been made.
1664
+		 *
1665
+		 * @param EEM_Base $model
1666
+		 * @param array    $fields_n_values the updated fields and their new values
1667
+		 * @param array    $query_params    @see EEM_Base::get_all()
1668
+		 */
1669
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1670
+		/**
1671
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1672
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1673
+		 *
1674
+		 * @param array    $fields_n_values fields and their new values
1675
+		 * @param EEM_Base $model           the model being queried
1676
+		 * @param array    $query_params    see EEM_Base::get_all()
1677
+		 */
1678
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1679
+			$query_params);
1680
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1681
+		//to do that, for each table, verify that it's PK isn't null.
1682
+		$tables = $this->get_tables();
1683
+		//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
1684
+		//NOTE: we should make this code more efficient by NOT querying twice
1685
+		//before the real update, but that needs to first go through ALPHA testing
1686
+		//as it's dangerous. says Mike August 8 2014
1687
+		//we want to make sure the default_where strategy is ignored
1688
+		$this->_ignore_where_strategy = true;
1689
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1690
+		foreach ($wpdb_select_results as $wpdb_result) {
1691
+			// type cast stdClass as array
1692
+			$wpdb_result = (array)$wpdb_result;
1693
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1694
+			if ($this->has_primary_key_field()) {
1695
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1696
+			} else {
1697
+				//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)
1698
+				$main_table_pk_value = null;
1699
+			}
1700
+			//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
1701
+			//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
1702
+			if (count($tables) > 1) {
1703
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1704
+				//in that table, and so we'll want to insert one
1705
+				foreach ($tables as $table_obj) {
1706
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1707
+					//if there is no private key for this table on the results, it means there's no entry
1708
+					//in this table, right? so insert a row in the current table, using any fields available
1709
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1710
+						   && $wpdb_result[$this_table_pk_column])
1711
+					) {
1712
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1713
+							$main_table_pk_value);
1714
+						//if we died here, report the error
1715
+						if (! $success) {
1716
+							return false;
1717
+						}
1718
+					}
1719
+				}
1720
+			}
1721
+			//				//and now check that if we have cached any models by that ID on the model, that
1722
+			//				//they also get updated properly
1723
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1724
+			//				if( $model_object ){
1725
+			//					foreach( $fields_n_values as $field => $value ){
1726
+			//						$model_object->set($field, $value);
1727
+			//let's make sure default_where strategy is followed now
1728
+			$this->_ignore_where_strategy = false;
1729
+		}
1730
+		//if we want to keep model objects in sync, AND
1731
+		//if this wasn't called from a model object (to update itself)
1732
+		//then we want to make sure we keep all the existing
1733
+		//model objects in sync with the db
1734
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1735
+			if ($this->has_primary_key_field()) {
1736
+				$model_objs_affected_ids = $this->get_col($query_params);
1737
+			} else {
1738
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1739
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1740
+				$model_objs_affected_ids = array();
1741
+				foreach ($models_affected_key_columns as $row) {
1742
+					$combined_index_key = $this->get_index_primary_key_string($row);
1743
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1744
+				}
1745
+			}
1746
+			if (! $model_objs_affected_ids) {
1747
+				//wait wait wait- if nothing was affected let's stop here
1748
+				return 0;
1749
+			}
1750
+			foreach ($model_objs_affected_ids as $id) {
1751
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1752
+				if ($model_obj_in_entity_map) {
1753
+					foreach ($fields_n_values as $field => $new_value) {
1754
+						$model_obj_in_entity_map->set($field, $new_value);
1755
+					}
1756
+				}
1757
+			}
1758
+			//if there is a primary key on this model, we can now do a slight optimization
1759
+			if ($this->has_primary_key_field()) {
1760
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1761
+				$query_params = array(
1762
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1763
+					'limit'                    => count($model_objs_affected_ids),
1764
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1765
+				);
1766
+			}
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$SQL = "UPDATE "
1770
+			   . $model_query_info->get_full_join_sql()
1771
+			   . " SET "
1772
+			   . $this->_construct_update_sql($fields_n_values)
1773
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1774
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1775
+		/**
1776
+		 * Action called after a model update call has been made.
1777
+		 *
1778
+		 * @param EEM_Base $model
1779
+		 * @param array    $fields_n_values the updated fields and their new values
1780
+		 * @param array    $query_params    @see EEM_Base::get_all()
1781
+		 * @param int      $rows_affected
1782
+		 */
1783
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1784
+		return $rows_affected;//how many supposedly got updated
1785
+	}
1786
+
1787
+
1788
+
1789
+	/**
1790
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1791
+	 * are teh values of the field specified (or by default the primary key field)
1792
+	 * that matched the query params. Note that you should pass the name of the
1793
+	 * model FIELD, not the database table's column name.
1794
+	 *
1795
+	 * @param array  $query_params @see EEM_Base::get_all()
1796
+	 * @param string $field_to_select
1797
+	 * @return array just like $wpdb->get_col()
1798
+	 * @throws EE_Error
1799
+	 */
1800
+	public function get_col($query_params = array(), $field_to_select = null)
1801
+	{
1802
+		if ($field_to_select) {
1803
+			$field = $this->field_settings_for($field_to_select);
1804
+		} elseif ($this->has_primary_key_field()) {
1805
+			$field = $this->get_primary_key_field();
1806
+		} else {
1807
+			//no primary key, just grab the first column
1808
+			$field = reset($this->field_settings());
1809
+		}
1810
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1811
+		$select_expressions = $field->get_qualified_column();
1812
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1813
+		return $this->_do_wpdb_query('get_col', array($SQL));
1814
+	}
1815
+
1816
+
1817
+
1818
+	/**
1819
+	 * Returns a single column value for a single row from the database
1820
+	 *
1821
+	 * @param array  $query_params    @see EEM_Base::get_all()
1822
+	 * @param string $field_to_select @see EEM_Base::get_col()
1823
+	 * @return string
1824
+	 * @throws EE_Error
1825
+	 */
1826
+	public function get_var($query_params = array(), $field_to_select = null)
1827
+	{
1828
+		$query_params['limit'] = 1;
1829
+		$col = $this->get_col($query_params, $field_to_select);
1830
+		if (! empty($col)) {
1831
+			return reset($col);
1832
+		}
1833
+		return null;
1834
+	}
1835
+
1836
+
1837
+
1838
+	/**
1839
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1840
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1841
+	 * injection, but currently no further filtering is done
1842
+	 *
1843
+	 * @global      $wpdb
1844
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1845
+	 *                               be updated to in the DB
1846
+	 * @return string of SQL
1847
+	 * @throws EE_Error
1848
+	 */
1849
+	public function _construct_update_sql($fields_n_values)
1850
+	{
1851
+		/** @type WPDB $wpdb */
1852
+		global $wpdb;
1853
+		$cols_n_values = array();
1854
+		foreach ($fields_n_values as $field_name => $value) {
1855
+			$field_obj = $this->field_settings_for($field_name);
1856
+			//if the value is NULL, we want to assign the value to that.
1857
+			//wpdb->prepare doesn't really handle that properly
1858
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1859
+			$value_sql = $prepared_value === null ? 'NULL'
1860
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1861
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1862
+		}
1863
+		return implode(",", $cols_n_values);
1864
+	}
1865
+
1866
+
1867
+
1868
+	/**
1869
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1870
+	 * Performs a HARD delete, meaning the database row should always be removed,
1871
+	 * not just have a flag field on it switched
1872
+	 * Wrapper for EEM_Base::delete_permanently()
1873
+	 *
1874
+	 * @param mixed $id
1875
+	 * @param boolean $allow_blocking
1876
+	 * @return int the number of rows deleted
1877
+	 * @throws EE_Error
1878
+	 */
1879
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1880
+	{
1881
+		return $this->delete_permanently(
1882
+			array(
1883
+				array($this->get_primary_key_field()->get_name() => $id),
1884
+				'limit' => 1,
1885
+			),
1886
+			$allow_blocking
1887
+		);
1888
+	}
1889
+
1890
+
1891
+
1892
+	/**
1893
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1894
+	 * Wrapper for EEM_Base::delete()
1895
+	 *
1896
+	 * @param mixed $id
1897
+	 * @param boolean $allow_blocking
1898
+	 * @return int the number of rows deleted
1899
+	 * @throws EE_Error
1900
+	 */
1901
+	public function delete_by_ID($id, $allow_blocking = true)
1902
+	{
1903
+		return $this->delete(
1904
+			array(
1905
+				array($this->get_primary_key_field()->get_name() => $id),
1906
+				'limit' => 1,
1907
+			),
1908
+			$allow_blocking
1909
+		);
1910
+	}
1911
+
1912
+
1913
+
1914
+	/**
1915
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1916
+	 * meaning if the model has a field that indicates its been "trashed" or
1917
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1918
+	 *
1919
+	 * @see EEM_Base::delete_permanently
1920
+	 * @param array   $query_params
1921
+	 * @param boolean $allow_blocking
1922
+	 * @return int how many rows got deleted
1923
+	 * @throws EE_Error
1924
+	 */
1925
+	public function delete($query_params, $allow_blocking = true)
1926
+	{
1927
+		return $this->delete_permanently($query_params, $allow_blocking);
1928
+	}
1929
+
1930
+
1931
+
1932
+	/**
1933
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1934
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1935
+	 * as archived, not actually deleted
1936
+	 *
1937
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1938
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1939
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1940
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1941
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1942
+	 *                                DB
1943
+	 * @return int how many rows got deleted
1944
+	 * @throws EE_Error
1945
+	 */
1946
+	public function delete_permanently($query_params, $allow_blocking = true)
1947
+	{
1948
+		/**
1949
+		 * Action called just before performing a real deletion query. You can use the
1950
+		 * model and its $query_params to find exactly which items will be deleted
1951
+		 *
1952
+		 * @param EEM_Base $model
1953
+		 * @param array    $query_params   @see EEM_Base::get_all()
1954
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1955
+		 *                                 to block (prevent) this deletion
1956
+		 */
1957
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1958
+		//some MySQL databases may be running safe mode, which may restrict
1959
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1960
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1961
+		//to delete them
1962
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1963
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1964
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1965
+			$columns_and_ids_for_deleting
1966
+		);
1967
+		/**
1968
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1969
+		 *
1970
+		 * @param EEM_Base $this  The model instance being acted on.
1971
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1972
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1973
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1974
+		 *                                                  derived from the incoming query parameters.
1975
+		 *                                                  @see details on the structure of this array in the phpdocs
1976
+		 *                                                  for the `_get_ids_for_delete_method`
1977
+		 *
1978
+		 */
1979
+		do_action('AHEE__EEM_Base__delete__before_query',
1980
+			$this,
1981
+			$query_params,
1982
+			$allow_blocking,
1983
+			$columns_and_ids_for_deleting
1984
+		);
1985
+		if ($deletion_where_query_part) {
1986
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1987
+			$table_aliases = array_keys($this->_tables);
1988
+			$SQL = "DELETE "
1989
+				   . implode(", ", $table_aliases)
1990
+				   . " FROM "
1991
+				   . $model_query_info->get_full_join_sql()
1992
+				   . " WHERE "
1993
+				   . $deletion_where_query_part;
1994
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1995
+		} else {
1996
+			$rows_deleted = 0;
1997
+		}
1998
+
1999
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2000
+		//there was no error with the delete query.
2001
+		if ($this->has_primary_key_field()
2002
+			&& $rows_deleted !== false
2003
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2004
+		) {
2005
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2006
+			foreach ($ids_for_removal as $id) {
2007
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2008
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2009
+				}
2010
+			}
2011
+
2012
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2013
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2014
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2015
+			// (although it is possible).
2016
+			//Note this can be skipped by using the provided filter and returning false.
2017
+			if (apply_filters(
2018
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2019
+				! $this instanceof EEM_Extra_Meta,
2020
+				$this
2021
+			)) {
2022
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2023
+					0 => array(
2024
+						'EXM_type' => $this->get_this_model_name(),
2025
+						'OBJ_ID'   => array(
2026
+							'IN',
2027
+							$ids_for_removal
2028
+						)
2029
+					)
2030
+				));
2031
+			}
2032
+		}
2033
+
2034
+		/**
2035
+		 * Action called just after performing a real deletion query. Although at this point the
2036
+		 * items should have been deleted
2037
+		 *
2038
+		 * @param EEM_Base $model
2039
+		 * @param array    $query_params @see EEM_Base::get_all()
2040
+		 * @param int      $rows_deleted
2041
+		 */
2042
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2043
+		return $rows_deleted;//how many supposedly got deleted
2044
+	}
2045
+
2046
+
2047
+
2048
+	/**
2049
+	 * Checks all the relations that throw error messages when there are blocking related objects
2050
+	 * for related model objects. If there are any related model objects on those relations,
2051
+	 * adds an EE_Error, and return true
2052
+	 *
2053
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2054
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2055
+	 *                                                 should be ignored when determining whether there are related
2056
+	 *                                                 model objects which block this model object's deletion. Useful
2057
+	 *                                                 if you know A is related to B and are considering deleting A,
2058
+	 *                                                 but want to see if A has any other objects blocking its deletion
2059
+	 *                                                 before removing the relation between A and B
2060
+	 * @return boolean
2061
+	 * @throws EE_Error
2062
+	 */
2063
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2064
+	{
2065
+		//first, if $ignore_this_model_obj was supplied, get its model
2066
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2067
+			$ignored_model = $ignore_this_model_obj->get_model();
2068
+		} else {
2069
+			$ignored_model = null;
2070
+		}
2071
+		//now check all the relations of $this_model_obj_or_id and see if there
2072
+		//are any related model objects blocking it?
2073
+		$is_blocked = false;
2074
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2075
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2076
+				//if $ignore_this_model_obj was supplied, then for the query
2077
+				//on that model needs to be told to ignore $ignore_this_model_obj
2078
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2079
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2080
+						array(
2081
+							$ignored_model->get_primary_key_field()->get_name() => array(
2082
+								'!=',
2083
+								$ignore_this_model_obj->ID(),
2084
+							),
2085
+						),
2086
+					));
2087
+				} else {
2088
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2089
+				}
2090
+				if ($related_model_objects) {
2091
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2092
+					$is_blocked = true;
2093
+				}
2094
+			}
2095
+		}
2096
+		return $is_blocked;
2097
+	}
2098
+
2099
+
2100
+	/**
2101
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2102
+	 * @param array $row_results_for_deleting
2103
+	 * @param bool  $allow_blocking
2104
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2105
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2106
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2107
+	 *                 deleted. Example:
2108
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2109
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2110
+	 *                 where each element is a group of columns and values that get deleted. Example:
2111
+	 *                      array(
2112
+	 *                          0 => array(
2113
+	 *                              'Term_Relationship.object_id' => 1
2114
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2115
+	 *                          ),
2116
+	 *                          1 => array(
2117
+	 *                              'Term_Relationship.object_id' => 1
2118
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2119
+	 *                          )
2120
+	 *                      )
2121
+	 * @throws EE_Error
2122
+	 */
2123
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2124
+	{
2125
+		$ids_to_delete_indexed_by_column = array();
2126
+		if ($this->has_primary_key_field()) {
2127
+			$primary_table = $this->_get_main_table();
2128
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2129
+			$other_tables = $this->_get_other_tables();
2130
+			$ids_to_delete_indexed_by_column = $query = array();
2131
+			foreach ($row_results_for_deleting as $item_to_delete) {
2132
+				//before we mark this item for deletion,
2133
+				//make sure there's no related entities blocking its deletion (if we're checking)
2134
+				if (
2135
+					$allow_blocking
2136
+					&& $this->delete_is_blocked_by_related_models(
2137
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2138
+					)
2139
+				) {
2140
+					continue;
2141
+				}
2142
+				//primary table deletes
2143
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2144
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2145
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2146
+				}
2147
+			}
2148
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2149
+			$fields = $this->get_combined_primary_key_fields();
2150
+			foreach ($row_results_for_deleting as $item_to_delete) {
2151
+				$ids_to_delete_indexed_by_column_for_row = array();
2152
+				foreach ($fields as $cpk_field) {
2153
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2154
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2155
+							$item_to_delete[$cpk_field->get_qualified_column()];
2156
+					}
2157
+				}
2158
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2159
+			}
2160
+		} else {
2161
+			//so there's no primary key and no combined key...
2162
+			//sorry, can't help you
2163
+			throw new EE_Error(
2164
+				sprintf(
2165
+					__(
2166
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2167
+						"event_espresso"
2168
+					), get_class($this)
2169
+				)
2170
+			);
2171
+		}    
2172
+		return $ids_to_delete_indexed_by_column;
2173
+	}
2174
+
2175
+
2176
+	/**
2177
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2178
+	 * the corresponding query_part for the query performing the delete.
2179
+	 *
2180
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2181
+	 * @return string
2182
+	 * @throws EE_Error
2183
+	 */
2184
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2185
+		$query_part = '';
2186
+		if (empty($ids_to_delete_indexed_by_column)) {
2187
+			return $query_part;
2188
+		} elseif ($this->has_primary_key_field()) {
2189
+			$query = array();
2190
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2191
+				//make sure we have unique $ids
2192
+				$ids = array_unique($ids);
2193
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2194
+			}
2195
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2196
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2197
+			$ways_to_identify_a_row = array();
2198
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2199
+				$values_for_each_combined_primary_key_for_a_row = array();
2200
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2201
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2202
+				}
2203
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2204
+			}
2205
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2206
+		}
2207
+		return $query_part;
2208
+	}
2209 2209
     
2210 2210
 
2211 2211
 
2212
-    /**
2213
-     * Gets the model field by the fully qualified name
2214
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2215
-     * @return EE_Model_Field_Base
2216
-     */
2217
-    public function get_field_by_column($qualified_column_name)
2218
-    {
2219
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2220
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2221
-               return $field_obj;
2222
-           }
2223
-       }
2224
-        throw new EE_Error(
2225
-            sprintf(
2226
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2227
-                $this->get_this_model_name(),
2228
-                $qualified_column_name
2229
-            )
2230
-        );
2231
-    }
2232
-
2233
-
2234
-
2235
-    /**
2236
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2237
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2238
-     * column
2239
-     *
2240
-     * @param array  $query_params   like EEM_Base::get_all's
2241
-     * @param string $field_to_count field on model to count by (not column name)
2242
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2243
-     *                               that by the setting $distinct to TRUE;
2244
-     * @return int
2245
-     * @throws EE_Error
2246
-     */
2247
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2248
-    {
2249
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2250
-        if ($field_to_count) {
2251
-            $field_obj = $this->field_settings_for($field_to_count);
2252
-            $column_to_count = $field_obj->get_qualified_column();
2253
-        } elseif ($this->has_primary_key_field()) {
2254
-            $pk_field_obj = $this->get_primary_key_field();
2255
-            $column_to_count = $pk_field_obj->get_qualified_column();
2256
-        } else {
2257
-            //there's no primary key
2258
-            //if we're counting distinct items, and there's no primary key,
2259
-            //we need to list out the columns for distinction;
2260
-            //otherwise we can just use star
2261
-            if ($distinct) {
2262
-                $columns_to_use = array();
2263
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2264
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2265
-                }
2266
-                $column_to_count = implode(',', $columns_to_use);
2267
-            } else {
2268
-                $column_to_count = '*';
2269
-            }
2270
-        }
2271
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2272
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2273
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2274
-    }
2275
-
2276
-
2277
-
2278
-    /**
2279
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2280
-     *
2281
-     * @param array  $query_params like EEM_Base::get_all
2282
-     * @param string $field_to_sum name of field (array key in $_fields array)
2283
-     * @return float
2284
-     * @throws EE_Error
2285
-     */
2286
-    public function sum($query_params, $field_to_sum = null)
2287
-    {
2288
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2289
-        if ($field_to_sum) {
2290
-            $field_obj = $this->field_settings_for($field_to_sum);
2291
-        } else {
2292
-            $field_obj = $this->get_primary_key_field();
2293
-        }
2294
-        $column_to_count = $field_obj->get_qualified_column();
2295
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2297
-        $data_type = $field_obj->get_wpdb_data_type();
2298
-        if ($data_type === '%d' || $data_type === '%s') {
2299
-            return (float)$return_value;
2300
-        }
2301
-        //must be %f
2302
-        return (float)$return_value;
2303
-    }
2304
-
2305
-
2306
-
2307
-    /**
2308
-     * Just calls the specified method on $wpdb with the given arguments
2309
-     * Consolidates a little extra error handling code
2310
-     *
2311
-     * @param string $wpdb_method
2312
-     * @param array  $arguments_to_provide
2313
-     * @throws EE_Error
2314
-     * @global wpdb  $wpdb
2315
-     * @return mixed
2316
-     */
2317
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2318
-    {
2319
-        //if we're in maintenance mode level 2, DON'T run any queries
2320
-        //because level 2 indicates the database needs updating and
2321
-        //is probably out of sync with the code
2322
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2323
-            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.",
2324
-                "event_espresso")));
2325
-        }
2326
-        /** @type WPDB $wpdb */
2327
-        global $wpdb;
2328
-        if (! method_exists($wpdb, $wpdb_method)) {
2329
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2330
-                'event_espresso'), $wpdb_method));
2331
-        }
2332
-        if (WP_DEBUG) {
2333
-            $old_show_errors_value = $wpdb->show_errors;
2334
-            $wpdb->show_errors(false);
2335
-        }
2336
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2337
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2338
-        if (WP_DEBUG) {
2339
-            $wpdb->show_errors($old_show_errors_value);
2340
-            if (! empty($wpdb->last_error)) {
2341
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2342
-            }
2343
-            if ($result === false) {
2344
-                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"',
2345
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2346
-            }
2347
-        } elseif ($result === false) {
2348
-            EE_Error::add_error(
2349
-                sprintf(
2350
-                    __('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"',
2351
-                        'event_espresso'),
2352
-                    $wpdb_method,
2353
-                    var_export($arguments_to_provide, true),
2354
-                    $wpdb->last_error
2355
-                ),
2356
-                __FILE__,
2357
-                __FUNCTION__,
2358
-                __LINE__
2359
-            );
2360
-        }
2361
-        return $result;
2362
-    }
2363
-
2364
-
2365
-
2366
-    /**
2367
-     * Attempts to run the indicated WPDB method with the provided arguments,
2368
-     * and if there's an error tries to verify the DB is correct. Uses
2369
-     * the static property EEM_Base::$_db_verification_level to determine whether
2370
-     * we should try to fix the EE core db, the addons, or just give up
2371
-     *
2372
-     * @param string $wpdb_method
2373
-     * @param array  $arguments_to_provide
2374
-     * @return mixed
2375
-     */
2376
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2377
-    {
2378
-        /** @type WPDB $wpdb */
2379
-        global $wpdb;
2380
-        $wpdb->last_error = null;
2381
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2382
-        // was there an error running the query? but we don't care on new activations
2383
-        // (we're going to setup the DB anyway on new activations)
2384
-        if (($result === false || ! empty($wpdb->last_error))
2385
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2386
-        ) {
2387
-            switch (EEM_Base::$_db_verification_level) {
2388
-                case EEM_Base::db_verified_none :
2389
-                    // let's double-check core's DB
2390
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2391
-                    break;
2392
-                case EEM_Base::db_verified_core :
2393
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2394
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2395
-                    break;
2396
-                case EEM_Base::db_verified_addons :
2397
-                    // ummmm... you in trouble
2398
-                    return $result;
2399
-                    break;
2400
-            }
2401
-            if (! empty($error_message)) {
2402
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2403
-                trigger_error($error_message);
2404
-            }
2405
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2406
-        }
2407
-        return $result;
2408
-    }
2409
-
2410
-
2411
-
2412
-    /**
2413
-     * Verifies the EE core database is up-to-date and records that we've done it on
2414
-     * EEM_Base::$_db_verification_level
2415
-     *
2416
-     * @param string $wpdb_method
2417
-     * @param array  $arguments_to_provide
2418
-     * @return string
2419
-     */
2420
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2421
-    {
2422
-        /** @type WPDB $wpdb */
2423
-        global $wpdb;
2424
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2425
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2426
-        $error_message = sprintf(
2427
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
-                'event_espresso'),
2429
-            $wpdb->last_error,
2430
-            $wpdb_method,
2431
-            wp_json_encode($arguments_to_provide)
2432
-        );
2433
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2434
-        return $error_message;
2435
-    }
2436
-
2437
-
2438
-
2439
-    /**
2440
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2441
-     * EEM_Base::$_db_verification_level
2442
-     *
2443
-     * @param $wpdb_method
2444
-     * @param $arguments_to_provide
2445
-     * @return string
2446
-     */
2447
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2448
-    {
2449
-        /** @type WPDB $wpdb */
2450
-        global $wpdb;
2451
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2452
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2453
-        $error_message = sprintf(
2454
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
-                'event_espresso'),
2456
-            $wpdb->last_error,
2457
-            $wpdb_method,
2458
-            wp_json_encode($arguments_to_provide)
2459
-        );
2460
-        EE_System::instance()->initialize_addons();
2461
-        return $error_message;
2462
-    }
2463
-
2464
-
2465
-
2466
-    /**
2467
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2468
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2469
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2470
-     * ..."
2471
-     *
2472
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2473
-     * @return string
2474
-     */
2475
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476
-    {
2477
-        return " FROM " . $model_query_info->get_full_join_sql() .
2478
-               $model_query_info->get_where_sql() .
2479
-               $model_query_info->get_group_by_sql() .
2480
-               $model_query_info->get_having_sql() .
2481
-               $model_query_info->get_order_by_sql() .
2482
-               $model_query_info->get_limit_sql();
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * Set to easily debug the next X queries ran from this model.
2489
-     *
2490
-     * @param int $count
2491
-     */
2492
-    public function show_next_x_db_queries($count = 1)
2493
-    {
2494
-        $this->_show_next_x_db_queries = $count;
2495
-    }
2496
-
2497
-
2498
-
2499
-    /**
2500
-     * @param $sql_query
2501
-     */
2502
-    public function show_db_query_if_previously_requested($sql_query)
2503
-    {
2504
-        if ($this->_show_next_x_db_queries > 0) {
2505
-            echo $sql_query;
2506
-            $this->_show_next_x_db_queries--;
2507
-        }
2508
-    }
2509
-
2510
-
2511
-
2512
-    /**
2513
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2514
-     * There are the 3 cases:
2515
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2516
-     * $otherModelObject has no ID, it is first saved.
2517
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2518
-     * has no ID, it is first saved.
2519
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2520
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2521
-     * join table
2522
-     *
2523
-     * @param        EE_Base_Class                     /int $thisModelObject
2524
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2525
-     * @param string $relationName                     , key in EEM_Base::_relations
2526
-     *                                                 an attendee to a group, you also want to specify which role they
2527
-     *                                                 will have in that group. So you would use this parameter to
2528
-     *                                                 specify array('role-column-name'=>'role-id')
2529
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2530
-     *                                                 to for relation to methods that allow you to further specify
2531
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2532
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2533
-     *                                                 because these will be inserted in any new rows created as well.
2534
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2535
-     * @throws EE_Error
2536
-     */
2537
-    public function add_relationship_to(
2538
-        $id_or_obj,
2539
-        $other_model_id_or_obj,
2540
-        $relationName,
2541
-        $extra_join_model_fields_n_values = array()
2542
-    ) {
2543
-        $relation_obj = $this->related_settings_for($relationName);
2544
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2551
-     * There are the 3 cases:
2552
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2553
-     * error
2554
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2555
-     * an error
2556
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2557
-     *
2558
-     * @param        EE_Base_Class /int $id_or_obj
2559
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2560
-     * @param string $relationName key in EEM_Base::_relations
2561
-     * @return boolean of success
2562
-     * @throws EE_Error
2563
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2564
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566
-     *                             because these will be inserted in any new rows created as well.
2567
-     */
2568
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569
-    {
2570
-        $relation_obj = $this->related_settings_for($relationName);
2571
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2572
-    }
2573
-
2574
-
2575
-
2576
-    /**
2577
-     * @param mixed           $id_or_obj
2578
-     * @param string          $relationName
2579
-     * @param array           $where_query_params
2580
-     * @param EE_Base_Class[] objects to which relations were removed
2581
-     * @return \EE_Base_Class[]
2582
-     * @throws EE_Error
2583
-     */
2584
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2585
-    {
2586
-        $relation_obj = $this->related_settings_for($relationName);
2587
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2588
-    }
2589
-
2590
-
2591
-
2592
-    /**
2593
-     * Gets all the related items of the specified $model_name, using $query_params.
2594
-     * Note: by default, we remove the "default query params"
2595
-     * because we want to get even deleted items etc.
2596
-     *
2597
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2598
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2599
-     * @param array  $query_params like EEM_Base::get_all
2600
-     * @return EE_Base_Class[]
2601
-     * @throws EE_Error
2602
-     */
2603
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2604
-    {
2605
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2606
-        $relation_settings = $this->related_settings_for($model_name);
2607
-        return $relation_settings->get_all_related($model_obj, $query_params);
2608
-    }
2609
-
2610
-
2611
-
2612
-    /**
2613
-     * Deletes all the model objects across the relation indicated by $model_name
2614
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2615
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2616
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617
-     *
2618
-     * @param EE_Base_Class|int|string $id_or_obj
2619
-     * @param string                   $model_name
2620
-     * @param array                    $query_params
2621
-     * @return int how many deleted
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2625
-    {
2626
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2627
-        $relation_settings = $this->related_settings_for($model_name);
2628
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2629
-    }
2630
-
2631
-
2632
-
2633
-    /**
2634
-     * Hard deletes all the model objects across the relation indicated by $model_name
2635
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2636
-     * the model objects can't be hard deleted because of blocking related model objects,
2637
-     * just does a soft-delete on them instead.
2638
-     *
2639
-     * @param EE_Base_Class|int|string $id_or_obj
2640
-     * @param string                   $model_name
2641
-     * @param array                    $query_params
2642
-     * @return int how many deleted
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2646
-    {
2647
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2648
-        $relation_settings = $this->related_settings_for($model_name);
2649
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2650
-    }
2651
-
2652
-
2653
-
2654
-    /**
2655
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2656
-     * unless otherwise specified in the $query_params
2657
-     *
2658
-     * @param        int             /EE_Base_Class $id_or_obj
2659
-     * @param string $model_name     like 'Event', or 'Registration'
2660
-     * @param array  $query_params   like EEM_Base::get_all's
2661
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2662
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2663
-     *                               that by the setting $distinct to TRUE;
2664
-     * @return int
2665
-     * @throws EE_Error
2666
-     */
2667
-    public function count_related(
2668
-        $id_or_obj,
2669
-        $model_name,
2670
-        $query_params = array(),
2671
-        $field_to_count = null,
2672
-        $distinct = false
2673
-    ) {
2674
-        $related_model = $this->get_related_model_obj($model_name);
2675
-        //we're just going to use the query params on the related model's normal get_all query,
2676
-        //except add a condition to say to match the current mod
2677
-        if (! isset($query_params['default_where_conditions'])) {
2678
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679
-        }
2680
-        $this_model_name = $this->get_this_model_name();
2681
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2683
-        return $related_model->count($query_params, $field_to_count, $distinct);
2684
-    }
2685
-
2686
-
2687
-
2688
-    /**
2689
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2690
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2691
-     *
2692
-     * @param        int           /EE_Base_Class $id_or_obj
2693
-     * @param string $model_name   like 'Event', or 'Registration'
2694
-     * @param array  $query_params like EEM_Base::get_all's
2695
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2696
-     * @return float
2697
-     * @throws EE_Error
2698
-     */
2699
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700
-    {
2701
-        $related_model = $this->get_related_model_obj($model_name);
2702
-        if (! is_array($query_params)) {
2703
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2704
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2705
-                    gettype($query_params)), '4.6.0');
2706
-            $query_params = array();
2707
-        }
2708
-        //we're just going to use the query params on the related model's normal get_all query,
2709
-        //except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2711
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
-        }
2713
-        $this_model_name = $this->get_this_model_name();
2714
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2716
-        return $related_model->sum($query_params, $field_to_sum);
2717
-    }
2718
-
2719
-
2720
-
2721
-    /**
2722
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
-     * $modelObject
2724
-     *
2725
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
-     * @param array               $query_params     like EEM_Base::get_all's
2728
-     * @return EE_Base_Class
2729
-     * @throws EE_Error
2730
-     */
2731
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
-    {
2733
-        $query_params['limit'] = 1;
2734
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
-        if ($results) {
2736
-            return array_shift($results);
2737
-        }
2738
-        return null;
2739
-    }
2740
-
2741
-
2742
-
2743
-    /**
2744
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
-     *
2746
-     * @return string
2747
-     */
2748
-    public function get_this_model_name()
2749
-    {
2750
-        return str_replace("EEM_", "", get_class($this));
2751
-    }
2752
-
2753
-
2754
-
2755
-    /**
2756
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
-     *
2758
-     * @return EE_Any_Foreign_Model_Name_Field
2759
-     * @throws EE_Error
2760
-     */
2761
-    public function get_field_containing_related_model_name()
2762
-    {
2763
-        foreach ($this->field_settings(true) as $field) {
2764
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
-                $field_with_model_name = $field;
2766
-            }
2767
-        }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770
-                $this->get_this_model_name()));
2771
-        }
2772
-        return $field_with_model_name;
2773
-    }
2774
-
2775
-
2776
-
2777
-    /**
2778
-     * Inserts a new entry into the database, for each table.
2779
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2780
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2781
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2782
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2783
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2784
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2785
-     *
2786
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2787
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2788
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2789
-     *                              of EEM_Base)
2790
-     * @return int new primary key on main table that got inserted
2791
-     * @throws EE_Error
2792
-     */
2793
-    public function insert($field_n_values)
2794
-    {
2795
-        /**
2796
-         * Filters the fields and their values before inserting an item using the models
2797
-         *
2798
-         * @param array    $fields_n_values keys are the fields and values are their new values
2799
-         * @param EEM_Base $model           the model used
2800
-         */
2801
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2803
-            $main_table = $this->_get_main_table();
2804
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2805
-            if ($new_id !== false) {
2806
-                foreach ($this->_get_other_tables() as $other_table) {
2807
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2808
-                }
2809
-            }
2810
-            /**
2811
-             * Done just after attempting to insert a new model object
2812
-             *
2813
-             * @param EEM_Base   $model           used
2814
-             * @param array      $fields_n_values fields and their values
2815
-             * @param int|string the              ID of the newly-inserted model object
2816
-             */
2817
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2818
-            return $new_id;
2819
-        }
2820
-        return false;
2821
-    }
2822
-
2823
-
2824
-
2825
-    /**
2826
-     * Checks that the result would satisfy the unique indexes on this model
2827
-     *
2828
-     * @param array  $field_n_values
2829
-     * @param string $action
2830
-     * @return boolean
2831
-     * @throws EE_Error
2832
-     */
2833
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2834
-    {
2835
-        foreach ($this->unique_indexes() as $index_name => $index) {
2836
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2837
-            if ($this->exists(array($uniqueness_where_params))) {
2838
-                EE_Error::add_error(
2839
-                    sprintf(
2840
-                        __(
2841
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2842
-                            "event_espresso"
2843
-                        ),
2844
-                        $action,
2845
-                        $this->_get_class_name(),
2846
-                        $index_name,
2847
-                        implode(",", $index->field_names()),
2848
-                        http_build_query($uniqueness_where_params)
2849
-                    ),
2850
-                    __FILE__,
2851
-                    __FUNCTION__,
2852
-                    __LINE__
2853
-                );
2854
-                return false;
2855
-            }
2856
-        }
2857
-        return true;
2858
-    }
2859
-
2860
-
2861
-
2862
-    /**
2863
-     * Checks the database for an item that conflicts (ie, if this item were
2864
-     * saved to the DB would break some uniqueness requirement, like a primary key
2865
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2866
-     * can be either an EE_Base_Class or an array of fields n values
2867
-     *
2868
-     * @param EE_Base_Class|array $obj_or_fields_array
2869
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2870
-     *                                                 when looking for conflicts
2871
-     *                                                 (ie, if false, we ignore the model object's primary key
2872
-     *                                                 when finding "conflicts". If true, it's also considered).
2873
-     *                                                 Only works for INT primary key,
2874
-     *                                                 STRING primary keys cannot be ignored
2875
-     * @throws EE_Error
2876
-     * @return EE_Base_Class|array
2877
-     */
2878
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2879
-    {
2880
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2881
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2882
-        } elseif (is_array($obj_or_fields_array)) {
2883
-            $fields_n_values = $obj_or_fields_array;
2884
-        } else {
2885
-            throw new EE_Error(
2886
-                sprintf(
2887
-                    __(
2888
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2889
-                        "event_espresso"
2890
-                    ),
2891
-                    get_class($this),
2892
-                    $obj_or_fields_array
2893
-                )
2894
-            );
2895
-        }
2896
-        $query_params = array();
2897
-        if ($this->has_primary_key_field()
2898
-            && ($include_primary_key
2899
-                || $this->get_primary_key_field()
2900
-                   instanceof
2901
-                   EE_Primary_Key_String_Field)
2902
-            && isset($fields_n_values[$this->primary_key_name()])
2903
-        ) {
2904
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2905
-        }
2906
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2909
-        }
2910
-        //if there is nothing to base this search on, then we shouldn't find anything
2911
-        if (empty($query_params)) {
2912
-            return array();
2913
-        }
2914
-        return $this->get_one($query_params);
2915
-    }
2916
-
2917
-
2918
-
2919
-    /**
2920
-     * Like count, but is optimized and returns a boolean instead of an int
2921
-     *
2922
-     * @param array $query_params
2923
-     * @return boolean
2924
-     * @throws EE_Error
2925
-     */
2926
-    public function exists($query_params)
2927
-    {
2928
-        $query_params['limit'] = 1;
2929
-        return $this->count($query_params) > 0;
2930
-    }
2931
-
2932
-
2933
-
2934
-    /**
2935
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2936
-     *
2937
-     * @param int|string $id
2938
-     * @return boolean
2939
-     * @throws EE_Error
2940
-     */
2941
-    public function exists_by_ID($id)
2942
-    {
2943
-        return $this->exists(
2944
-            array(
2945
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2946
-                array(
2947
-                    $this->primary_key_name() => $id,
2948
-                ),
2949
-            )
2950
-        );
2951
-    }
2952
-
2953
-
2954
-
2955
-    /**
2956
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2957
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2958
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2959
-     * on the main table)
2960
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2961
-     * cases where we want to call it directly rather than via insert().
2962
-     *
2963
-     * @access   protected
2964
-     * @param EE_Table_Base $table
2965
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2966
-     *                                       float
2967
-     * @param int           $new_id          for now we assume only int keys
2968
-     * @throws EE_Error
2969
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2970
-     * @return int ID of new row inserted, or FALSE on failure
2971
-     */
2972
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2973
-    {
2974
-        global $wpdb;
2975
-        $insertion_col_n_values = array();
2976
-        $format_for_insertion = array();
2977
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2978
-        foreach ($fields_on_table as $field_name => $field_obj) {
2979
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2980
-            if ($field_obj->is_auto_increment()) {
2981
-                continue;
2982
-            }
2983
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2985
-            if ($prepared_value !== null) {
2986
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2987
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988
-            }
2989
-        }
2990
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2991
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2992
-            //so add the fk to the main table as a column
2993
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2994
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2995
-        }
2996
-        //insert the new entry
2997
-        $result = $this->_do_wpdb_query('insert',
2998
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2999
-        if ($result === false) {
3000
-            return false;
3001
-        }
3002
-        //ok, now what do we return for the ID of the newly-inserted thing?
3003
-        if ($this->has_primary_key_field()) {
3004
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3005
-                return $wpdb->insert_id;
3006
-            }
3007
-            //it's not an auto-increment primary key, so
3008
-            //it must have been supplied
3009
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3010
-        }
3011
-        //we can't return a  primary key because there is none. instead return
3012
-        //a unique string indicating this model
3013
-        return $this->get_index_primary_key_string($fields_n_values);
3014
-    }
3015
-
3016
-
3017
-
3018
-    /**
3019
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3020
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3021
-     * and there is no default, we pass it along. WPDB will take care of it)
3022
-     *
3023
-     * @param EE_Model_Field_Base $field_obj
3024
-     * @param array               $fields_n_values
3025
-     * @return mixed string|int|float depending on what the table column will be expecting
3026
-     * @throws EE_Error
3027
-     */
3028
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3029
-    {
3030
-        //if this field doesn't allow nullable, don't allow it
3031
-        if (
3032
-            ! $field_obj->is_nullable()
3033
-            && (
3034
-                ! isset($fields_n_values[$field_obj->get_name()])
3035
-                || $fields_n_values[$field_obj->get_name()] === null
3036
-            )
3037
-        ) {
3038
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3039
-        }
3040
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3041
-            ? $fields_n_values[$field_obj->get_name()]
3042
-            : null;
3043
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3044
-    }
3045
-
3046
-
3047
-
3048
-    /**
3049
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3050
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3051
-     * the field's prepare_for_set() method.
3052
-     *
3053
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3054
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3055
-     *                                   top of file)
3056
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3057
-     *                                   $value is a custom selection
3058
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3059
-     */
3060
-    private function _prepare_value_for_use_in_db($value, $field)
3061
-    {
3062
-        if ($field && $field instanceof EE_Model_Field_Base) {
3063
-            switch ($this->_values_already_prepared_by_model_object) {
3064
-                /** @noinspection PhpMissingBreakStatementInspection */
3065
-                case self::not_prepared_by_model_object:
3066
-                    $value = $field->prepare_for_set($value);
3067
-                //purposefully left out "return"
3068
-                case self::prepared_by_model_object:
3069
-                    /** @noinspection SuspiciousAssignmentsInspection */
3070
-                    $value = $field->prepare_for_use_in_db($value);
3071
-                case self::prepared_for_use_in_db:
3072
-                    //leave the value alone
3073
-            }
3074
-            return $value;
3075
-        }
3076
-        return $value;
3077
-    }
3078
-
3079
-
3080
-
3081
-    /**
3082
-     * Returns the main table on this model
3083
-     *
3084
-     * @return EE_Primary_Table
3085
-     * @throws EE_Error
3086
-     */
3087
-    protected function _get_main_table()
3088
-    {
3089
-        foreach ($this->_tables as $table) {
3090
-            if ($table instanceof EE_Primary_Table) {
3091
-                return $table;
3092
-            }
3093
-        }
3094
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3095
-            'event_espresso'), get_class($this)));
3096
-    }
3097
-
3098
-
3099
-
3100
-    /**
3101
-     * table
3102
-     * returns EE_Primary_Table table name
3103
-     *
3104
-     * @return string
3105
-     * @throws EE_Error
3106
-     */
3107
-    public function table()
3108
-    {
3109
-        return $this->_get_main_table()->get_table_name();
3110
-    }
3111
-
3112
-
3113
-
3114
-    /**
3115
-     * table
3116
-     * returns first EE_Secondary_Table table name
3117
-     *
3118
-     * @return string
3119
-     */
3120
-    public function second_table()
3121
-    {
3122
-        // grab second table from tables array
3123
-        $second_table = end($this->_tables);
3124
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * get_table_obj_by_alias
3131
-     * returns table name given it's alias
3132
-     *
3133
-     * @param string $table_alias
3134
-     * @return EE_Primary_Table | EE_Secondary_Table
3135
-     */
3136
-    public function get_table_obj_by_alias($table_alias = '')
3137
-    {
3138
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3139
-    }
3140
-
3141
-
3142
-
3143
-    /**
3144
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3145
-     *
3146
-     * @return EE_Secondary_Table[]
3147
-     */
3148
-    protected function _get_other_tables()
3149
-    {
3150
-        $other_tables = array();
3151
-        foreach ($this->_tables as $table_alias => $table) {
3152
-            if ($table instanceof EE_Secondary_Table) {
3153
-                $other_tables[$table_alias] = $table;
3154
-            }
3155
-        }
3156
-        return $other_tables;
3157
-    }
3158
-
3159
-
3160
-
3161
-    /**
3162
-     * Finds all the fields that correspond to the given table
3163
-     *
3164
-     * @param string $table_alias , array key in EEM_Base::_tables
3165
-     * @return EE_Model_Field_Base[]
3166
-     */
3167
-    public function _get_fields_for_table($table_alias)
3168
-    {
3169
-        return $this->_fields[$table_alias];
3170
-    }
3171
-
3172
-
3173
-
3174
-    /**
3175
-     * Recurses through all the where parameters, and finds all the related models we'll need
3176
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3177
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3178
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3179
-     * related Registration, Transaction, and Payment models.
3180
-     *
3181
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3182
-     * @return EE_Model_Query_Info_Carrier
3183
-     * @throws EE_Error
3184
-     */
3185
-    public function _extract_related_models_from_query($query_params)
3186
-    {
3187
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3188
-        if (array_key_exists(0, $query_params)) {
3189
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3190
-        }
3191
-        if (array_key_exists('group_by', $query_params)) {
3192
-            if (is_array($query_params['group_by'])) {
3193
-                $this->_extract_related_models_from_sub_params_array_values(
3194
-                    $query_params['group_by'],
3195
-                    $query_info_carrier,
3196
-                    'group_by'
3197
-                );
3198
-            } elseif (! empty ($query_params['group_by'])) {
3199
-                $this->_extract_related_model_info_from_query_param(
3200
-                    $query_params['group_by'],
3201
-                    $query_info_carrier,
3202
-                    'group_by'
3203
-                );
3204
-            }
3205
-        }
3206
-        if (array_key_exists('having', $query_params)) {
3207
-            $this->_extract_related_models_from_sub_params_array_keys(
3208
-                $query_params[0],
3209
-                $query_info_carrier,
3210
-                'having'
3211
-            );
3212
-        }
3213
-        if (array_key_exists('order_by', $query_params)) {
3214
-            if (is_array($query_params['order_by'])) {
3215
-                $this->_extract_related_models_from_sub_params_array_keys(
3216
-                    $query_params['order_by'],
3217
-                    $query_info_carrier,
3218
-                    'order_by'
3219
-                );
3220
-            } elseif (! empty($query_params['order_by'])) {
3221
-                $this->_extract_related_model_info_from_query_param(
3222
-                    $query_params['order_by'],
3223
-                    $query_info_carrier,
3224
-                    'order_by'
3225
-                );
3226
-            }
3227
-        }
3228
-        if (array_key_exists('force_join', $query_params)) {
3229
-            $this->_extract_related_models_from_sub_params_array_values(
3230
-                $query_params['force_join'],
3231
-                $query_info_carrier,
3232
-                'force_join'
3233
-            );
3234
-        }
3235
-        return $query_info_carrier;
3236
-    }
3237
-
3238
-
3239
-
3240
-    /**
3241
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3242
-     *
3243
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3244
-     *                                                      $query_params['having']
3245
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3246
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3247
-     * @throws EE_Error
3248
-     * @return \EE_Model_Query_Info_Carrier
3249
-     */
3250
-    private function _extract_related_models_from_sub_params_array_keys(
3251
-        $sub_query_params,
3252
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253
-        $query_param_type
3254
-    ) {
3255
-        if (! empty($sub_query_params)) {
3256
-            $sub_query_params = (array)$sub_query_params;
3257
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3260
-                    $query_param_type);
3261
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3262
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3263
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3264
-                //of array('Registration.TXN_ID'=>23)
3265
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3266
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3267
-                    if (! is_array($possibly_array_of_params)) {
3268
-                        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'))",
3269
-                            "event_espresso"),
3270
-                            $param, $possibly_array_of_params));
3271
-                    }
3272
-                    $this->_extract_related_models_from_sub_params_array_keys(
3273
-                        $possibly_array_of_params,
3274
-                        $model_query_info_carrier, $query_param_type
3275
-                    );
3276
-                } elseif ($query_param_type === 0 //ie WHERE
3277
-                          && is_array($possibly_array_of_params)
3278
-                          && isset($possibly_array_of_params[2])
3279
-                          && $possibly_array_of_params[2] == true
3280
-                ) {
3281
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3282
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3283
-                    //from which we should extract query parameters!
3284
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3285
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3286
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3287
-                    }
3288
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3289
-                        $model_query_info_carrier, $query_param_type);
3290
-                }
3291
-            }
3292
-        }
3293
-        return $model_query_info_carrier;
3294
-    }
3295
-
3296
-
3297
-
3298
-    /**
3299
-     * For extracting related models from forced_joins, where the array values contain the info about what
3300
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3301
-     *
3302
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3303
-     *                                                      $query_params['having']
3304
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3306
-     * @throws EE_Error
3307
-     * @return \EE_Model_Query_Info_Carrier
3308
-     */
3309
-    private function _extract_related_models_from_sub_params_array_values(
3310
-        $sub_query_params,
3311
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
-        $query_param_type
3313
-    ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            if (! is_array($sub_query_params)) {
3316
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3317
-                    $sub_query_params));
3318
-            }
3319
-            foreach ($sub_query_params as $param) {
3320
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3321
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3322
-                    $query_param_type);
3323
-            }
3324
-        }
3325
-        return $model_query_info_carrier;
3326
-    }
3327
-
3328
-
3329
-
3330
-    /**
3331
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3332
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3333
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3334
-     * but use them in a different order. Eg, we need to know what models we are querying
3335
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3336
-     * other models before we can finalize the where clause SQL.
3337
-     *
3338
-     * @param array $query_params
3339
-     * @throws EE_Error
3340
-     * @return EE_Model_Query_Info_Carrier
3341
-     */
3342
-    public function _create_model_query_info_carrier($query_params)
3343
-    {
3344
-        if (! is_array($query_params)) {
3345
-            EE_Error::doing_it_wrong(
3346
-                'EEM_Base::_create_model_query_info_carrier',
3347
-                sprintf(
3348
-                    __(
3349
-                        '$query_params should be an array, you passed a variable of type %s',
3350
-                        'event_espresso'
3351
-                    ),
3352
-                    gettype($query_params)
3353
-                ),
3354
-                '4.6.0'
3355
-            );
3356
-            $query_params = array();
3357
-        }
3358
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3359
-        //first check if we should alter the query to account for caps or not
3360
-        //because the caps might require us to do extra joins
3361
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3362
-            $query_params[0] = $where_query_params = array_replace_recursive(
3363
-                $where_query_params,
3364
-                $this->caps_where_conditions(
3365
-                    $query_params['caps']
3366
-                )
3367
-            );
3368
-        }
3369
-        $query_object = $this->_extract_related_models_from_query($query_params);
3370
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3371
-        foreach ($where_query_params as $key => $value) {
3372
-            if (is_int($key)) {
3373
-                throw new EE_Error(
3374
-                    sprintf(
3375
-                        __(
3376
-                            "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.",
3377
-                            "event_espresso"
3378
-                        ),
3379
-                        $key,
3380
-                        var_export($value, true),
3381
-                        var_export($query_params, true),
3382
-                        get_class($this)
3383
-                    )
3384
-                );
3385
-            }
3386
-        }
3387
-        if (
3388
-            array_key_exists('default_where_conditions', $query_params)
3389
-            && ! empty($query_params['default_where_conditions'])
3390
-        ) {
3391
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3392
-        } else {
3393
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3394
-        }
3395
-        $where_query_params = array_merge(
3396
-            $this->_get_default_where_conditions_for_models_in_query(
3397
-                $query_object,
3398
-                $use_default_where_conditions,
3399
-                $where_query_params
3400
-            ),
3401
-            $where_query_params
3402
-        );
3403
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3404
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3405
-        // So we need to setup a subquery and use that for the main join.
3406
-        // Note for now this only works on the primary table for the model.
3407
-        // So for instance, you could set the limit array like this:
3408
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3409
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3410
-            $query_object->set_main_model_join_sql(
3411
-                $this->_construct_limit_join_select(
3412
-                    $query_params['on_join_limit'][0],
3413
-                    $query_params['on_join_limit'][1]
3414
-                )
3415
-            );
3416
-        }
3417
-        //set limit
3418
-        if (array_key_exists('limit', $query_params)) {
3419
-            if (is_array($query_params['limit'])) {
3420
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3421
-                    $e = sprintf(
3422
-                        __(
3423
-                            "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)",
3424
-                            "event_espresso"
3425
-                        ),
3426
-                        http_build_query($query_params['limit'])
3427
-                    );
3428
-                    throw new EE_Error($e . "|" . $e);
3429
-                }
3430
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3431
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3432
-            } elseif (! empty ($query_params['limit'])) {
3433
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3434
-            }
3435
-        }
3436
-        //set order by
3437
-        if (array_key_exists('order_by', $query_params)) {
3438
-            if (is_array($query_params['order_by'])) {
3439
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3440
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3441
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3442
-                if (array_key_exists('order', $query_params)) {
3443
-                    throw new EE_Error(
3444
-                        sprintf(
3445
-                            __(
3446
-                                "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 ",
3447
-                                "event_espresso"
3448
-                            ),
3449
-                            get_class($this),
3450
-                            implode(", ", array_keys($query_params['order_by'])),
3451
-                            implode(", ", $query_params['order_by']),
3452
-                            $query_params['order']
3453
-                        )
3454
-                    );
3455
-                }
3456
-                $this->_extract_related_models_from_sub_params_array_keys(
3457
-                    $query_params['order_by'],
3458
-                    $query_object,
3459
-                    'order_by'
3460
-                );
3461
-                //assume it's an array of fields to order by
3462
-                $order_array = array();
3463
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3464
-                    $order = $this->_extract_order($order);
3465
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3466
-                }
3467
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3468
-            } elseif (! empty ($query_params['order_by'])) {
3469
-                $this->_extract_related_model_info_from_query_param(
3470
-                    $query_params['order_by'],
3471
-                    $query_object,
3472
-                    'order',
3473
-                    $query_params['order_by']
3474
-                );
3475
-                $order = isset($query_params['order'])
3476
-                    ? $this->_extract_order($query_params['order'])
3477
-                    : 'DESC';
3478
-                $query_object->set_order_by_sql(
3479
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3480
-                );
3481
-            }
3482
-        }
3483
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3484
-        if (! array_key_exists('order_by', $query_params)
3485
-            && array_key_exists('order', $query_params)
3486
-            && ! empty($query_params['order'])
3487
-        ) {
3488
-            $pk_field = $this->get_primary_key_field();
3489
-            $order = $this->_extract_order($query_params['order']);
3490
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3491
-        }
3492
-        //set group by
3493
-        if (array_key_exists('group_by', $query_params)) {
3494
-            if (is_array($query_params['group_by'])) {
3495
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3496
-                $group_by_array = array();
3497
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3498
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3499
-                }
3500
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3501
-            } elseif (! empty ($query_params['group_by'])) {
3502
-                $query_object->set_group_by_sql(
3503
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3504
-                );
3505
-            }
3506
-        }
3507
-        //set having
3508
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3509
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3510
-        }
3511
-        //now, just verify they didn't pass anything wack
3512
-        foreach ($query_params as $query_key => $query_value) {
3513
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3514
-                throw new EE_Error(
3515
-                    sprintf(
3516
-                        __(
3517
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3518
-                            'event_espresso'
3519
-                        ),
3520
-                        $query_key,
3521
-                        get_class($this),
3522
-                        //						print_r( $this->_allowed_query_params, TRUE )
3523
-                        implode(',', $this->_allowed_query_params)
3524
-                    )
3525
-                );
3526
-            }
3527
-        }
3528
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3529
-        if (empty($main_model_join_sql)) {
3530
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3531
-        }
3532
-        return $query_object;
3533
-    }
3534
-
3535
-
3536
-
3537
-    /**
3538
-     * Gets the where conditions that should be imposed on the query based on the
3539
-     * context (eg reading frontend, backend, edit or delete).
3540
-     *
3541
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3542
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3543
-     * @throws EE_Error
3544
-     */
3545
-    public function caps_where_conditions($context = self::caps_read)
3546
-    {
3547
-        EEM_Base::verify_is_valid_cap_context($context);
3548
-        $cap_where_conditions = array();
3549
-        $cap_restrictions = $this->caps_missing($context);
3550
-        /**
3551
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3552
-         */
3553
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3554
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3555
-                $restriction_if_no_cap->get_default_where_conditions());
3556
-        }
3557
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3558
-            $cap_restrictions);
3559
-    }
3560
-
3561
-
3562
-
3563
-    /**
3564
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3565
-     * otherwise throws an exception
3566
-     *
3567
-     * @param string $should_be_order_string
3568
-     * @return string either ASC, asc, DESC or desc
3569
-     * @throws EE_Error
3570
-     */
3571
-    private function _extract_order($should_be_order_string)
3572
-    {
3573
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3574
-            return $should_be_order_string;
3575
-        }
3576
-        throw new EE_Error(
3577
-            sprintf(
3578
-                __(
3579
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3580
-                    "event_espresso"
3581
-                ), get_class($this), $should_be_order_string
3582
-            )
3583
-        );
3584
-    }
3585
-
3586
-
3587
-
3588
-    /**
3589
-     * Looks at all the models which are included in this query, and asks each
3590
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3591
-     * so they can be merged
3592
-     *
3593
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3594
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3595
-     *                                                                  'none' means NO default where conditions will
3596
-     *                                                                  be used AT ALL during this query.
3597
-     *                                                                  'other_models_only' means default where
3598
-     *                                                                  conditions from other models will be used, but
3599
-     *                                                                  not for this primary model. 'all', the default,
3600
-     *                                                                  means default where conditions will apply as
3601
-     *                                                                  normal
3602
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3603
-     * @throws EE_Error
3604
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3605
-     */
3606
-    private function _get_default_where_conditions_for_models_in_query(
3607
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3608
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3609
-        $where_query_params = array()
3610
-    ) {
3611
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3612
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3613
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3614
-                "event_espresso"), $use_default_where_conditions,
3615
-                implode(", ", $allowed_used_default_where_conditions_values)));
3616
-        }
3617
-        $universal_query_params = array();
3618
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3619
-            $universal_query_params = $this->_get_default_where_conditions();
3620
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3621
-            $universal_query_params = $this->_get_minimum_where_conditions();
3622
-        }
3623
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3624
-            $related_model = $this->get_related_model_obj($model_name);
3625
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3626
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3627
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3628
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3629
-            } else {
3630
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3631
-                continue;
3632
-            }
3633
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3634
-                $related_model_universal_where_params,
3635
-                $where_query_params,
3636
-                $related_model,
3637
-                $model_relation_path
3638
-            );
3639
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3640
-                $universal_query_params,
3641
-                $overrides
3642
-            );
3643
-        }
3644
-        return $universal_query_params;
3645
-    }
3646
-
3647
-
3648
-
3649
-    /**
3650
-     * Determines whether or not we should use default where conditions for the model in question
3651
-     * (this model, or other related models).
3652
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3653
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3654
-     * We should use default where conditions on related models when they requested to use default where conditions
3655
-     * on all models, or specifically just on other related models
3656
-     * @param      $default_where_conditions_value
3657
-     * @param bool $for_this_model false means this is for OTHER related models
3658
-     * @return bool
3659
-     */
3660
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3661
-    {
3662
-        return (
3663
-                   $for_this_model
3664
-                   && in_array(
3665
-                       $default_where_conditions_value,
3666
-                       array(
3667
-                           EEM_Base::default_where_conditions_all,
3668
-                           EEM_Base::default_where_conditions_this_only,
3669
-                           EEM_Base::default_where_conditions_minimum_others,
3670
-                       ),
3671
-                       true
3672
-                   )
3673
-               )
3674
-               || (
3675
-                   ! $for_this_model
3676
-                   && in_array(
3677
-                       $default_where_conditions_value,
3678
-                       array(
3679
-                           EEM_Base::default_where_conditions_all,
3680
-                           EEM_Base::default_where_conditions_others_only,
3681
-                       ),
3682
-                       true
3683
-                   )
3684
-               );
3685
-    }
3686
-
3687
-    /**
3688
-     * Determines whether or not we should use default minimum conditions for the model in question
3689
-     * (this model, or other related models).
3690
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3691
-     * where conditions.
3692
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3693
-     * on this model or others
3694
-     * @param      $default_where_conditions_value
3695
-     * @param bool $for_this_model false means this is for OTHER related models
3696
-     * @return bool
3697
-     */
3698
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3699
-    {
3700
-        return (
3701
-                   $for_this_model
3702
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3703
-               )
3704
-               || (
3705
-                   ! $for_this_model
3706
-                   && in_array(
3707
-                       $default_where_conditions_value,
3708
-                       array(
3709
-                           EEM_Base::default_where_conditions_minimum_others,
3710
-                           EEM_Base::default_where_conditions_minimum_all,
3711
-                       ),
3712
-                       true
3713
-                   )
3714
-               );
3715
-    }
3716
-
3717
-
3718
-    /**
3719
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3720
-     * then we also add a special where condition which allows for that model's primary key
3721
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3722
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3723
-     *
3724
-     * @param array    $default_where_conditions
3725
-     * @param array    $provided_where_conditions
3726
-     * @param EEM_Base $model
3727
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3728
-     * @return array like EEM_Base::get_all's $query_params[0]
3729
-     * @throws EE_Error
3730
-     */
3731
-    private function _override_defaults_or_make_null_friendly(
3732
-        $default_where_conditions,
3733
-        $provided_where_conditions,
3734
-        $model,
3735
-        $model_relation_path
3736
-    ) {
3737
-        $null_friendly_where_conditions = array();
3738
-        $none_overridden = true;
3739
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3740
-        foreach ($default_where_conditions as $key => $val) {
3741
-            if (isset($provided_where_conditions[$key])) {
3742
-                $none_overridden = false;
3743
-            } else {
3744
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3745
-            }
3746
-        }
3747
-        if ($none_overridden && $default_where_conditions) {
3748
-            if ($model->has_primary_key_field()) {
3749
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3750
-                                                                                . "."
3751
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3752
-            }/*else{
2212
+	/**
2213
+	 * Gets the model field by the fully qualified name
2214
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2215
+	 * @return EE_Model_Field_Base
2216
+	 */
2217
+	public function get_field_by_column($qualified_column_name)
2218
+	{
2219
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2220
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2221
+			   return $field_obj;
2222
+		   }
2223
+	   }
2224
+		throw new EE_Error(
2225
+			sprintf(
2226
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2227
+				$this->get_this_model_name(),
2228
+				$qualified_column_name
2229
+			)
2230
+		);
2231
+	}
2232
+
2233
+
2234
+
2235
+	/**
2236
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2237
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2238
+	 * column
2239
+	 *
2240
+	 * @param array  $query_params   like EEM_Base::get_all's
2241
+	 * @param string $field_to_count field on model to count by (not column name)
2242
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2243
+	 *                               that by the setting $distinct to TRUE;
2244
+	 * @return int
2245
+	 * @throws EE_Error
2246
+	 */
2247
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2248
+	{
2249
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2250
+		if ($field_to_count) {
2251
+			$field_obj = $this->field_settings_for($field_to_count);
2252
+			$column_to_count = $field_obj->get_qualified_column();
2253
+		} elseif ($this->has_primary_key_field()) {
2254
+			$pk_field_obj = $this->get_primary_key_field();
2255
+			$column_to_count = $pk_field_obj->get_qualified_column();
2256
+		} else {
2257
+			//there's no primary key
2258
+			//if we're counting distinct items, and there's no primary key,
2259
+			//we need to list out the columns for distinction;
2260
+			//otherwise we can just use star
2261
+			if ($distinct) {
2262
+				$columns_to_use = array();
2263
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2264
+					$columns_to_use[] = $field_obj->get_qualified_column();
2265
+				}
2266
+				$column_to_count = implode(',', $columns_to_use);
2267
+			} else {
2268
+				$column_to_count = '*';
2269
+			}
2270
+		}
2271
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2272
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2273
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2274
+	}
2275
+
2276
+
2277
+
2278
+	/**
2279
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2280
+	 *
2281
+	 * @param array  $query_params like EEM_Base::get_all
2282
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2283
+	 * @return float
2284
+	 * @throws EE_Error
2285
+	 */
2286
+	public function sum($query_params, $field_to_sum = null)
2287
+	{
2288
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2289
+		if ($field_to_sum) {
2290
+			$field_obj = $this->field_settings_for($field_to_sum);
2291
+		} else {
2292
+			$field_obj = $this->get_primary_key_field();
2293
+		}
2294
+		$column_to_count = $field_obj->get_qualified_column();
2295
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2297
+		$data_type = $field_obj->get_wpdb_data_type();
2298
+		if ($data_type === '%d' || $data_type === '%s') {
2299
+			return (float)$return_value;
2300
+		}
2301
+		//must be %f
2302
+		return (float)$return_value;
2303
+	}
2304
+
2305
+
2306
+
2307
+	/**
2308
+	 * Just calls the specified method on $wpdb with the given arguments
2309
+	 * Consolidates a little extra error handling code
2310
+	 *
2311
+	 * @param string $wpdb_method
2312
+	 * @param array  $arguments_to_provide
2313
+	 * @throws EE_Error
2314
+	 * @global wpdb  $wpdb
2315
+	 * @return mixed
2316
+	 */
2317
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2318
+	{
2319
+		//if we're in maintenance mode level 2, DON'T run any queries
2320
+		//because level 2 indicates the database needs updating and
2321
+		//is probably out of sync with the code
2322
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2323
+			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.",
2324
+				"event_espresso")));
2325
+		}
2326
+		/** @type WPDB $wpdb */
2327
+		global $wpdb;
2328
+		if (! method_exists($wpdb, $wpdb_method)) {
2329
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2330
+				'event_espresso'), $wpdb_method));
2331
+		}
2332
+		if (WP_DEBUG) {
2333
+			$old_show_errors_value = $wpdb->show_errors;
2334
+			$wpdb->show_errors(false);
2335
+		}
2336
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2337
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2338
+		if (WP_DEBUG) {
2339
+			$wpdb->show_errors($old_show_errors_value);
2340
+			if (! empty($wpdb->last_error)) {
2341
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2342
+			}
2343
+			if ($result === false) {
2344
+				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"',
2345
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2346
+			}
2347
+		} elseif ($result === false) {
2348
+			EE_Error::add_error(
2349
+				sprintf(
2350
+					__('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"',
2351
+						'event_espresso'),
2352
+					$wpdb_method,
2353
+					var_export($arguments_to_provide, true),
2354
+					$wpdb->last_error
2355
+				),
2356
+				__FILE__,
2357
+				__FUNCTION__,
2358
+				__LINE__
2359
+			);
2360
+		}
2361
+		return $result;
2362
+	}
2363
+
2364
+
2365
+
2366
+	/**
2367
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2368
+	 * and if there's an error tries to verify the DB is correct. Uses
2369
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2370
+	 * we should try to fix the EE core db, the addons, or just give up
2371
+	 *
2372
+	 * @param string $wpdb_method
2373
+	 * @param array  $arguments_to_provide
2374
+	 * @return mixed
2375
+	 */
2376
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2377
+	{
2378
+		/** @type WPDB $wpdb */
2379
+		global $wpdb;
2380
+		$wpdb->last_error = null;
2381
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2382
+		// was there an error running the query? but we don't care on new activations
2383
+		// (we're going to setup the DB anyway on new activations)
2384
+		if (($result === false || ! empty($wpdb->last_error))
2385
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2386
+		) {
2387
+			switch (EEM_Base::$_db_verification_level) {
2388
+				case EEM_Base::db_verified_none :
2389
+					// let's double-check core's DB
2390
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2391
+					break;
2392
+				case EEM_Base::db_verified_core :
2393
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2394
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2395
+					break;
2396
+				case EEM_Base::db_verified_addons :
2397
+					// ummmm... you in trouble
2398
+					return $result;
2399
+					break;
2400
+			}
2401
+			if (! empty($error_message)) {
2402
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2403
+				trigger_error($error_message);
2404
+			}
2405
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2406
+		}
2407
+		return $result;
2408
+	}
2409
+
2410
+
2411
+
2412
+	/**
2413
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2414
+	 * EEM_Base::$_db_verification_level
2415
+	 *
2416
+	 * @param string $wpdb_method
2417
+	 * @param array  $arguments_to_provide
2418
+	 * @return string
2419
+	 */
2420
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2421
+	{
2422
+		/** @type WPDB $wpdb */
2423
+		global $wpdb;
2424
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2425
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2426
+		$error_message = sprintf(
2427
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
+				'event_espresso'),
2429
+			$wpdb->last_error,
2430
+			$wpdb_method,
2431
+			wp_json_encode($arguments_to_provide)
2432
+		);
2433
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2434
+		return $error_message;
2435
+	}
2436
+
2437
+
2438
+
2439
+	/**
2440
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2441
+	 * EEM_Base::$_db_verification_level
2442
+	 *
2443
+	 * @param $wpdb_method
2444
+	 * @param $arguments_to_provide
2445
+	 * @return string
2446
+	 */
2447
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2448
+	{
2449
+		/** @type WPDB $wpdb */
2450
+		global $wpdb;
2451
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2452
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2453
+		$error_message = sprintf(
2454
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
+				'event_espresso'),
2456
+			$wpdb->last_error,
2457
+			$wpdb_method,
2458
+			wp_json_encode($arguments_to_provide)
2459
+		);
2460
+		EE_System::instance()->initialize_addons();
2461
+		return $error_message;
2462
+	}
2463
+
2464
+
2465
+
2466
+	/**
2467
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2468
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2469
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2470
+	 * ..."
2471
+	 *
2472
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2473
+	 * @return string
2474
+	 */
2475
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476
+	{
2477
+		return " FROM " . $model_query_info->get_full_join_sql() .
2478
+			   $model_query_info->get_where_sql() .
2479
+			   $model_query_info->get_group_by_sql() .
2480
+			   $model_query_info->get_having_sql() .
2481
+			   $model_query_info->get_order_by_sql() .
2482
+			   $model_query_info->get_limit_sql();
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * Set to easily debug the next X queries ran from this model.
2489
+	 *
2490
+	 * @param int $count
2491
+	 */
2492
+	public function show_next_x_db_queries($count = 1)
2493
+	{
2494
+		$this->_show_next_x_db_queries = $count;
2495
+	}
2496
+
2497
+
2498
+
2499
+	/**
2500
+	 * @param $sql_query
2501
+	 */
2502
+	public function show_db_query_if_previously_requested($sql_query)
2503
+	{
2504
+		if ($this->_show_next_x_db_queries > 0) {
2505
+			echo $sql_query;
2506
+			$this->_show_next_x_db_queries--;
2507
+		}
2508
+	}
2509
+
2510
+
2511
+
2512
+	/**
2513
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2514
+	 * There are the 3 cases:
2515
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2516
+	 * $otherModelObject has no ID, it is first saved.
2517
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2518
+	 * has no ID, it is first saved.
2519
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2520
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2521
+	 * join table
2522
+	 *
2523
+	 * @param        EE_Base_Class                     /int $thisModelObject
2524
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2525
+	 * @param string $relationName                     , key in EEM_Base::_relations
2526
+	 *                                                 an attendee to a group, you also want to specify which role they
2527
+	 *                                                 will have in that group. So you would use this parameter to
2528
+	 *                                                 specify array('role-column-name'=>'role-id')
2529
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2530
+	 *                                                 to for relation to methods that allow you to further specify
2531
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2532
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2533
+	 *                                                 because these will be inserted in any new rows created as well.
2534
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2535
+	 * @throws EE_Error
2536
+	 */
2537
+	public function add_relationship_to(
2538
+		$id_or_obj,
2539
+		$other_model_id_or_obj,
2540
+		$relationName,
2541
+		$extra_join_model_fields_n_values = array()
2542
+	) {
2543
+		$relation_obj = $this->related_settings_for($relationName);
2544
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2551
+	 * There are the 3 cases:
2552
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2553
+	 * error
2554
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2555
+	 * an error
2556
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2557
+	 *
2558
+	 * @param        EE_Base_Class /int $id_or_obj
2559
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2560
+	 * @param string $relationName key in EEM_Base::_relations
2561
+	 * @return boolean of success
2562
+	 * @throws EE_Error
2563
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2564
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566
+	 *                             because these will be inserted in any new rows created as well.
2567
+	 */
2568
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569
+	{
2570
+		$relation_obj = $this->related_settings_for($relationName);
2571
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2572
+	}
2573
+
2574
+
2575
+
2576
+	/**
2577
+	 * @param mixed           $id_or_obj
2578
+	 * @param string          $relationName
2579
+	 * @param array           $where_query_params
2580
+	 * @param EE_Base_Class[] objects to which relations were removed
2581
+	 * @return \EE_Base_Class[]
2582
+	 * @throws EE_Error
2583
+	 */
2584
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2585
+	{
2586
+		$relation_obj = $this->related_settings_for($relationName);
2587
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2588
+	}
2589
+
2590
+
2591
+
2592
+	/**
2593
+	 * Gets all the related items of the specified $model_name, using $query_params.
2594
+	 * Note: by default, we remove the "default query params"
2595
+	 * because we want to get even deleted items etc.
2596
+	 *
2597
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2598
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2599
+	 * @param array  $query_params like EEM_Base::get_all
2600
+	 * @return EE_Base_Class[]
2601
+	 * @throws EE_Error
2602
+	 */
2603
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2604
+	{
2605
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2606
+		$relation_settings = $this->related_settings_for($model_name);
2607
+		return $relation_settings->get_all_related($model_obj, $query_params);
2608
+	}
2609
+
2610
+
2611
+
2612
+	/**
2613
+	 * Deletes all the model objects across the relation indicated by $model_name
2614
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2615
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2616
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617
+	 *
2618
+	 * @param EE_Base_Class|int|string $id_or_obj
2619
+	 * @param string                   $model_name
2620
+	 * @param array                    $query_params
2621
+	 * @return int how many deleted
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2625
+	{
2626
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2627
+		$relation_settings = $this->related_settings_for($model_name);
2628
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2629
+	}
2630
+
2631
+
2632
+
2633
+	/**
2634
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2635
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2636
+	 * the model objects can't be hard deleted because of blocking related model objects,
2637
+	 * just does a soft-delete on them instead.
2638
+	 *
2639
+	 * @param EE_Base_Class|int|string $id_or_obj
2640
+	 * @param string                   $model_name
2641
+	 * @param array                    $query_params
2642
+	 * @return int how many deleted
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2646
+	{
2647
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2648
+		$relation_settings = $this->related_settings_for($model_name);
2649
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2650
+	}
2651
+
2652
+
2653
+
2654
+	/**
2655
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2656
+	 * unless otherwise specified in the $query_params
2657
+	 *
2658
+	 * @param        int             /EE_Base_Class $id_or_obj
2659
+	 * @param string $model_name     like 'Event', or 'Registration'
2660
+	 * @param array  $query_params   like EEM_Base::get_all's
2661
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2662
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2663
+	 *                               that by the setting $distinct to TRUE;
2664
+	 * @return int
2665
+	 * @throws EE_Error
2666
+	 */
2667
+	public function count_related(
2668
+		$id_or_obj,
2669
+		$model_name,
2670
+		$query_params = array(),
2671
+		$field_to_count = null,
2672
+		$distinct = false
2673
+	) {
2674
+		$related_model = $this->get_related_model_obj($model_name);
2675
+		//we're just going to use the query params on the related model's normal get_all query,
2676
+		//except add a condition to say to match the current mod
2677
+		if (! isset($query_params['default_where_conditions'])) {
2678
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679
+		}
2680
+		$this_model_name = $this->get_this_model_name();
2681
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2683
+		return $related_model->count($query_params, $field_to_count, $distinct);
2684
+	}
2685
+
2686
+
2687
+
2688
+	/**
2689
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2690
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2691
+	 *
2692
+	 * @param        int           /EE_Base_Class $id_or_obj
2693
+	 * @param string $model_name   like 'Event', or 'Registration'
2694
+	 * @param array  $query_params like EEM_Base::get_all's
2695
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2696
+	 * @return float
2697
+	 * @throws EE_Error
2698
+	 */
2699
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700
+	{
2701
+		$related_model = $this->get_related_model_obj($model_name);
2702
+		if (! is_array($query_params)) {
2703
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2704
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2705
+					gettype($query_params)), '4.6.0');
2706
+			$query_params = array();
2707
+		}
2708
+		//we're just going to use the query params on the related model's normal get_all query,
2709
+		//except add a condition to say to match the current mod
2710
+		if (! isset($query_params['default_where_conditions'])) {
2711
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
+		}
2713
+		$this_model_name = $this->get_this_model_name();
2714
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2716
+		return $related_model->sum($query_params, $field_to_sum);
2717
+	}
2718
+
2719
+
2720
+
2721
+	/**
2722
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
+	 * $modelObject
2724
+	 *
2725
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
+	 * @param array               $query_params     like EEM_Base::get_all's
2728
+	 * @return EE_Base_Class
2729
+	 * @throws EE_Error
2730
+	 */
2731
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
+	{
2733
+		$query_params['limit'] = 1;
2734
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
+		if ($results) {
2736
+			return array_shift($results);
2737
+		}
2738
+		return null;
2739
+	}
2740
+
2741
+
2742
+
2743
+	/**
2744
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
+	 *
2746
+	 * @return string
2747
+	 */
2748
+	public function get_this_model_name()
2749
+	{
2750
+		return str_replace("EEM_", "", get_class($this));
2751
+	}
2752
+
2753
+
2754
+
2755
+	/**
2756
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
+	 *
2758
+	 * @return EE_Any_Foreign_Model_Name_Field
2759
+	 * @throws EE_Error
2760
+	 */
2761
+	public function get_field_containing_related_model_name()
2762
+	{
2763
+		foreach ($this->field_settings(true) as $field) {
2764
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
+				$field_with_model_name = $field;
2766
+			}
2767
+		}
2768
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770
+				$this->get_this_model_name()));
2771
+		}
2772
+		return $field_with_model_name;
2773
+	}
2774
+
2775
+
2776
+
2777
+	/**
2778
+	 * Inserts a new entry into the database, for each table.
2779
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2780
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2781
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2782
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2783
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2784
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2785
+	 *
2786
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2787
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2788
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2789
+	 *                              of EEM_Base)
2790
+	 * @return int new primary key on main table that got inserted
2791
+	 * @throws EE_Error
2792
+	 */
2793
+	public function insert($field_n_values)
2794
+	{
2795
+		/**
2796
+		 * Filters the fields and their values before inserting an item using the models
2797
+		 *
2798
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2799
+		 * @param EEM_Base $model           the model used
2800
+		 */
2801
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2803
+			$main_table = $this->_get_main_table();
2804
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2805
+			if ($new_id !== false) {
2806
+				foreach ($this->_get_other_tables() as $other_table) {
2807
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2808
+				}
2809
+			}
2810
+			/**
2811
+			 * Done just after attempting to insert a new model object
2812
+			 *
2813
+			 * @param EEM_Base   $model           used
2814
+			 * @param array      $fields_n_values fields and their values
2815
+			 * @param int|string the              ID of the newly-inserted model object
2816
+			 */
2817
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2818
+			return $new_id;
2819
+		}
2820
+		return false;
2821
+	}
2822
+
2823
+
2824
+
2825
+	/**
2826
+	 * Checks that the result would satisfy the unique indexes on this model
2827
+	 *
2828
+	 * @param array  $field_n_values
2829
+	 * @param string $action
2830
+	 * @return boolean
2831
+	 * @throws EE_Error
2832
+	 */
2833
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2834
+	{
2835
+		foreach ($this->unique_indexes() as $index_name => $index) {
2836
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2837
+			if ($this->exists(array($uniqueness_where_params))) {
2838
+				EE_Error::add_error(
2839
+					sprintf(
2840
+						__(
2841
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2842
+							"event_espresso"
2843
+						),
2844
+						$action,
2845
+						$this->_get_class_name(),
2846
+						$index_name,
2847
+						implode(",", $index->field_names()),
2848
+						http_build_query($uniqueness_where_params)
2849
+					),
2850
+					__FILE__,
2851
+					__FUNCTION__,
2852
+					__LINE__
2853
+				);
2854
+				return false;
2855
+			}
2856
+		}
2857
+		return true;
2858
+	}
2859
+
2860
+
2861
+
2862
+	/**
2863
+	 * Checks the database for an item that conflicts (ie, if this item were
2864
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2865
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2866
+	 * can be either an EE_Base_Class or an array of fields n values
2867
+	 *
2868
+	 * @param EE_Base_Class|array $obj_or_fields_array
2869
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2870
+	 *                                                 when looking for conflicts
2871
+	 *                                                 (ie, if false, we ignore the model object's primary key
2872
+	 *                                                 when finding "conflicts". If true, it's also considered).
2873
+	 *                                                 Only works for INT primary key,
2874
+	 *                                                 STRING primary keys cannot be ignored
2875
+	 * @throws EE_Error
2876
+	 * @return EE_Base_Class|array
2877
+	 */
2878
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2879
+	{
2880
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2881
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2882
+		} elseif (is_array($obj_or_fields_array)) {
2883
+			$fields_n_values = $obj_or_fields_array;
2884
+		} else {
2885
+			throw new EE_Error(
2886
+				sprintf(
2887
+					__(
2888
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2889
+						"event_espresso"
2890
+					),
2891
+					get_class($this),
2892
+					$obj_or_fields_array
2893
+				)
2894
+			);
2895
+		}
2896
+		$query_params = array();
2897
+		if ($this->has_primary_key_field()
2898
+			&& ($include_primary_key
2899
+				|| $this->get_primary_key_field()
2900
+				   instanceof
2901
+				   EE_Primary_Key_String_Field)
2902
+			&& isset($fields_n_values[$this->primary_key_name()])
2903
+		) {
2904
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2905
+		}
2906
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2909
+		}
2910
+		//if there is nothing to base this search on, then we shouldn't find anything
2911
+		if (empty($query_params)) {
2912
+			return array();
2913
+		}
2914
+		return $this->get_one($query_params);
2915
+	}
2916
+
2917
+
2918
+
2919
+	/**
2920
+	 * Like count, but is optimized and returns a boolean instead of an int
2921
+	 *
2922
+	 * @param array $query_params
2923
+	 * @return boolean
2924
+	 * @throws EE_Error
2925
+	 */
2926
+	public function exists($query_params)
2927
+	{
2928
+		$query_params['limit'] = 1;
2929
+		return $this->count($query_params) > 0;
2930
+	}
2931
+
2932
+
2933
+
2934
+	/**
2935
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2936
+	 *
2937
+	 * @param int|string $id
2938
+	 * @return boolean
2939
+	 * @throws EE_Error
2940
+	 */
2941
+	public function exists_by_ID($id)
2942
+	{
2943
+		return $this->exists(
2944
+			array(
2945
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2946
+				array(
2947
+					$this->primary_key_name() => $id,
2948
+				),
2949
+			)
2950
+		);
2951
+	}
2952
+
2953
+
2954
+
2955
+	/**
2956
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2957
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2958
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2959
+	 * on the main table)
2960
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2961
+	 * cases where we want to call it directly rather than via insert().
2962
+	 *
2963
+	 * @access   protected
2964
+	 * @param EE_Table_Base $table
2965
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2966
+	 *                                       float
2967
+	 * @param int           $new_id          for now we assume only int keys
2968
+	 * @throws EE_Error
2969
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2970
+	 * @return int ID of new row inserted, or FALSE on failure
2971
+	 */
2972
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2973
+	{
2974
+		global $wpdb;
2975
+		$insertion_col_n_values = array();
2976
+		$format_for_insertion = array();
2977
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2978
+		foreach ($fields_on_table as $field_name => $field_obj) {
2979
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2980
+			if ($field_obj->is_auto_increment()) {
2981
+				continue;
2982
+			}
2983
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2985
+			if ($prepared_value !== null) {
2986
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2987
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988
+			}
2989
+		}
2990
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2991
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2992
+			//so add the fk to the main table as a column
2993
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2994
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2995
+		}
2996
+		//insert the new entry
2997
+		$result = $this->_do_wpdb_query('insert',
2998
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2999
+		if ($result === false) {
3000
+			return false;
3001
+		}
3002
+		//ok, now what do we return for the ID of the newly-inserted thing?
3003
+		if ($this->has_primary_key_field()) {
3004
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3005
+				return $wpdb->insert_id;
3006
+			}
3007
+			//it's not an auto-increment primary key, so
3008
+			//it must have been supplied
3009
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3010
+		}
3011
+		//we can't return a  primary key because there is none. instead return
3012
+		//a unique string indicating this model
3013
+		return $this->get_index_primary_key_string($fields_n_values);
3014
+	}
3015
+
3016
+
3017
+
3018
+	/**
3019
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3020
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3021
+	 * and there is no default, we pass it along. WPDB will take care of it)
3022
+	 *
3023
+	 * @param EE_Model_Field_Base $field_obj
3024
+	 * @param array               $fields_n_values
3025
+	 * @return mixed string|int|float depending on what the table column will be expecting
3026
+	 * @throws EE_Error
3027
+	 */
3028
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3029
+	{
3030
+		//if this field doesn't allow nullable, don't allow it
3031
+		if (
3032
+			! $field_obj->is_nullable()
3033
+			&& (
3034
+				! isset($fields_n_values[$field_obj->get_name()])
3035
+				|| $fields_n_values[$field_obj->get_name()] === null
3036
+			)
3037
+		) {
3038
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3039
+		}
3040
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3041
+			? $fields_n_values[$field_obj->get_name()]
3042
+			: null;
3043
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3044
+	}
3045
+
3046
+
3047
+
3048
+	/**
3049
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3050
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3051
+	 * the field's prepare_for_set() method.
3052
+	 *
3053
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3054
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3055
+	 *                                   top of file)
3056
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3057
+	 *                                   $value is a custom selection
3058
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3059
+	 */
3060
+	private function _prepare_value_for_use_in_db($value, $field)
3061
+	{
3062
+		if ($field && $field instanceof EE_Model_Field_Base) {
3063
+			switch ($this->_values_already_prepared_by_model_object) {
3064
+				/** @noinspection PhpMissingBreakStatementInspection */
3065
+				case self::not_prepared_by_model_object:
3066
+					$value = $field->prepare_for_set($value);
3067
+				//purposefully left out "return"
3068
+				case self::prepared_by_model_object:
3069
+					/** @noinspection SuspiciousAssignmentsInspection */
3070
+					$value = $field->prepare_for_use_in_db($value);
3071
+				case self::prepared_for_use_in_db:
3072
+					//leave the value alone
3073
+			}
3074
+			return $value;
3075
+		}
3076
+		return $value;
3077
+	}
3078
+
3079
+
3080
+
3081
+	/**
3082
+	 * Returns the main table on this model
3083
+	 *
3084
+	 * @return EE_Primary_Table
3085
+	 * @throws EE_Error
3086
+	 */
3087
+	protected function _get_main_table()
3088
+	{
3089
+		foreach ($this->_tables as $table) {
3090
+			if ($table instanceof EE_Primary_Table) {
3091
+				return $table;
3092
+			}
3093
+		}
3094
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3095
+			'event_espresso'), get_class($this)));
3096
+	}
3097
+
3098
+
3099
+
3100
+	/**
3101
+	 * table
3102
+	 * returns EE_Primary_Table table name
3103
+	 *
3104
+	 * @return string
3105
+	 * @throws EE_Error
3106
+	 */
3107
+	public function table()
3108
+	{
3109
+		return $this->_get_main_table()->get_table_name();
3110
+	}
3111
+
3112
+
3113
+
3114
+	/**
3115
+	 * table
3116
+	 * returns first EE_Secondary_Table table name
3117
+	 *
3118
+	 * @return string
3119
+	 */
3120
+	public function second_table()
3121
+	{
3122
+		// grab second table from tables array
3123
+		$second_table = end($this->_tables);
3124
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * get_table_obj_by_alias
3131
+	 * returns table name given it's alias
3132
+	 *
3133
+	 * @param string $table_alias
3134
+	 * @return EE_Primary_Table | EE_Secondary_Table
3135
+	 */
3136
+	public function get_table_obj_by_alias($table_alias = '')
3137
+	{
3138
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3139
+	}
3140
+
3141
+
3142
+
3143
+	/**
3144
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3145
+	 *
3146
+	 * @return EE_Secondary_Table[]
3147
+	 */
3148
+	protected function _get_other_tables()
3149
+	{
3150
+		$other_tables = array();
3151
+		foreach ($this->_tables as $table_alias => $table) {
3152
+			if ($table instanceof EE_Secondary_Table) {
3153
+				$other_tables[$table_alias] = $table;
3154
+			}
3155
+		}
3156
+		return $other_tables;
3157
+	}
3158
+
3159
+
3160
+
3161
+	/**
3162
+	 * Finds all the fields that correspond to the given table
3163
+	 *
3164
+	 * @param string $table_alias , array key in EEM_Base::_tables
3165
+	 * @return EE_Model_Field_Base[]
3166
+	 */
3167
+	public function _get_fields_for_table($table_alias)
3168
+	{
3169
+		return $this->_fields[$table_alias];
3170
+	}
3171
+
3172
+
3173
+
3174
+	/**
3175
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3176
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3177
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3178
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3179
+	 * related Registration, Transaction, and Payment models.
3180
+	 *
3181
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3182
+	 * @return EE_Model_Query_Info_Carrier
3183
+	 * @throws EE_Error
3184
+	 */
3185
+	public function _extract_related_models_from_query($query_params)
3186
+	{
3187
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3188
+		if (array_key_exists(0, $query_params)) {
3189
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3190
+		}
3191
+		if (array_key_exists('group_by', $query_params)) {
3192
+			if (is_array($query_params['group_by'])) {
3193
+				$this->_extract_related_models_from_sub_params_array_values(
3194
+					$query_params['group_by'],
3195
+					$query_info_carrier,
3196
+					'group_by'
3197
+				);
3198
+			} elseif (! empty ($query_params['group_by'])) {
3199
+				$this->_extract_related_model_info_from_query_param(
3200
+					$query_params['group_by'],
3201
+					$query_info_carrier,
3202
+					'group_by'
3203
+				);
3204
+			}
3205
+		}
3206
+		if (array_key_exists('having', $query_params)) {
3207
+			$this->_extract_related_models_from_sub_params_array_keys(
3208
+				$query_params[0],
3209
+				$query_info_carrier,
3210
+				'having'
3211
+			);
3212
+		}
3213
+		if (array_key_exists('order_by', $query_params)) {
3214
+			if (is_array($query_params['order_by'])) {
3215
+				$this->_extract_related_models_from_sub_params_array_keys(
3216
+					$query_params['order_by'],
3217
+					$query_info_carrier,
3218
+					'order_by'
3219
+				);
3220
+			} elseif (! empty($query_params['order_by'])) {
3221
+				$this->_extract_related_model_info_from_query_param(
3222
+					$query_params['order_by'],
3223
+					$query_info_carrier,
3224
+					'order_by'
3225
+				);
3226
+			}
3227
+		}
3228
+		if (array_key_exists('force_join', $query_params)) {
3229
+			$this->_extract_related_models_from_sub_params_array_values(
3230
+				$query_params['force_join'],
3231
+				$query_info_carrier,
3232
+				'force_join'
3233
+			);
3234
+		}
3235
+		return $query_info_carrier;
3236
+	}
3237
+
3238
+
3239
+
3240
+	/**
3241
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3242
+	 *
3243
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3244
+	 *                                                      $query_params['having']
3245
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3246
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3247
+	 * @throws EE_Error
3248
+	 * @return \EE_Model_Query_Info_Carrier
3249
+	 */
3250
+	private function _extract_related_models_from_sub_params_array_keys(
3251
+		$sub_query_params,
3252
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253
+		$query_param_type
3254
+	) {
3255
+		if (! empty($sub_query_params)) {
3256
+			$sub_query_params = (array)$sub_query_params;
3257
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3260
+					$query_param_type);
3261
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3262
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3263
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3264
+				//of array('Registration.TXN_ID'=>23)
3265
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3266
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3267
+					if (! is_array($possibly_array_of_params)) {
3268
+						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'))",
3269
+							"event_espresso"),
3270
+							$param, $possibly_array_of_params));
3271
+					}
3272
+					$this->_extract_related_models_from_sub_params_array_keys(
3273
+						$possibly_array_of_params,
3274
+						$model_query_info_carrier, $query_param_type
3275
+					);
3276
+				} elseif ($query_param_type === 0 //ie WHERE
3277
+						  && is_array($possibly_array_of_params)
3278
+						  && isset($possibly_array_of_params[2])
3279
+						  && $possibly_array_of_params[2] == true
3280
+				) {
3281
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3282
+					//indicating that $possible_array_of_params[1] is actually a field name,
3283
+					//from which we should extract query parameters!
3284
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3285
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3286
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3287
+					}
3288
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3289
+						$model_query_info_carrier, $query_param_type);
3290
+				}
3291
+			}
3292
+		}
3293
+		return $model_query_info_carrier;
3294
+	}
3295
+
3296
+
3297
+
3298
+	/**
3299
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3300
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3301
+	 *
3302
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3303
+	 *                                                      $query_params['having']
3304
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3306
+	 * @throws EE_Error
3307
+	 * @return \EE_Model_Query_Info_Carrier
3308
+	 */
3309
+	private function _extract_related_models_from_sub_params_array_values(
3310
+		$sub_query_params,
3311
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
+		$query_param_type
3313
+	) {
3314
+		if (! empty($sub_query_params)) {
3315
+			if (! is_array($sub_query_params)) {
3316
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3317
+					$sub_query_params));
3318
+			}
3319
+			foreach ($sub_query_params as $param) {
3320
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3321
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3322
+					$query_param_type);
3323
+			}
3324
+		}
3325
+		return $model_query_info_carrier;
3326
+	}
3327
+
3328
+
3329
+
3330
+	/**
3331
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3332
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3333
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3334
+	 * but use them in a different order. Eg, we need to know what models we are querying
3335
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3336
+	 * other models before we can finalize the where clause SQL.
3337
+	 *
3338
+	 * @param array $query_params
3339
+	 * @throws EE_Error
3340
+	 * @return EE_Model_Query_Info_Carrier
3341
+	 */
3342
+	public function _create_model_query_info_carrier($query_params)
3343
+	{
3344
+		if (! is_array($query_params)) {
3345
+			EE_Error::doing_it_wrong(
3346
+				'EEM_Base::_create_model_query_info_carrier',
3347
+				sprintf(
3348
+					__(
3349
+						'$query_params should be an array, you passed a variable of type %s',
3350
+						'event_espresso'
3351
+					),
3352
+					gettype($query_params)
3353
+				),
3354
+				'4.6.0'
3355
+			);
3356
+			$query_params = array();
3357
+		}
3358
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3359
+		//first check if we should alter the query to account for caps or not
3360
+		//because the caps might require us to do extra joins
3361
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3362
+			$query_params[0] = $where_query_params = array_replace_recursive(
3363
+				$where_query_params,
3364
+				$this->caps_where_conditions(
3365
+					$query_params['caps']
3366
+				)
3367
+			);
3368
+		}
3369
+		$query_object = $this->_extract_related_models_from_query($query_params);
3370
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3371
+		foreach ($where_query_params as $key => $value) {
3372
+			if (is_int($key)) {
3373
+				throw new EE_Error(
3374
+					sprintf(
3375
+						__(
3376
+							"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.",
3377
+							"event_espresso"
3378
+						),
3379
+						$key,
3380
+						var_export($value, true),
3381
+						var_export($query_params, true),
3382
+						get_class($this)
3383
+					)
3384
+				);
3385
+			}
3386
+		}
3387
+		if (
3388
+			array_key_exists('default_where_conditions', $query_params)
3389
+			&& ! empty($query_params['default_where_conditions'])
3390
+		) {
3391
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3392
+		} else {
3393
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3394
+		}
3395
+		$where_query_params = array_merge(
3396
+			$this->_get_default_where_conditions_for_models_in_query(
3397
+				$query_object,
3398
+				$use_default_where_conditions,
3399
+				$where_query_params
3400
+			),
3401
+			$where_query_params
3402
+		);
3403
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3404
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3405
+		// So we need to setup a subquery and use that for the main join.
3406
+		// Note for now this only works on the primary table for the model.
3407
+		// So for instance, you could set the limit array like this:
3408
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3409
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3410
+			$query_object->set_main_model_join_sql(
3411
+				$this->_construct_limit_join_select(
3412
+					$query_params['on_join_limit'][0],
3413
+					$query_params['on_join_limit'][1]
3414
+				)
3415
+			);
3416
+		}
3417
+		//set limit
3418
+		if (array_key_exists('limit', $query_params)) {
3419
+			if (is_array($query_params['limit'])) {
3420
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3421
+					$e = sprintf(
3422
+						__(
3423
+							"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)",
3424
+							"event_espresso"
3425
+						),
3426
+						http_build_query($query_params['limit'])
3427
+					);
3428
+					throw new EE_Error($e . "|" . $e);
3429
+				}
3430
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3431
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3432
+			} elseif (! empty ($query_params['limit'])) {
3433
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3434
+			}
3435
+		}
3436
+		//set order by
3437
+		if (array_key_exists('order_by', $query_params)) {
3438
+			if (is_array($query_params['order_by'])) {
3439
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3440
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3441
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3442
+				if (array_key_exists('order', $query_params)) {
3443
+					throw new EE_Error(
3444
+						sprintf(
3445
+							__(
3446
+								"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 ",
3447
+								"event_espresso"
3448
+							),
3449
+							get_class($this),
3450
+							implode(", ", array_keys($query_params['order_by'])),
3451
+							implode(", ", $query_params['order_by']),
3452
+							$query_params['order']
3453
+						)
3454
+					);
3455
+				}
3456
+				$this->_extract_related_models_from_sub_params_array_keys(
3457
+					$query_params['order_by'],
3458
+					$query_object,
3459
+					'order_by'
3460
+				);
3461
+				//assume it's an array of fields to order by
3462
+				$order_array = array();
3463
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3464
+					$order = $this->_extract_order($order);
3465
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3466
+				}
3467
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3468
+			} elseif (! empty ($query_params['order_by'])) {
3469
+				$this->_extract_related_model_info_from_query_param(
3470
+					$query_params['order_by'],
3471
+					$query_object,
3472
+					'order',
3473
+					$query_params['order_by']
3474
+				);
3475
+				$order = isset($query_params['order'])
3476
+					? $this->_extract_order($query_params['order'])
3477
+					: 'DESC';
3478
+				$query_object->set_order_by_sql(
3479
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3480
+				);
3481
+			}
3482
+		}
3483
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3484
+		if (! array_key_exists('order_by', $query_params)
3485
+			&& array_key_exists('order', $query_params)
3486
+			&& ! empty($query_params['order'])
3487
+		) {
3488
+			$pk_field = $this->get_primary_key_field();
3489
+			$order = $this->_extract_order($query_params['order']);
3490
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3491
+		}
3492
+		//set group by
3493
+		if (array_key_exists('group_by', $query_params)) {
3494
+			if (is_array($query_params['group_by'])) {
3495
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3496
+				$group_by_array = array();
3497
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3498
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3499
+				}
3500
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3501
+			} elseif (! empty ($query_params['group_by'])) {
3502
+				$query_object->set_group_by_sql(
3503
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3504
+				);
3505
+			}
3506
+		}
3507
+		//set having
3508
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3509
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3510
+		}
3511
+		//now, just verify they didn't pass anything wack
3512
+		foreach ($query_params as $query_key => $query_value) {
3513
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3514
+				throw new EE_Error(
3515
+					sprintf(
3516
+						__(
3517
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3518
+							'event_espresso'
3519
+						),
3520
+						$query_key,
3521
+						get_class($this),
3522
+						//						print_r( $this->_allowed_query_params, TRUE )
3523
+						implode(',', $this->_allowed_query_params)
3524
+					)
3525
+				);
3526
+			}
3527
+		}
3528
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3529
+		if (empty($main_model_join_sql)) {
3530
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3531
+		}
3532
+		return $query_object;
3533
+	}
3534
+
3535
+
3536
+
3537
+	/**
3538
+	 * Gets the where conditions that should be imposed on the query based on the
3539
+	 * context (eg reading frontend, backend, edit or delete).
3540
+	 *
3541
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3542
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3543
+	 * @throws EE_Error
3544
+	 */
3545
+	public function caps_where_conditions($context = self::caps_read)
3546
+	{
3547
+		EEM_Base::verify_is_valid_cap_context($context);
3548
+		$cap_where_conditions = array();
3549
+		$cap_restrictions = $this->caps_missing($context);
3550
+		/**
3551
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3552
+		 */
3553
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3554
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3555
+				$restriction_if_no_cap->get_default_where_conditions());
3556
+		}
3557
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3558
+			$cap_restrictions);
3559
+	}
3560
+
3561
+
3562
+
3563
+	/**
3564
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3565
+	 * otherwise throws an exception
3566
+	 *
3567
+	 * @param string $should_be_order_string
3568
+	 * @return string either ASC, asc, DESC or desc
3569
+	 * @throws EE_Error
3570
+	 */
3571
+	private function _extract_order($should_be_order_string)
3572
+	{
3573
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3574
+			return $should_be_order_string;
3575
+		}
3576
+		throw new EE_Error(
3577
+			sprintf(
3578
+				__(
3579
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3580
+					"event_espresso"
3581
+				), get_class($this), $should_be_order_string
3582
+			)
3583
+		);
3584
+	}
3585
+
3586
+
3587
+
3588
+	/**
3589
+	 * Looks at all the models which are included in this query, and asks each
3590
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3591
+	 * so they can be merged
3592
+	 *
3593
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3594
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3595
+	 *                                                                  'none' means NO default where conditions will
3596
+	 *                                                                  be used AT ALL during this query.
3597
+	 *                                                                  'other_models_only' means default where
3598
+	 *                                                                  conditions from other models will be used, but
3599
+	 *                                                                  not for this primary model. 'all', the default,
3600
+	 *                                                                  means default where conditions will apply as
3601
+	 *                                                                  normal
3602
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3603
+	 * @throws EE_Error
3604
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3605
+	 */
3606
+	private function _get_default_where_conditions_for_models_in_query(
3607
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3608
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3609
+		$where_query_params = array()
3610
+	) {
3611
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3612
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3613
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3614
+				"event_espresso"), $use_default_where_conditions,
3615
+				implode(", ", $allowed_used_default_where_conditions_values)));
3616
+		}
3617
+		$universal_query_params = array();
3618
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3619
+			$universal_query_params = $this->_get_default_where_conditions();
3620
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3621
+			$universal_query_params = $this->_get_minimum_where_conditions();
3622
+		}
3623
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3624
+			$related_model = $this->get_related_model_obj($model_name);
3625
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3626
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3627
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3628
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3629
+			} else {
3630
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3631
+				continue;
3632
+			}
3633
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3634
+				$related_model_universal_where_params,
3635
+				$where_query_params,
3636
+				$related_model,
3637
+				$model_relation_path
3638
+			);
3639
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3640
+				$universal_query_params,
3641
+				$overrides
3642
+			);
3643
+		}
3644
+		return $universal_query_params;
3645
+	}
3646
+
3647
+
3648
+
3649
+	/**
3650
+	 * Determines whether or not we should use default where conditions for the model in question
3651
+	 * (this model, or other related models).
3652
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3653
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3654
+	 * We should use default where conditions on related models when they requested to use default where conditions
3655
+	 * on all models, or specifically just on other related models
3656
+	 * @param      $default_where_conditions_value
3657
+	 * @param bool $for_this_model false means this is for OTHER related models
3658
+	 * @return bool
3659
+	 */
3660
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3661
+	{
3662
+		return (
3663
+				   $for_this_model
3664
+				   && in_array(
3665
+					   $default_where_conditions_value,
3666
+					   array(
3667
+						   EEM_Base::default_where_conditions_all,
3668
+						   EEM_Base::default_where_conditions_this_only,
3669
+						   EEM_Base::default_where_conditions_minimum_others,
3670
+					   ),
3671
+					   true
3672
+				   )
3673
+			   )
3674
+			   || (
3675
+				   ! $for_this_model
3676
+				   && in_array(
3677
+					   $default_where_conditions_value,
3678
+					   array(
3679
+						   EEM_Base::default_where_conditions_all,
3680
+						   EEM_Base::default_where_conditions_others_only,
3681
+					   ),
3682
+					   true
3683
+				   )
3684
+			   );
3685
+	}
3686
+
3687
+	/**
3688
+	 * Determines whether or not we should use default minimum conditions for the model in question
3689
+	 * (this model, or other related models).
3690
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3691
+	 * where conditions.
3692
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3693
+	 * on this model or others
3694
+	 * @param      $default_where_conditions_value
3695
+	 * @param bool $for_this_model false means this is for OTHER related models
3696
+	 * @return bool
3697
+	 */
3698
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3699
+	{
3700
+		return (
3701
+				   $for_this_model
3702
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3703
+			   )
3704
+			   || (
3705
+				   ! $for_this_model
3706
+				   && in_array(
3707
+					   $default_where_conditions_value,
3708
+					   array(
3709
+						   EEM_Base::default_where_conditions_minimum_others,
3710
+						   EEM_Base::default_where_conditions_minimum_all,
3711
+					   ),
3712
+					   true
3713
+				   )
3714
+			   );
3715
+	}
3716
+
3717
+
3718
+	/**
3719
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3720
+	 * then we also add a special where condition which allows for that model's primary key
3721
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3722
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3723
+	 *
3724
+	 * @param array    $default_where_conditions
3725
+	 * @param array    $provided_where_conditions
3726
+	 * @param EEM_Base $model
3727
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3728
+	 * @return array like EEM_Base::get_all's $query_params[0]
3729
+	 * @throws EE_Error
3730
+	 */
3731
+	private function _override_defaults_or_make_null_friendly(
3732
+		$default_where_conditions,
3733
+		$provided_where_conditions,
3734
+		$model,
3735
+		$model_relation_path
3736
+	) {
3737
+		$null_friendly_where_conditions = array();
3738
+		$none_overridden = true;
3739
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3740
+		foreach ($default_where_conditions as $key => $val) {
3741
+			if (isset($provided_where_conditions[$key])) {
3742
+				$none_overridden = false;
3743
+			} else {
3744
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3745
+			}
3746
+		}
3747
+		if ($none_overridden && $default_where_conditions) {
3748
+			if ($model->has_primary_key_field()) {
3749
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3750
+																				. "."
3751
+																				. $model->primary_key_name()] = array('IS NULL');
3752
+			}/*else{
3753 3753
 				//@todo NO PK, use other defaults
3754 3754
 			}*/
3755
-        }
3756
-        return $null_friendly_where_conditions;
3757
-    }
3758
-
3759
-
3760
-
3761
-    /**
3762
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3763
-     * default where conditions on all get_all, update, and delete queries done by this model.
3764
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3765
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3766
-     *
3767
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3768
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3769
-     */
3770
-    private function _get_default_where_conditions($model_relation_path = null)
3771
-    {
3772
-        if ($this->_ignore_where_strategy) {
3773
-            return array();
3774
-        }
3775
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3776
-    }
3777
-
3778
-
3779
-
3780
-    /**
3781
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3782
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3783
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3785
-     * Similar to _get_default_where_conditions
3786
-     *
3787
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3788
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3789
-     */
3790
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3791
-    {
3792
-        if ($this->_ignore_where_strategy) {
3793
-            return array();
3794
-        }
3795
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3796
-    }
3797
-
3798
-
3799
-
3800
-    /**
3801
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3802
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3803
-     *
3804
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3805
-     * @return string
3806
-     * @throws EE_Error
3807
-     */
3808
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3809
-    {
3810
-        $selects = $this->_get_columns_to_select_for_this_model();
3811
-        foreach (
3812
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3813
-            $name_of_other_model_included
3814
-        ) {
3815
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3816
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3817
-            foreach ($other_model_selects as $key => $value) {
3818
-                $selects[] = $value;
3819
-            }
3820
-        }
3821
-        return implode(", ", $selects);
3822
-    }
3823
-
3824
-
3825
-
3826
-    /**
3827
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3828
-     * So that's going to be the columns for all the fields on the model
3829
-     *
3830
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3831
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3832
-     */
3833
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3834
-    {
3835
-        $fields = $this->field_settings();
3836
-        $selects = array();
3837
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3838
-            $this->get_this_model_name());
3839
-        foreach ($fields as $field_obj) {
3840
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3841
-                         . $field_obj->get_table_alias()
3842
-                         . "."
3843
-                         . $field_obj->get_table_column()
3844
-                         . " AS '"
3845
-                         . $table_alias_with_model_relation_chain_prefix
3846
-                         . $field_obj->get_table_alias()
3847
-                         . "."
3848
-                         . $field_obj->get_table_column()
3849
-                         . "'";
3850
-        }
3851
-        //make sure we are also getting the PKs of each table
3852
-        $tables = $this->get_tables();
3853
-        if (count($tables) > 1) {
3854
-            foreach ($tables as $table_obj) {
3855
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3856
-                                       . $table_obj->get_fully_qualified_pk_column();
3857
-                if (! in_array($qualified_pk_column, $selects)) {
3858
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3859
-                }
3860
-            }
3861
-        }
3862
-        return $selects;
3863
-    }
3864
-
3865
-
3866
-
3867
-    /**
3868
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3869
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3870
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3871
-     * SQL for joining, and the data types
3872
-     *
3873
-     * @param null|string                 $original_query_param
3874
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3875
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3876
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3877
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3878
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3879
-     *                                                          or 'Registration's
3880
-     * @param string                      $original_query_param what it originally was (eg
3881
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3882
-     *                                                          matches $query_param
3883
-     * @throws EE_Error
3884
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3885
-     */
3886
-    private function _extract_related_model_info_from_query_param(
3887
-        $query_param,
3888
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3889
-        $query_param_type,
3890
-        $original_query_param = null
3891
-    ) {
3892
-        if ($original_query_param === null) {
3893
-            $original_query_param = $query_param;
3894
-        }
3895
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3896
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3897
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3898
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3899
-        //check to see if we have a field on this model
3900
-        $this_model_fields = $this->field_settings(true);
3901
-        if (array_key_exists($query_param, $this_model_fields)) {
3902
-            if ($allow_fields) {
3903
-                return;
3904
-            }
3905
-            throw new EE_Error(
3906
-                sprintf(
3907
-                    __(
3908
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3909
-                        "event_espresso"
3910
-                    ),
3911
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3912
-                )
3913
-            );
3914
-        }
3915
-        //check if this is a special logic query param
3916
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3917
-            if ($allow_logic_query_params) {
3918
-                return;
3919
-            }
3920
-            throw new EE_Error(
3921
-                sprintf(
3922
-                    __(
3923
-                        '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',
3924
-                        'event_espresso'
3925
-                    ),
3926
-                    implode('", "', $this->_logic_query_param_keys),
3927
-                    $query_param,
3928
-                    get_class($this),
3929
-                    '<br />',
3930
-                    "\t"
3931
-                    . ' $passed_in_query_info = <pre>'
3932
-                    . print_r($passed_in_query_info, true)
3933
-                    . '</pre>'
3934
-                    . "\n\t"
3935
-                    . ' $query_param_type = '
3936
-                    . $query_param_type
3937
-                    . "\n\t"
3938
-                    . ' $original_query_param = '
3939
-                    . $original_query_param
3940
-                )
3941
-            );
3942
-        }
3943
-        //check if it's a custom selection
3944
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3945
-            return;
3946
-        }
3947
-        //check if has a model name at the beginning
3948
-        //and
3949
-        //check if it's a field on a related model
3950
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3951
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3952
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3953
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3954
-                if ($query_param === '') {
3955
-                    //nothing left to $query_param
3956
-                    //we should actually end in a field name, not a model like this!
3957
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3958
-                        "event_espresso"),
3959
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3960
-                }
3961
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3962
-                $related_model_obj->_extract_related_model_info_from_query_param(
3963
-                    $query_param,
3964
-                    $passed_in_query_info, $query_param_type, $original_query_param
3965
-                );
3966
-                return;
3967
-            }
3968
-            if ($query_param === $valid_related_model_name) {
3969
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3970
-                return;
3971
-            }
3972
-        }
3973
-        //ok so $query_param didn't start with a model name
3974
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3975
-        //it's wack, that's what it is
3976
-        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",
3977
-            "event_espresso"),
3978
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3979
-    }
3980
-
3981
-
3982
-
3983
-    /**
3984
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3985
-     * and store it on $passed_in_query_info
3986
-     *
3987
-     * @param string                      $model_name
3988
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3990
-     *                                                          model and $model_name. Eg, if we are querying Event,
3991
-     *                                                          and are adding a join to 'Payment' with the original
3992
-     *                                                          query param key
3993
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3994
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3995
-     *                                                          Payment wants to add default query params so that it
3996
-     *                                                          will know what models to prepend onto its default query
3997
-     *                                                          params or in case it wants to rename tables (in case
3998
-     *                                                          there are multiple joins to the same table)
3999
-     * @return void
4000
-     * @throws EE_Error
4001
-     */
4002
-    private function _add_join_to_model(
4003
-        $model_name,
4004
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4005
-        $original_query_param
4006
-    ) {
4007
-        $relation_obj = $this->related_settings_for($model_name);
4008
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4009
-        //check if the relation is HABTM, because then we're essentially doing two joins
4010
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4011
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4012
-            $join_model_obj = $relation_obj->get_join_model();
4013
-            //replace the model specified with the join model for this relation chain, whi
4014
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4015
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4016
-            $passed_in_query_info->merge(
4017
-                new EE_Model_Query_Info_Carrier(
4018
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4019
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4020
-                )
4021
-            );
4022
-        }
4023
-        //now just join to the other table pointed to by the relation object, and add its data types
4024
-        $passed_in_query_info->merge(
4025
-            new EE_Model_Query_Info_Carrier(
4026
-                array($model_relation_chain => $model_name),
4027
-                $relation_obj->get_join_statement($model_relation_chain)
4028
-            )
4029
-        );
4030
-    }
4031
-
4032
-
4033
-
4034
-    /**
4035
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4036
-     *
4037
-     * @param array $where_params like EEM_Base::get_all
4038
-     * @return string of SQL
4039
-     * @throws EE_Error
4040
-     */
4041
-    private function _construct_where_clause($where_params)
4042
-    {
4043
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4044
-        if ($SQL) {
4045
-            return " WHERE " . $SQL;
4046
-        }
4047
-        return '';
4048
-    }
4049
-
4050
-
4051
-
4052
-    /**
4053
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4054
-     * and should be passed HAVING parameters, not WHERE parameters
4055
-     *
4056
-     * @param array $having_params
4057
-     * @return string
4058
-     * @throws EE_Error
4059
-     */
4060
-    private function _construct_having_clause($having_params)
4061
-    {
4062
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4063
-        if ($SQL) {
4064
-            return " HAVING " . $SQL;
4065
-        }
4066
-        return '';
4067
-    }
4068
-
4069
-
4070
-    /**
4071
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4072
-     * Event_Meta.meta_value = 'foo'))"
4073
-     *
4074
-     * @param array  $where_params see EEM_Base::get_all for documentation
4075
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4076
-     * @throws EE_Error
4077
-     * @return string of SQL
4078
-     */
4079
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4080
-    {
4081
-        $where_clauses = array();
4082
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4083
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4084
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4085
-                switch ($query_param) {
4086
-                    case 'not':
4087
-                    case 'NOT':
4088
-                        $where_clauses[] = "! ("
4089
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4090
-                                $glue)
4091
-                                           . ")";
4092
-                        break;
4093
-                    case 'and':
4094
-                    case 'AND':
4095
-                        $where_clauses[] = " ("
4096
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4097
-                                ' AND ')
4098
-                                           . ")";
4099
-                        break;
4100
-                    case 'or':
4101
-                    case 'OR':
4102
-                        $where_clauses[] = " ("
4103
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4104
-                                ' OR ')
4105
-                                           . ")";
4106
-                        break;
4107
-                }
4108
-            } else {
4109
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4110
-                //if it's not a normal field, maybe it's a custom selection?
4111
-                if (! $field_obj) {
4112
-                    if (isset($this->_custom_selections[$query_param][1])) {
4113
-                        $field_obj = $this->_custom_selections[$query_param][1];
4114
-                    } else {
4115
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4116
-                            "event_espresso"), $query_param));
4117
-                    }
4118
-                }
4119
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4120
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4121
-            }
4122
-        }
4123
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4124
-    }
4125
-
4126
-
4127
-
4128
-    /**
4129
-     * Takes the input parameter and extract the table name (alias) and column name
4130
-     *
4131
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4132
-     * @throws EE_Error
4133
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4134
-     */
4135
-    private function _deduce_column_name_from_query_param($query_param)
4136
-    {
4137
-        $field = $this->_deduce_field_from_query_param($query_param);
4138
-        if ($field) {
4139
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4140
-                $query_param);
4141
-            return $table_alias_prefix . $field->get_qualified_column();
4142
-        }
4143
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4144
-            //maybe it's custom selection item?
4145
-            //if so, just use it as the "column name"
4146
-            return $query_param;
4147
-        }
4148
-        throw new EE_Error(
4149
-            sprintf(
4150
-                __(
4151
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4152
-                    "event_espresso"
4153
-                ), $query_param, implode(",", $this->_custom_selections)
4154
-            )
4155
-        );
4156
-    }
4157
-
4158
-
4159
-
4160
-    /**
4161
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4162
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4163
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4164
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4165
-     *
4166
-     * @param string $condition_query_param_key
4167
-     * @return string
4168
-     */
4169
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4170
-    {
4171
-        $pos_of_star = strpos($condition_query_param_key, '*');
4172
-        if ($pos_of_star === false) {
4173
-            return $condition_query_param_key;
4174
-        }
4175
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4176
-        return $condition_query_param_sans_star;
4177
-    }
4178
-
4179
-
4180
-
4181
-    /**
4182
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4183
-     *
4184
-     * @param                            mixed      array | string    $op_and_value
4185
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4186
-     * @throws EE_Error
4187
-     * @return string
4188
-     */
4189
-    private function _construct_op_and_value($op_and_value, $field_obj)
4190
-    {
4191
-        if (is_array($op_and_value)) {
4192
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4193
-            if (! $operator) {
4194
-                $php_array_like_string = array();
4195
-                foreach ($op_and_value as $key => $value) {
4196
-                    $php_array_like_string[] = "$key=>$value";
4197
-                }
4198
-                throw new EE_Error(
4199
-                    sprintf(
4200
-                        __(
4201
-                            "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))",
4202
-                            "event_espresso"
4203
-                        ),
4204
-                        implode(",", $php_array_like_string)
4205
-                    )
4206
-                );
4207
-            }
4208
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4209
-        } else {
4210
-            $operator = '=';
4211
-            $value = $op_and_value;
4212
-        }
4213
-        //check to see if the value is actually another field
4214
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4215
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4216
-        }
4217
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4218
-            //in this case, the value should be an array, or at least a comma-separated list
4219
-            //it will need to handle a little differently
4220
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4221
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4222
-            return $operator . SP . $cleaned_value;
4223
-        }
4224
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4225
-            //the value should be an array with count of two.
4226
-            if (count($value) !== 2) {
4227
-                throw new EE_Error(
4228
-                    sprintf(
4229
-                        __(
4230
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4231
-                            'event_espresso'
4232
-                        ),
4233
-                        "BETWEEN"
4234
-                    )
4235
-                );
4236
-            }
4237
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4238
-            return $operator . SP . $cleaned_value;
4239
-        }
4240
-        if (in_array($operator, $this->valid_null_style_operators())) {
4241
-            if ($value !== null) {
4242
-                throw new EE_Error(
4243
-                    sprintf(
4244
-                        __(
4245
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4246
-                            "event_espresso"
4247
-                        ),
4248
-                        $value,
4249
-                        $operator
4250
-                    )
4251
-                );
4252
-            }
4253
-            return $operator;
4254
-        }
4255
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4256
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4257
-            //remove other junk. So just treat it as a string.
4258
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4259
-        }
4260
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4261
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4262
-        }
4263
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4264
-            throw new EE_Error(
4265
-                sprintf(
4266
-                    __(
4267
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4268
-                        'event_espresso'
4269
-                    ),
4270
-                    $operator,
4271
-                    $operator
4272
-                )
4273
-            );
4274
-        }
4275
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4276
-            throw new EE_Error(
4277
-                sprintf(
4278
-                    __(
4279
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4280
-                        'event_espresso'
4281
-                    ),
4282
-                    $operator,
4283
-                    $operator
4284
-                )
4285
-            );
4286
-        }
4287
-        throw new EE_Error(
4288
-            sprintf(
4289
-                __(
4290
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4291
-                    "event_espresso"
4292
-                ),
4293
-                http_build_query($op_and_value)
4294
-            )
4295
-        );
4296
-    }
4297
-
4298
-
4299
-
4300
-    /**
4301
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4302
-     *
4303
-     * @param array                      $values
4304
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4305
-     *                                              '%s'
4306
-     * @return string
4307
-     * @throws EE_Error
4308
-     */
4309
-    public function _construct_between_value($values, $field_obj)
4310
-    {
4311
-        $cleaned_values = array();
4312
-        foreach ($values as $value) {
4313
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4314
-        }
4315
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4316
-    }
4317
-
4318
-
4319
-
4320
-    /**
4321
-     * Takes an array or a comma-separated list of $values and cleans them
4322
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4323
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4324
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4325
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4326
-     *
4327
-     * @param mixed                      $values    array or comma-separated string
4328
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4329
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4330
-     * @throws EE_Error
4331
-     */
4332
-    public function _construct_in_value($values, $field_obj)
4333
-    {
4334
-        //check if the value is a CSV list
4335
-        if (is_string($values)) {
4336
-            //in which case, turn it into an array
4337
-            $values = explode(",", $values);
4338
-        }
4339
-        $cleaned_values = array();
4340
-        foreach ($values as $value) {
4341
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4342
-        }
4343
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4344
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4345
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4346
-        if (empty($cleaned_values)) {
4347
-            $all_fields = $this->field_settings();
4348
-            $a_field = array_shift($all_fields);
4349
-            $main_table = $this->_get_main_table();
4350
-            $cleaned_values[] = "SELECT "
4351
-                                . $a_field->get_table_column()
4352
-                                . " FROM "
4353
-                                . $main_table->get_table_name()
4354
-                                . " WHERE FALSE";
4355
-        }
4356
-        return "(" . implode(",", $cleaned_values) . ")";
4357
-    }
4358
-
4359
-
4360
-
4361
-    /**
4362
-     * @param mixed                      $value
4363
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4364
-     * @throws EE_Error
4365
-     * @return false|null|string
4366
-     */
4367
-    private function _wpdb_prepare_using_field($value, $field_obj)
4368
-    {
4369
-        /** @type WPDB $wpdb */
4370
-        global $wpdb;
4371
-        if ($field_obj instanceof EE_Model_Field_Base) {
4372
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4373
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4374
-        } //$field_obj should really just be a data type
4375
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4376
-            throw new EE_Error(
4377
-                sprintf(
4378
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4379
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4380
-                )
4381
-            );
4382
-        }
4383
-        return $wpdb->prepare($field_obj, $value);
4384
-    }
4385
-
4386
-
4387
-
4388
-    /**
4389
-     * Takes the input parameter and finds the model field that it indicates.
4390
-     *
4391
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4392
-     * @throws EE_Error
4393
-     * @return EE_Model_Field_Base
4394
-     */
4395
-    protected function _deduce_field_from_query_param($query_param_name)
4396
-    {
4397
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4398
-        //which will help us find the database table and column
4399
-        $query_param_parts = explode(".", $query_param_name);
4400
-        if (empty($query_param_parts)) {
4401
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4402
-                'event_espresso'), $query_param_name));
4403
-        }
4404
-        $number_of_parts = count($query_param_parts);
4405
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4406
-        if ($number_of_parts === 1) {
4407
-            $field_name = $last_query_param_part;
4408
-            $model_obj = $this;
4409
-        } else {// $number_of_parts >= 2
4410
-            //the last part is the column name, and there are only 2parts. therefore...
4411
-            $field_name = $last_query_param_part;
4412
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4413
-        }
4414
-        try {
4415
-            return $model_obj->field_settings_for($field_name);
4416
-        } catch (EE_Error $e) {
4417
-            return null;
4418
-        }
4419
-    }
4420
-
4421
-
4422
-
4423
-    /**
4424
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4425
-     * alias and column which corresponds to it
4426
-     *
4427
-     * @param string $field_name
4428
-     * @throws EE_Error
4429
-     * @return string
4430
-     */
4431
-    public function _get_qualified_column_for_field($field_name)
4432
-    {
4433
-        $all_fields = $this->field_settings();
4434
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4435
-        if ($field) {
4436
-            return $field->get_qualified_column();
4437
-        }
4438
-        throw new EE_Error(
4439
-            sprintf(
4440
-                __(
4441
-                    "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.",
4442
-                    'event_espresso'
4443
-                ), $field_name, get_class($this)
4444
-            )
4445
-        );
4446
-    }
4447
-
4448
-
4449
-
4450
-    /**
4451
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4452
-     * Example usage:
4453
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4454
-     *      array(),
4455
-     *      ARRAY_A,
4456
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4457
-     *  );
4458
-     * is equivalent to
4459
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4460
-     * and
4461
-     *  EEM_Event::instance()->get_all_wpdb_results(
4462
-     *      array(
4463
-     *          array(
4464
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4465
-     *          ),
4466
-     *          ARRAY_A,
4467
-     *          implode(
4468
-     *              ', ',
4469
-     *              array_merge(
4470
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4471
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4472
-     *              )
4473
-     *          )
4474
-     *      )
4475
-     *  );
4476
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4477
-     *
4478
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4479
-     *                                            and the one whose fields you are selecting for example: when querying
4480
-     *                                            tickets model and selecting fields from the tickets model you would
4481
-     *                                            leave this parameter empty, because no models are needed to join
4482
-     *                                            between the queried model and the selected one. Likewise when
4483
-     *                                            querying the datetime model and selecting fields from the tickets
4484
-     *                                            model, it would also be left empty, because there is a direct
4485
-     *                                            relation from datetimes to tickets, so no model is needed to join
4486
-     *                                            them together. However, when querying from the event model and
4487
-     *                                            selecting fields from the ticket model, you should provide the string
4488
-     *                                            'Datetime', indicating that the event model must first join to the
4489
-     *                                            datetime model in order to find its relation to ticket model.
4490
-     *                                            Also, when querying from the venue model and selecting fields from
4491
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4492
-     *                                            indicating you need to join the venue model to the event model,
4493
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4494
-     *                                            This string is used to deduce the prefix that gets added onto the
4495
-     *                                            models' tables qualified columns
4496
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4497
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4498
-     *                                            qualified column names
4499
-     * @return array|string
4500
-     */
4501
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4502
-    {
4503
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4504
-        $qualified_columns = array();
4505
-        foreach ($this->field_settings() as $field_name => $field) {
4506
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4507
-        }
4508
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4509
-    }
4510
-
4511
-
4512
-
4513
-    /**
4514
-     * constructs the select use on special limit joins
4515
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4516
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4517
-     * (as that is typically where the limits would be set).
4518
-     *
4519
-     * @param  string       $table_alias The table the select is being built for
4520
-     * @param  mixed|string $limit       The limit for this select
4521
-     * @return string                The final select join element for the query.
4522
-     */
4523
-    public function _construct_limit_join_select($table_alias, $limit)
4524
-    {
4525
-        $SQL = '';
4526
-        foreach ($this->_tables as $table_obj) {
4527
-            if ($table_obj instanceof EE_Primary_Table) {
4528
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4529
-                    ? $table_obj->get_select_join_limit($limit)
4530
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4531
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4532
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4533
-                    ? $table_obj->get_select_join_limit_join($limit)
4534
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4535
-            }
4536
-        }
4537
-        return $SQL;
4538
-    }
4539
-
4540
-
4541
-
4542
-    /**
4543
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4544
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4545
-     *
4546
-     * @return string SQL
4547
-     * @throws EE_Error
4548
-     */
4549
-    public function _construct_internal_join()
4550
-    {
4551
-        $SQL = $this->_get_main_table()->get_table_sql();
4552
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4553
-        return $SQL;
4554
-    }
4555
-
4556
-
4557
-
4558
-    /**
4559
-     * Constructs the SQL for joining all the tables on this model.
4560
-     * Normally $alias should be the primary table's alias, but in cases where
4561
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4562
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4563
-     * alias, this will construct SQL like:
4564
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4565
-     * With $alias being a secondary table's alias, this will construct SQL like:
4566
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4567
-     *
4568
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4569
-     * @return string
4570
-     */
4571
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4572
-    {
4573
-        $SQL = '';
4574
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4575
-        foreach ($this->_tables as $table_obj) {
4576
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4577
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4578
-                    //so we're joining to this table, meaning the table is already in
4579
-                    //the FROM statement, BUT the primary table isn't. So we want
4580
-                    //to add the inverse join sql
4581
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4582
-                } else {
4583
-                    //just add a regular JOIN to this table from the primary table
4584
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4585
-                }
4586
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4587
-        }
4588
-        return $SQL;
4589
-    }
4590
-
4591
-
4592
-
4593
-    /**
4594
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4595
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4596
-     * their data type (eg, '%s', '%d', etc)
4597
-     *
4598
-     * @return array
4599
-     */
4600
-    public function _get_data_types()
4601
-    {
4602
-        $data_types = array();
4603
-        foreach ($this->field_settings() as $field_obj) {
4604
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4605
-            /** @var $field_obj EE_Model_Field_Base */
4606
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4607
-        }
4608
-        return $data_types;
4609
-    }
4610
-
4611
-
4612
-
4613
-    /**
4614
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4615
-     *
4616
-     * @param string $model_name
4617
-     * @throws EE_Error
4618
-     * @return EEM_Base
4619
-     */
4620
-    public function get_related_model_obj($model_name)
4621
-    {
4622
-        $model_classname = "EEM_" . $model_name;
4623
-        if (! class_exists($model_classname)) {
4624
-            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",
4625
-                'event_espresso'), $model_name, $model_classname));
4626
-        }
4627
-        return call_user_func($model_classname . "::instance");
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * Returns the array of EE_ModelRelations for this model.
4634
-     *
4635
-     * @return EE_Model_Relation_Base[]
4636
-     */
4637
-    public function relation_settings()
4638
-    {
4639
-        return $this->_model_relations;
4640
-    }
4641
-
4642
-
4643
-
4644
-    /**
4645
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4646
-     * because without THOSE models, this model probably doesn't have much purpose.
4647
-     * (Eg, without an event, datetimes have little purpose.)
4648
-     *
4649
-     * @return EE_Belongs_To_Relation[]
4650
-     */
4651
-    public function belongs_to_relations()
4652
-    {
4653
-        $belongs_to_relations = array();
4654
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4655
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4656
-                $belongs_to_relations[$model_name] = $relation_obj;
4657
-            }
4658
-        }
4659
-        return $belongs_to_relations;
4660
-    }
4661
-
4662
-
4663
-
4664
-    /**
4665
-     * Returns the specified EE_Model_Relation, or throws an exception
4666
-     *
4667
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4668
-     * @throws EE_Error
4669
-     * @return EE_Model_Relation_Base
4670
-     */
4671
-    public function related_settings_for($relation_name)
4672
-    {
4673
-        $relatedModels = $this->relation_settings();
4674
-        if (! array_key_exists($relation_name, $relatedModels)) {
4675
-            throw new EE_Error(
4676
-                sprintf(
4677
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4678
-                        'event_espresso'),
4679
-                    $relation_name,
4680
-                    $this->_get_class_name(),
4681
-                    implode(', ', array_keys($relatedModels))
4682
-                )
4683
-            );
4684
-        }
4685
-        return $relatedModels[$relation_name];
4686
-    }
4687
-
4688
-
4689
-
4690
-    /**
4691
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4692
-     * fields
4693
-     *
4694
-     * @param string $fieldName
4695
-     * @param boolean $include_db_only_fields
4696
-     * @throws EE_Error
4697
-     * @return EE_Model_Field_Base
4698
-     */
4699
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4700
-    {
4701
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4702
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4703
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4704
-                get_class($this)));
4705
-        }
4706
-        return $fieldSettings[$fieldName];
4707
-    }
4708
-
4709
-
4710
-
4711
-    /**
4712
-     * Checks if this field exists on this model
4713
-     *
4714
-     * @param string $fieldName a key in the model's _field_settings array
4715
-     * @return boolean
4716
-     */
4717
-    public function has_field($fieldName)
4718
-    {
4719
-        $fieldSettings = $this->field_settings(true);
4720
-        if (isset($fieldSettings[$fieldName])) {
4721
-            return true;
4722
-        }
4723
-        return false;
4724
-    }
4725
-
4726
-
4727
-
4728
-    /**
4729
-     * Returns whether or not this model has a relation to the specified model
4730
-     *
4731
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4732
-     * @return boolean
4733
-     */
4734
-    public function has_relation($relation_name)
4735
-    {
4736
-        $relations = $this->relation_settings();
4737
-        if (isset($relations[$relation_name])) {
4738
-            return true;
4739
-        }
4740
-        return false;
4741
-    }
4742
-
4743
-
4744
-
4745
-    /**
4746
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747
-     * Eg, on EE_Answer that would be ANS_ID field object
4748
-     *
4749
-     * @param $field_obj
4750
-     * @return boolean
4751
-     */
4752
-    public function is_primary_key_field($field_obj)
4753
-    {
4754
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4761
-     * Eg, on EE_Answer that would be ANS_ID field object
4762
-     *
4763
-     * @return EE_Model_Field_Base
4764
-     * @throws EE_Error
4765
-     */
4766
-    public function get_primary_key_field()
4767
-    {
4768
-        if ($this->_primary_key_field === null) {
4769
-            foreach ($this->field_settings(true) as $field_obj) {
4770
-                if ($this->is_primary_key_field($field_obj)) {
4771
-                    $this->_primary_key_field = $field_obj;
4772
-                    break;
4773
-                }
4774
-            }
4775
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4776
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4777
-                    get_class($this)));
4778
-            }
4779
-        }
4780
-        return $this->_primary_key_field;
4781
-    }
4782
-
4783
-
4784
-
4785
-    /**
4786
-     * Returns whether or not not there is a primary key on this model.
4787
-     * Internally does some caching.
4788
-     *
4789
-     * @return boolean
4790
-     */
4791
-    public function has_primary_key_field()
4792
-    {
4793
-        if ($this->_has_primary_key_field === null) {
4794
-            try {
4795
-                $this->get_primary_key_field();
4796
-                $this->_has_primary_key_field = true;
4797
-            } catch (EE_Error $e) {
4798
-                $this->_has_primary_key_field = false;
4799
-            }
4800
-        }
4801
-        return $this->_has_primary_key_field;
4802
-    }
4803
-
4804
-
4805
-
4806
-    /**
4807
-     * Finds the first field of type $field_class_name.
4808
-     *
4809
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4810
-     *                                 EE_Foreign_Key_Field, etc
4811
-     * @return EE_Model_Field_Base or null if none is found
4812
-     */
4813
-    public function get_a_field_of_type($field_class_name)
4814
-    {
4815
-        foreach ($this->field_settings() as $field) {
4816
-            if ($field instanceof $field_class_name) {
4817
-                return $field;
4818
-            }
4819
-        }
4820
-        return null;
4821
-    }
4822
-
4823
-
4824
-
4825
-    /**
4826
-     * Gets a foreign key field pointing to model.
4827
-     *
4828
-     * @param string $model_name eg Event, Registration, not EEM_Event
4829
-     * @return EE_Foreign_Key_Field_Base
4830
-     * @throws EE_Error
4831
-     */
4832
-    public function get_foreign_key_to($model_name)
4833
-    {
4834
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4835
-            foreach ($this->field_settings() as $field) {
4836
-                if (
4837
-                    $field instanceof EE_Foreign_Key_Field_Base
4838
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4839
-                ) {
4840
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4841
-                    break;
4842
-                }
4843
-            }
4844
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4845
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4846
-                    'event_espresso'), $model_name, get_class($this)));
4847
-            }
4848
-        }
4849
-        return $this->_cache_foreign_key_to_fields[$model_name];
4850
-    }
4851
-
4852
-
4853
-
4854
-    /**
4855
-     * Gets the table name (including $wpdb->prefix) for the table alias
4856
-     *
4857
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4858
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4859
-     *                            Either one works
4860
-     * @return string
4861
-     */
4862
-    public function get_table_for_alias($table_alias)
4863
-    {
4864
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4865
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4866
-    }
4867
-
4868
-
4869
-
4870
-    /**
4871
-     * Returns a flat array of all field son this model, instead of organizing them
4872
-     * by table_alias as they are in the constructor.
4873
-     *
4874
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4875
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4876
-     */
4877
-    public function field_settings($include_db_only_fields = false)
4878
-    {
4879
-        if ($include_db_only_fields) {
4880
-            if ($this->_cached_fields === null) {
4881
-                $this->_cached_fields = array();
4882
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4883
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4884
-                        $this->_cached_fields[$field_name] = $field_obj;
4885
-                    }
4886
-                }
4887
-            }
4888
-            return $this->_cached_fields;
4889
-        }
4890
-        if ($this->_cached_fields_non_db_only === null) {
4891
-            $this->_cached_fields_non_db_only = array();
4892
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4893
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4894
-                    /** @var $field_obj EE_Model_Field_Base */
4895
-                    if (! $field_obj->is_db_only_field()) {
4896
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4897
-                    }
4898
-                }
4899
-            }
4900
-        }
4901
-        return $this->_cached_fields_non_db_only;
4902
-    }
4903
-
4904
-
4905
-
4906
-    /**
4907
-     *        cycle though array of attendees and create objects out of each item
4908
-     *
4909
-     * @access        private
4910
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4911
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4912
-     *                           numerically indexed)
4913
-     * @throws EE_Error
4914
-     */
4915
-    protected function _create_objects($rows = array())
4916
-    {
4917
-        $array_of_objects = array();
4918
-        if (empty($rows)) {
4919
-            return array();
4920
-        }
4921
-        $count_if_model_has_no_primary_key = 0;
4922
-        $has_primary_key = $this->has_primary_key_field();
4923
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4924
-        foreach ((array)$rows as $row) {
4925
-            if (empty($row)) {
4926
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4927
-                return array();
4928
-            }
4929
-            //check if we've already set this object in the results array,
4930
-            //in which case there's no need to process it further (again)
4931
-            if ($has_primary_key) {
4932
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4933
-                    $row,
4934
-                    $primary_key_field->get_qualified_column(),
4935
-                    $primary_key_field->get_table_column()
4936
-                );
4937
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4938
-                    continue;
4939
-                }
4940
-            }
4941
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4942
-            if (! $classInstance) {
4943
-                throw new EE_Error(
4944
-                    sprintf(
4945
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4946
-                        $this->get_this_model_name(),
4947
-                        http_build_query($row)
4948
-                    )
4949
-                );
4950
-            }
4951
-            //set the timezone on the instantiated objects
4952
-            $classInstance->set_timezone($this->_timezone);
4953
-            //make sure if there is any timezone setting present that we set the timezone for the object
4954
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4955
-            $array_of_objects[$key] = $classInstance;
4956
-            //also, for all the relations of type BelongsTo, see if we can cache
4957
-            //those related models
4958
-            //(we could do this for other relations too, but if there are conditions
4959
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4960
-            //so it requires a little more thought than just caching them immediately...)
4961
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4962
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4963
-                    //check if this model's INFO is present. If so, cache it on the model
4964
-                    $other_model = $relation_obj->get_other_model();
4965
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4966
-                    //if we managed to make a model object from the results, cache it on the main model object
4967
-                    if ($other_model_obj_maybe) {
4968
-                        //set timezone on these other model objects if they are present
4969
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4970
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4971
-                    }
4972
-                }
4973
-            }
4974
-        }
4975
-        return $array_of_objects;
4976
-    }
4977
-
4978
-
4979
-
4980
-    /**
4981
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4982
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4983
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4984
-     * object (as set in the model_field!).
4985
-     *
4986
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4987
-     */
4988
-    public function create_default_object()
4989
-    {
4990
-        $this_model_fields_and_values = array();
4991
-        //setup the row using default values;
4992
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4993
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4994
-        }
4995
-        $className = $this->_get_class_name();
4996
-        $classInstance = EE_Registry::instance()
4997
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4998
-        return $classInstance;
4999
-    }
5000
-
5001
-
5002
-
5003
-    /**
5004
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5005
-     *                             or an stdClass where each property is the name of a column,
5006
-     * @return EE_Base_Class
5007
-     * @throws EE_Error
5008
-     */
5009
-    public function instantiate_class_from_array_or_object($cols_n_values)
5010
-    {
5011
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5012
-            $cols_n_values = get_object_vars($cols_n_values);
5013
-        }
5014
-        $primary_key = null;
5015
-        //make sure the array only has keys that are fields/columns on this model
5016
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5017
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5018
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5019
-        }
5020
-        $className = $this->_get_class_name();
5021
-        //check we actually found results that we can use to build our model object
5022
-        //if not, return null
5023
-        if ($this->has_primary_key_field()) {
5024
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5025
-                return null;
5026
-            }
5027
-        } else if ($this->unique_indexes()) {
5028
-            $first_column = reset($this_model_fields_n_values);
5029
-            if (empty($first_column)) {
5030
-                return null;
5031
-            }
5032
-        }
5033
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034
-        if ($primary_key) {
5035
-            $classInstance = $this->get_from_entity_map($primary_key);
5036
-            if (! $classInstance) {
5037
-                $classInstance = EE_Registry::instance()
5038
-                                            ->load_class($className,
5039
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5040
-                // add this new object to the entity map
5041
-                $classInstance = $this->add_to_entity_map($classInstance);
5042
-            }
5043
-        } else {
5044
-            $classInstance = EE_Registry::instance()
5045
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5046
-                                            true, false);
5047
-        }
5048
-        //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.
5049
-        $this->set_timezone($classInstance->get_timezone());
5050
-        return $classInstance;
5051
-    }
5052
-
5053
-
5054
-
5055
-    /**
5056
-     * Gets the model object from the  entity map if it exists
5057
-     *
5058
-     * @param int|string $id the ID of the model object
5059
-     * @return EE_Base_Class
5060
-     */
5061
-    public function get_from_entity_map($id)
5062
-    {
5063
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5064
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5065
-    }
5066
-
5067
-
5068
-
5069
-    /**
5070
-     * add_to_entity_map
5071
-     * Adds the object to the model's entity mappings
5072
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5073
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5074
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5075
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5076
-     *        then this method should be called immediately after the update query
5077
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5078
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5079
-     *
5080
-     * @param    EE_Base_Class $object
5081
-     * @throws EE_Error
5082
-     * @return \EE_Base_Class
5083
-     */
5084
-    public function add_to_entity_map(EE_Base_Class $object)
5085
-    {
5086
-        $className = $this->_get_class_name();
5087
-        if (! $object instanceof $className) {
5088
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5089
-                is_object($object) ? get_class($object) : $object, $className));
5090
-        }
5091
-        /** @var $object EE_Base_Class */
5092
-        if (! $object->ID()) {
5093
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5094
-                "event_espresso"), get_class($this)));
5095
-        }
5096
-        // double check it's not already there
5097
-        $classInstance = $this->get_from_entity_map($object->ID());
5098
-        if ($classInstance) {
5099
-            return $classInstance;
5100
-        }
5101
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5102
-        return $object;
5103
-    }
5104
-
5105
-
5106
-
5107
-    /**
5108
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5109
-     * if no identifier is provided, then the entire entity map is emptied
5110
-     *
5111
-     * @param int|string $id the ID of the model object
5112
-     * @return boolean
5113
-     */
5114
-    public function clear_entity_map($id = null)
5115
-    {
5116
-        if (empty($id)) {
5117
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5118
-            return true;
5119
-        }
5120
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5121
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5122
-            return true;
5123
-        }
5124
-        return false;
5125
-    }
5126
-
5127
-
5128
-
5129
-    /**
5130
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5131
-     * Given an array where keys are column (or column alias) names and values,
5132
-     * returns an array of their corresponding field names and database values
5133
-     *
5134
-     * @param array $cols_n_values
5135
-     * @return array
5136
-     */
5137
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5138
-    {
5139
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5140
-    }
5141
-
5142
-
5143
-
5144
-    /**
5145
-     * _deduce_fields_n_values_from_cols_n_values
5146
-     * Given an array where keys are column (or column alias) names and values,
5147
-     * returns an array of their corresponding field names and database values
5148
-     *
5149
-     * @param string $cols_n_values
5150
-     * @return array
5151
-     */
5152
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5153
-    {
5154
-        $this_model_fields_n_values = array();
5155
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5156
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5157
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5158
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5159
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5160
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5161
-                    if (! $field_obj->is_db_only_field()) {
5162
-                        //prepare field as if its coming from db
5163
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5164
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5165
-                    }
5166
-                }
5167
-            } else {
5168
-                //the table's rows existed. Use their values
5169
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5170
-                    if (! $field_obj->is_db_only_field()) {
5171
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5172
-                            $cols_n_values, $field_obj->get_qualified_column(),
5173
-                            $field_obj->get_table_column()
5174
-                        );
5175
-                    }
5176
-                }
5177
-            }
5178
-        }
5179
-        return $this_model_fields_n_values;
5180
-    }
5181
-
5182
-
5183
-
5184
-    /**
5185
-     * @param $cols_n_values
5186
-     * @param $qualified_column
5187
-     * @param $regular_column
5188
-     * @return null
5189
-     */
5190
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5191
-    {
5192
-        $value = null;
5193
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5194
-        //does the field on the model relate to this column retrieved from the db?
5195
-        //or is it a db-only field? (not relating to the model)
5196
-        if (isset($cols_n_values[$qualified_column])) {
5197
-            $value = $cols_n_values[$qualified_column];
5198
-        } elseif (isset($cols_n_values[$regular_column])) {
5199
-            $value = $cols_n_values[$regular_column];
5200
-        }
5201
-        return $value;
5202
-    }
5203
-
5204
-
5205
-
5206
-    /**
5207
-     * refresh_entity_map_from_db
5208
-     * Makes sure the model object in the entity map at $id assumes the values
5209
-     * of the database (opposite of EE_base_Class::save())
5210
-     *
5211
-     * @param int|string $id
5212
-     * @return EE_Base_Class
5213
-     * @throws EE_Error
5214
-     */
5215
-    public function refresh_entity_map_from_db($id)
5216
-    {
5217
-        $obj_in_map = $this->get_from_entity_map($id);
5218
-        if ($obj_in_map) {
5219
-            $wpdb_results = $this->_get_all_wpdb_results(
5220
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5221
-            );
5222
-            if ($wpdb_results && is_array($wpdb_results)) {
5223
-                $one_row = reset($wpdb_results);
5224
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5225
-                    $obj_in_map->set_from_db($field_name, $db_value);
5226
-                }
5227
-                //clear the cache of related model objects
5228
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5229
-                    $obj_in_map->clear_cache($relation_name, null, true);
5230
-                }
5231
-            }
5232
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5233
-            return $obj_in_map;
5234
-        }
5235
-        return $this->get_one_by_ID($id);
5236
-    }
5237
-
5238
-
5239
-
5240
-    /**
5241
-     * refresh_entity_map_with
5242
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5243
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5244
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5245
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5246
-     *
5247
-     * @param int|string    $id
5248
-     * @param EE_Base_Class $replacing_model_obj
5249
-     * @return \EE_Base_Class
5250
-     * @throws EE_Error
5251
-     */
5252
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5253
-    {
5254
-        $obj_in_map = $this->get_from_entity_map($id);
5255
-        if ($obj_in_map) {
5256
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5257
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5258
-                    $obj_in_map->set($field_name, $value);
5259
-                }
5260
-                //make the model object in the entity map's cache match the $replacing_model_obj
5261
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5262
-                    $obj_in_map->clear_cache($relation_name, null, true);
5263
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5264
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5265
-                    }
5266
-                }
5267
-            }
5268
-            return $obj_in_map;
5269
-        }
5270
-        $this->add_to_entity_map($replacing_model_obj);
5271
-        return $replacing_model_obj;
5272
-    }
5273
-
5274
-
5275
-
5276
-    /**
5277
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5278
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5279
-     * require_once($this->_getClassName().".class.php");
5280
-     *
5281
-     * @return string
5282
-     */
5283
-    private function _get_class_name()
5284
-    {
5285
-        return "EE_" . $this->get_this_model_name();
5286
-    }
5287
-
5288
-
5289
-
5290
-    /**
5291
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5292
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5293
-     * it would be 'Events'.
5294
-     *
5295
-     * @param int $quantity
5296
-     * @return string
5297
-     */
5298
-    public function item_name($quantity = 1)
5299
-    {
5300
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5301
-    }
5302
-
5303
-
5304
-
5305
-    /**
5306
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5307
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5308
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5309
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5310
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5311
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5312
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5313
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5314
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5315
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5316
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5317
-     *        return $previousReturnValue.$returnString;
5318
-     * }
5319
-     * require('EEM_Answer.model.php');
5320
-     * $answer=EEM_Answer::instance();
5321
-     * echo $answer->my_callback('monkeys',100);
5322
-     * //will output "you called my_callback! and passed args:monkeys,100"
5323
-     *
5324
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5325
-     * @param array  $args       array of original arguments passed to the function
5326
-     * @throws EE_Error
5327
-     * @return mixed whatever the plugin which calls add_filter decides
5328
-     */
5329
-    public function __call($methodName, $args)
5330
-    {
5331
-        $className = get_class($this);
5332
-        $tagName = "FHEE__{$className}__{$methodName}";
5333
-        if (! has_filter($tagName)) {
5334
-            throw new EE_Error(
5335
-                sprintf(
5336
-                    __('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 );',
5337
-                        'event_espresso'),
5338
-                    $methodName,
5339
-                    $className,
5340
-                    $tagName,
5341
-                    '<br />'
5342
-                )
5343
-            );
5344
-        }
5345
-        return apply_filters($tagName, null, $this, $args);
5346
-    }
5347
-
5348
-
5349
-
5350
-    /**
5351
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5352
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5353
-     *
5354
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5355
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5356
-     *                                                       the object's class name
5357
-     *                                                       or object's ID
5358
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5359
-     *                                                       exists in the database. If it does not, we add it
5360
-     * @throws EE_Error
5361
-     * @return EE_Base_Class
5362
-     */
5363
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5364
-    {
5365
-        $className = $this->_get_class_name();
5366
-        if ($base_class_obj_or_id instanceof $className) {
5367
-            $model_object = $base_class_obj_or_id;
5368
-        } else {
5369
-            $primary_key_field = $this->get_primary_key_field();
5370
-            if (
5371
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5372
-                && (
5373
-                    is_int($base_class_obj_or_id)
5374
-                    || is_string($base_class_obj_or_id)
5375
-                )
5376
-            ) {
5377
-                // assume it's an ID.
5378
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5379
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5380
-            } else if (
5381
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5382
-                && is_string($base_class_obj_or_id)
5383
-            ) {
5384
-                // assume its a string representation of the object
5385
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5386
-            } else {
5387
-                throw new EE_Error(
5388
-                    sprintf(
5389
-                        __(
5390
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5391
-                            'event_espresso'
5392
-                        ),
5393
-                        $base_class_obj_or_id,
5394
-                        $this->_get_class_name(),
5395
-                        print_r($base_class_obj_or_id, true)
5396
-                    )
5397
-                );
5398
-            }
5399
-        }
5400
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5401
-            $model_object->save();
5402
-        }
5403
-        return $model_object;
5404
-    }
5405
-
5406
-
5407
-
5408
-    /**
5409
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5410
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5411
-     * returns it ID.
5412
-     *
5413
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5414
-     * @return int|string depending on the type of this model object's ID
5415
-     * @throws EE_Error
5416
-     */
5417
-    public function ensure_is_ID($base_class_obj_or_id)
5418
-    {
5419
-        $className = $this->_get_class_name();
5420
-        if ($base_class_obj_or_id instanceof $className) {
5421
-            /** @var $base_class_obj_or_id EE_Base_Class */
5422
-            $id = $base_class_obj_or_id->ID();
5423
-        } elseif (is_int($base_class_obj_or_id)) {
5424
-            //assume it's an ID
5425
-            $id = $base_class_obj_or_id;
5426
-        } elseif (is_string($base_class_obj_or_id)) {
5427
-            //assume its a string representation of the object
5428
-            $id = $base_class_obj_or_id;
5429
-        } else {
5430
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5431
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5432
-                print_r($base_class_obj_or_id, true)));
5433
-        }
5434
-        return $id;
5435
-    }
5436
-
5437
-
5438
-
5439
-    /**
5440
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5441
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5442
-     * been sanitized and converted into the appropriate domain.
5443
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5444
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5445
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5446
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5447
-     * $EVT = EEM_Event::instance(); $old_setting =
5448
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5449
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5450
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5451
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5452
-     *
5453
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5454
-     * @return void
5455
-     */
5456
-    public function assume_values_already_prepared_by_model_object(
5457
-        $values_already_prepared = self::not_prepared_by_model_object
5458
-    ) {
5459
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5460
-    }
5461
-
5462
-
5463
-
5464
-    /**
5465
-     * Read comments for assume_values_already_prepared_by_model_object()
5466
-     *
5467
-     * @return int
5468
-     */
5469
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5470
-    {
5471
-        return $this->_values_already_prepared_by_model_object;
5472
-    }
5473
-
5474
-
5475
-
5476
-    /**
5477
-     * Gets all the indexes on this model
5478
-     *
5479
-     * @return EE_Index[]
5480
-     */
5481
-    public function indexes()
5482
-    {
5483
-        return $this->_indexes;
5484
-    }
5485
-
5486
-
5487
-
5488
-    /**
5489
-     * Gets all the Unique Indexes on this model
5490
-     *
5491
-     * @return EE_Unique_Index[]
5492
-     */
5493
-    public function unique_indexes()
5494
-    {
5495
-        $unique_indexes = array();
5496
-        foreach ($this->_indexes as $name => $index) {
5497
-            if ($index instanceof EE_Unique_Index) {
5498
-                $unique_indexes [$name] = $index;
5499
-            }
5500
-        }
5501
-        return $unique_indexes;
5502
-    }
5503
-
5504
-
5505
-
5506
-    /**
5507
-     * Gets all the fields which, when combined, make the primary key.
5508
-     * This is usually just an array with 1 element (the primary key), but in cases
5509
-     * where there is no primary key, it's a combination of fields as defined
5510
-     * on a primary index
5511
-     *
5512
-     * @return EE_Model_Field_Base[] indexed by the field's name
5513
-     * @throws EE_Error
5514
-     */
5515
-    public function get_combined_primary_key_fields()
5516
-    {
5517
-        foreach ($this->indexes() as $index) {
5518
-            if ($index instanceof EE_Primary_Key_Index) {
5519
-                return $index->fields();
5520
-            }
5521
-        }
5522
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5523
-    }
5524
-
5525
-
5526
-
5527
-    /**
5528
-     * Used to build a primary key string (when the model has no primary key),
5529
-     * which can be used a unique string to identify this model object.
5530
-     *
5531
-     * @param array $cols_n_values keys are field names, values are their values
5532
-     * @return string
5533
-     * @throws EE_Error
5534
-     */
5535
-    public function get_index_primary_key_string($cols_n_values)
5536
-    {
5537
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5538
-            $this->get_combined_primary_key_fields());
5539
-        return http_build_query($cols_n_values_for_primary_key_index);
5540
-    }
5541
-
5542
-
5543
-
5544
-    /**
5545
-     * Gets the field values from the primary key string
5546
-     *
5547
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5548
-     * @param string $index_primary_key_string
5549
-     * @return null|array
5550
-     * @throws EE_Error
5551
-     */
5552
-    public function parse_index_primary_key_string($index_primary_key_string)
5553
-    {
5554
-        $key_fields = $this->get_combined_primary_key_fields();
5555
-        //check all of them are in the $id
5556
-        $key_vals_in_combined_pk = array();
5557
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5558
-        foreach ($key_fields as $key_field_name => $field_obj) {
5559
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5560
-                return null;
5561
-            }
5562
-        }
5563
-        return $key_vals_in_combined_pk;
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * verifies that an array of key-value pairs for model fields has a key
5570
-     * for each field comprising the primary key index
5571
-     *
5572
-     * @param array $key_vals
5573
-     * @return boolean
5574
-     * @throws EE_Error
5575
-     */
5576
-    public function has_all_combined_primary_key_fields($key_vals)
5577
-    {
5578
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5579
-        foreach ($keys_it_should_have as $key) {
5580
-            if (! isset($key_vals[$key])) {
5581
-                return false;
5582
-            }
5583
-        }
5584
-        return true;
5585
-    }
5586
-
5587
-
5588
-
5589
-    /**
5590
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5591
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5592
-     *
5593
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5594
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5595
-     * @throws EE_Error
5596
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5597
-     *                                                              indexed)
5598
-     */
5599
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5600
-    {
5601
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5602
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5603
-        } elseif (is_array($model_object_or_attributes_array)) {
5604
-            $attributes_array = $model_object_or_attributes_array;
5605
-        } else {
5606
-            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",
5607
-                "event_espresso"), $model_object_or_attributes_array));
5608
-        }
5609
-        //even copies obviously won't have the same ID, so remove the primary key
5610
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5611
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5612
-            unset($attributes_array[$this->primary_key_name()]);
5613
-        }
5614
-        if (isset($query_params[0])) {
5615
-            $query_params[0] = array_merge($attributes_array, $query_params);
5616
-        } else {
5617
-            $query_params[0] = $attributes_array;
5618
-        }
5619
-        return $this->get_all($query_params);
5620
-    }
5621
-
5622
-
5623
-
5624
-    /**
5625
-     * Gets the first copy we find. See get_all_copies for more details
5626
-     *
5627
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5628
-     * @param array $query_params
5629
-     * @return EE_Base_Class
5630
-     * @throws EE_Error
5631
-     */
5632
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5633
-    {
5634
-        if (! is_array($query_params)) {
5635
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5636
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5637
-                    gettype($query_params)), '4.6.0');
5638
-            $query_params = array();
5639
-        }
5640
-        $query_params['limit'] = 1;
5641
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5642
-        if (is_array($copies)) {
5643
-            return array_shift($copies);
5644
-        }
5645
-        return null;
5646
-    }
5647
-
5648
-
5649
-
5650
-    /**
5651
-     * Updates the item with the specified id. Ignores default query parameters because
5652
-     * we have specified the ID, and its assumed we KNOW what we're doing
5653
-     *
5654
-     * @param array      $fields_n_values keys are field names, values are their new values
5655
-     * @param int|string $id              the value of the primary key to update
5656
-     * @return int number of rows updated
5657
-     * @throws EE_Error
5658
-     */
5659
-    public function update_by_ID($fields_n_values, $id)
5660
-    {
5661
-        $query_params = array(
5662
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5663
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5664
-        );
5665
-        return $this->update($fields_n_values, $query_params);
5666
-    }
5667
-
5668
-
5669
-
5670
-    /**
5671
-     * Changes an operator which was supplied to the models into one usable in SQL
5672
-     *
5673
-     * @param string $operator_supplied
5674
-     * @return string an operator which can be used in SQL
5675
-     * @throws EE_Error
5676
-     */
5677
-    private function _prepare_operator_for_sql($operator_supplied)
5678
-    {
5679
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5680
-            : null;
5681
-        if ($sql_operator) {
5682
-            return $sql_operator;
5683
-        }
5684
-        throw new EE_Error(
5685
-            sprintf(
5686
-                __(
5687
-                    "The operator '%s' is not in the list of valid operators: %s",
5688
-                    "event_espresso"
5689
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5690
-            )
5691
-        );
5692
-    }
5693
-
5694
-
5695
-
5696
-    /**
5697
-     * Gets the valid operators
5698
-     * @return array keys are accepted strings, values are the SQL they are converted to
5699
-     */
5700
-    public function valid_operators(){
5701
-        return $this->_valid_operators;
5702
-    }
5703
-
5704
-
5705
-
5706
-    /**
5707
-     * Gets the between-style operators (take 2 arguments).
5708
-     * @return array keys are accepted strings, values are the SQL they are converted to
5709
-     */
5710
-    public function valid_between_style_operators()
5711
-    {
5712
-        return array_intersect(
5713
-            $this->valid_operators(),
5714
-            $this->_between_style_operators
5715
-        );
5716
-    }
5717
-
5718
-    /**
5719
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5720
-     * @return array keys are accepted strings, values are the SQL they are converted to
5721
-     */
5722
-    public function valid_like_style_operators()
5723
-    {
5724
-        return array_intersect(
5725
-            $this->valid_operators(),
5726
-            $this->_like_style_operators
5727
-        );
5728
-    }
5729
-
5730
-    /**
5731
-     * Gets the "in"-style operators
5732
-     * @return array keys are accepted strings, values are the SQL they are converted to
5733
-     */
5734
-    public function valid_in_style_operators()
5735
-    {
5736
-        return array_intersect(
5737
-            $this->valid_operators(),
5738
-            $this->_in_style_operators
5739
-        );
5740
-    }
5741
-
5742
-    /**
5743
-     * Gets the "null"-style operators (accept no arguments)
5744
-     * @return array keys are accepted strings, values are the SQL they are converted to
5745
-     */
5746
-    public function valid_null_style_operators()
5747
-    {
5748
-        return array_intersect(
5749
-            $this->valid_operators(),
5750
-            $this->_null_style_operators
5751
-        );
5752
-    }
5753
-
5754
-    /**
5755
-     * Gets an array where keys are the primary keys and values are their 'names'
5756
-     * (as determined by the model object's name() function, which is often overridden)
5757
-     *
5758
-     * @param array $query_params like get_all's
5759
-     * @return string[]
5760
-     * @throws EE_Error
5761
-     */
5762
-    public function get_all_names($query_params = array())
5763
-    {
5764
-        $objs = $this->get_all($query_params);
5765
-        $names = array();
5766
-        foreach ($objs as $obj) {
5767
-            $names[$obj->ID()] = $obj->name();
5768
-        }
5769
-        return $names;
5770
-    }
5771
-
5772
-
5773
-
5774
-    /**
5775
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5776
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5777
-     * this is duplicated effort and reduces efficiency) you would be better to use
5778
-     * array_keys() on $model_objects.
5779
-     *
5780
-     * @param \EE_Base_Class[] $model_objects
5781
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5782
-     *                                               in the returned array
5783
-     * @return array
5784
-     * @throws EE_Error
5785
-     */
5786
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5787
-    {
5788
-        if (! $this->has_primary_key_field()) {
5789
-            if (WP_DEBUG) {
5790
-                EE_Error::add_error(
5791
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5792
-                    __FILE__,
5793
-                    __FUNCTION__,
5794
-                    __LINE__
5795
-                );
5796
-            }
5797
-        }
5798
-        $IDs = array();
5799
-        foreach ($model_objects as $model_object) {
5800
-            $id = $model_object->ID();
5801
-            if (! $id) {
5802
-                if ($filter_out_empty_ids) {
5803
-                    continue;
5804
-                }
5805
-                if (WP_DEBUG) {
5806
-                    EE_Error::add_error(
5807
-                        __(
5808
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5809
-                            'event_espresso'
5810
-                        ),
5811
-                        __FILE__,
5812
-                        __FUNCTION__,
5813
-                        __LINE__
5814
-                    );
5815
-                }
5816
-            }
5817
-            $IDs[] = $id;
5818
-        }
5819
-        return $IDs;
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * Returns the string used in capabilities relating to this model. If there
5826
-     * are no capabilities that relate to this model returns false
5827
-     *
5828
-     * @return string|false
5829
-     */
5830
-    public function cap_slug()
5831
-    {
5832
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5833
-    }
5834
-
5835
-
5836
-
5837
-    /**
5838
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5839
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5840
-     * only returns the cap restrictions array in that context (ie, the array
5841
-     * at that key)
5842
-     *
5843
-     * @param string $context
5844
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5845
-     * @throws EE_Error
5846
-     */
5847
-    public function cap_restrictions($context = EEM_Base::caps_read)
5848
-    {
5849
-        EEM_Base::verify_is_valid_cap_context($context);
5850
-        //check if we ought to run the restriction generator first
5851
-        if (
5852
-            isset($this->_cap_restriction_generators[$context])
5853
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5854
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5855
-        ) {
5856
-            $this->_cap_restrictions[$context] = array_merge(
5857
-                $this->_cap_restrictions[$context],
5858
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5859
-            );
5860
-        }
5861
-        //and make sure we've finalized the construction of each restriction
5862
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5863
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5864
-                $where_conditions_obj->_finalize_construct($this);
5865
-            }
5866
-        }
5867
-        return $this->_cap_restrictions[$context];
5868
-    }
5869
-
5870
-
5871
-
5872
-    /**
5873
-     * Indicating whether or not this model thinks its a wp core model
5874
-     *
5875
-     * @return boolean
5876
-     */
5877
-    public function is_wp_core_model()
5878
-    {
5879
-        return $this->_wp_core_model;
5880
-    }
5881
-
5882
-
5883
-
5884
-    /**
5885
-     * Gets all the caps that are missing which impose a restriction on
5886
-     * queries made in this context
5887
-     *
5888
-     * @param string $context one of EEM_Base::caps_ constants
5889
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5890
-     * @throws EE_Error
5891
-     */
5892
-    public function caps_missing($context = EEM_Base::caps_read)
5893
-    {
5894
-        $missing_caps = array();
5895
-        $cap_restrictions = $this->cap_restrictions($context);
5896
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5897
-            if (! EE_Capabilities::instance()
5898
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5899
-            ) {
5900
-                $missing_caps[$cap] = $restriction_if_no_cap;
5901
-            }
5902
-        }
5903
-        return $missing_caps;
5904
-    }
5905
-
5906
-
5907
-
5908
-    /**
5909
-     * Gets the mapping from capability contexts to action strings used in capability names
5910
-     *
5911
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5912
-     * one of 'read', 'edit', or 'delete'
5913
-     */
5914
-    public function cap_contexts_to_cap_action_map()
5915
-    {
5916
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5917
-            $this);
5918
-    }
5919
-
5920
-
5921
-
5922
-    /**
5923
-     * Gets the action string for the specified capability context
5924
-     *
5925
-     * @param string $context
5926
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5927
-     * @throws EE_Error
5928
-     */
5929
-    public function cap_action_for_context($context)
5930
-    {
5931
-        $mapping = $this->cap_contexts_to_cap_action_map();
5932
-        if (isset($mapping[$context])) {
5933
-            return $mapping[$context];
5934
-        }
5935
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5936
-            return $action;
5937
-        }
5938
-        throw new EE_Error(
5939
-            sprintf(
5940
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5941
-                $context,
5942
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5943
-            )
5944
-        );
5945
-    }
5946
-
5947
-
5948
-
5949
-    /**
5950
-     * Returns all the capability contexts which are valid when querying models
5951
-     *
5952
-     * @return array
5953
-     */
5954
-    public static function valid_cap_contexts()
5955
-    {
5956
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5957
-            self::caps_read,
5958
-            self::caps_read_admin,
5959
-            self::caps_edit,
5960
-            self::caps_delete,
5961
-        ));
5962
-    }
5963
-
5964
-
5965
-
5966
-    /**
5967
-     * Returns all valid options for 'default_where_conditions'
5968
-     *
5969
-     * @return array
5970
-     */
5971
-    public static function valid_default_where_conditions()
5972
-    {
5973
-        return array(
5974
-            EEM_Base::default_where_conditions_all,
5975
-            EEM_Base::default_where_conditions_this_only,
5976
-            EEM_Base::default_where_conditions_others_only,
5977
-            EEM_Base::default_where_conditions_minimum_all,
5978
-            EEM_Base::default_where_conditions_minimum_others,
5979
-            EEM_Base::default_where_conditions_none
5980
-        );
5981
-    }
5982
-
5983
-    // public static function default_where_conditions_full
5984
-    /**
5985
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5986
-     *
5987
-     * @param string $context
5988
-     * @return bool
5989
-     * @throws EE_Error
5990
-     */
5991
-    static public function verify_is_valid_cap_context($context)
5992
-    {
5993
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5994
-        if (in_array($context, $valid_cap_contexts)) {
5995
-            return true;
5996
-        }
5997
-        throw new EE_Error(
5998
-            sprintf(
5999
-                __(
6000
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6001
-                    'event_espresso'
6002
-                ),
6003
-                $context,
6004
-                'EEM_Base',
6005
-                implode(',', $valid_cap_contexts)
6006
-            )
6007
-        );
6008
-    }
6009
-
6010
-
6011
-
6012
-    /**
6013
-     * Clears all the models field caches. This is only useful when a sub-class
6014
-     * might have added a field or something and these caches might be invalidated
6015
-     */
6016
-    protected function _invalidate_field_caches()
6017
-    {
6018
-        $this->_cache_foreign_key_to_fields = array();
6019
-        $this->_cached_fields = null;
6020
-        $this->_cached_fields_non_db_only = null;
6021
-    }
6022
-
6023
-
6024
-
6025
-    /**
6026
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6027
-     * (eg "and", "or", "not").
6028
-     *
6029
-     * @return array
6030
-     */
6031
-    public function logic_query_param_keys()
6032
-    {
6033
-        return $this->_logic_query_param_keys;
6034
-    }
6035
-
6036
-
6037
-
6038
-    /**
6039
-     * Determines whether or not the where query param array key is for a logic query param.
6040
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6041
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6042
-     *
6043
-     * @param $query_param_key
6044
-     * @return bool
6045
-     */
6046
-    public function is_logic_query_param_key($query_param_key)
6047
-    {
6048
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6049
-            if ($query_param_key === $logic_query_param_key
6050
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6051
-            ) {
6052
-                return true;
6053
-            }
6054
-        }
6055
-        return false;
6056
-    }
3755
+		}
3756
+		return $null_friendly_where_conditions;
3757
+	}
3758
+
3759
+
3760
+
3761
+	/**
3762
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3763
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3764
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3765
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3766
+	 *
3767
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3768
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3769
+	 */
3770
+	private function _get_default_where_conditions($model_relation_path = null)
3771
+	{
3772
+		if ($this->_ignore_where_strategy) {
3773
+			return array();
3774
+		}
3775
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3776
+	}
3777
+
3778
+
3779
+
3780
+	/**
3781
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3782
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3783
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3785
+	 * Similar to _get_default_where_conditions
3786
+	 *
3787
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3788
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3789
+	 */
3790
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3791
+	{
3792
+		if ($this->_ignore_where_strategy) {
3793
+			return array();
3794
+		}
3795
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3796
+	}
3797
+
3798
+
3799
+
3800
+	/**
3801
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3802
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3803
+	 *
3804
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3805
+	 * @return string
3806
+	 * @throws EE_Error
3807
+	 */
3808
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3809
+	{
3810
+		$selects = $this->_get_columns_to_select_for_this_model();
3811
+		foreach (
3812
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3813
+			$name_of_other_model_included
3814
+		) {
3815
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3816
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3817
+			foreach ($other_model_selects as $key => $value) {
3818
+				$selects[] = $value;
3819
+			}
3820
+		}
3821
+		return implode(", ", $selects);
3822
+	}
3823
+
3824
+
3825
+
3826
+	/**
3827
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3828
+	 * So that's going to be the columns for all the fields on the model
3829
+	 *
3830
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3831
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3832
+	 */
3833
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3834
+	{
3835
+		$fields = $this->field_settings();
3836
+		$selects = array();
3837
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3838
+			$this->get_this_model_name());
3839
+		foreach ($fields as $field_obj) {
3840
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3841
+						 . $field_obj->get_table_alias()
3842
+						 . "."
3843
+						 . $field_obj->get_table_column()
3844
+						 . " AS '"
3845
+						 . $table_alias_with_model_relation_chain_prefix
3846
+						 . $field_obj->get_table_alias()
3847
+						 . "."
3848
+						 . $field_obj->get_table_column()
3849
+						 . "'";
3850
+		}
3851
+		//make sure we are also getting the PKs of each table
3852
+		$tables = $this->get_tables();
3853
+		if (count($tables) > 1) {
3854
+			foreach ($tables as $table_obj) {
3855
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3856
+									   . $table_obj->get_fully_qualified_pk_column();
3857
+				if (! in_array($qualified_pk_column, $selects)) {
3858
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3859
+				}
3860
+			}
3861
+		}
3862
+		return $selects;
3863
+	}
3864
+
3865
+
3866
+
3867
+	/**
3868
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3869
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3870
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3871
+	 * SQL for joining, and the data types
3872
+	 *
3873
+	 * @param null|string                 $original_query_param
3874
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3875
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3876
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3877
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3878
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3879
+	 *                                                          or 'Registration's
3880
+	 * @param string                      $original_query_param what it originally was (eg
3881
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3882
+	 *                                                          matches $query_param
3883
+	 * @throws EE_Error
3884
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3885
+	 */
3886
+	private function _extract_related_model_info_from_query_param(
3887
+		$query_param,
3888
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3889
+		$query_param_type,
3890
+		$original_query_param = null
3891
+	) {
3892
+		if ($original_query_param === null) {
3893
+			$original_query_param = $query_param;
3894
+		}
3895
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3896
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3897
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3898
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3899
+		//check to see if we have a field on this model
3900
+		$this_model_fields = $this->field_settings(true);
3901
+		if (array_key_exists($query_param, $this_model_fields)) {
3902
+			if ($allow_fields) {
3903
+				return;
3904
+			}
3905
+			throw new EE_Error(
3906
+				sprintf(
3907
+					__(
3908
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3909
+						"event_espresso"
3910
+					),
3911
+					$query_param, get_class($this), $query_param_type, $original_query_param
3912
+				)
3913
+			);
3914
+		}
3915
+		//check if this is a special logic query param
3916
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3917
+			if ($allow_logic_query_params) {
3918
+				return;
3919
+			}
3920
+			throw new EE_Error(
3921
+				sprintf(
3922
+					__(
3923
+						'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',
3924
+						'event_espresso'
3925
+					),
3926
+					implode('", "', $this->_logic_query_param_keys),
3927
+					$query_param,
3928
+					get_class($this),
3929
+					'<br />',
3930
+					"\t"
3931
+					. ' $passed_in_query_info = <pre>'
3932
+					. print_r($passed_in_query_info, true)
3933
+					. '</pre>'
3934
+					. "\n\t"
3935
+					. ' $query_param_type = '
3936
+					. $query_param_type
3937
+					. "\n\t"
3938
+					. ' $original_query_param = '
3939
+					. $original_query_param
3940
+				)
3941
+			);
3942
+		}
3943
+		//check if it's a custom selection
3944
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3945
+			return;
3946
+		}
3947
+		//check if has a model name at the beginning
3948
+		//and
3949
+		//check if it's a field on a related model
3950
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3951
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3952
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3953
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3954
+				if ($query_param === '') {
3955
+					//nothing left to $query_param
3956
+					//we should actually end in a field name, not a model like this!
3957
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3958
+						"event_espresso"),
3959
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3960
+				}
3961
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3962
+				$related_model_obj->_extract_related_model_info_from_query_param(
3963
+					$query_param,
3964
+					$passed_in_query_info, $query_param_type, $original_query_param
3965
+				);
3966
+				return;
3967
+			}
3968
+			if ($query_param === $valid_related_model_name) {
3969
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3970
+				return;
3971
+			}
3972
+		}
3973
+		//ok so $query_param didn't start with a model name
3974
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3975
+		//it's wack, that's what it is
3976
+		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",
3977
+			"event_espresso"),
3978
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3979
+	}
3980
+
3981
+
3982
+
3983
+	/**
3984
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3985
+	 * and store it on $passed_in_query_info
3986
+	 *
3987
+	 * @param string                      $model_name
3988
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3990
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3991
+	 *                                                          and are adding a join to 'Payment' with the original
3992
+	 *                                                          query param key
3993
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3994
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3995
+	 *                                                          Payment wants to add default query params so that it
3996
+	 *                                                          will know what models to prepend onto its default query
3997
+	 *                                                          params or in case it wants to rename tables (in case
3998
+	 *                                                          there are multiple joins to the same table)
3999
+	 * @return void
4000
+	 * @throws EE_Error
4001
+	 */
4002
+	private function _add_join_to_model(
4003
+		$model_name,
4004
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4005
+		$original_query_param
4006
+	) {
4007
+		$relation_obj = $this->related_settings_for($model_name);
4008
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4009
+		//check if the relation is HABTM, because then we're essentially doing two joins
4010
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4011
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4012
+			$join_model_obj = $relation_obj->get_join_model();
4013
+			//replace the model specified with the join model for this relation chain, whi
4014
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4015
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4016
+			$passed_in_query_info->merge(
4017
+				new EE_Model_Query_Info_Carrier(
4018
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4019
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4020
+				)
4021
+			);
4022
+		}
4023
+		//now just join to the other table pointed to by the relation object, and add its data types
4024
+		$passed_in_query_info->merge(
4025
+			new EE_Model_Query_Info_Carrier(
4026
+				array($model_relation_chain => $model_name),
4027
+				$relation_obj->get_join_statement($model_relation_chain)
4028
+			)
4029
+		);
4030
+	}
4031
+
4032
+
4033
+
4034
+	/**
4035
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4036
+	 *
4037
+	 * @param array $where_params like EEM_Base::get_all
4038
+	 * @return string of SQL
4039
+	 * @throws EE_Error
4040
+	 */
4041
+	private function _construct_where_clause($where_params)
4042
+	{
4043
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4044
+		if ($SQL) {
4045
+			return " WHERE " . $SQL;
4046
+		}
4047
+		return '';
4048
+	}
4049
+
4050
+
4051
+
4052
+	/**
4053
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4054
+	 * and should be passed HAVING parameters, not WHERE parameters
4055
+	 *
4056
+	 * @param array $having_params
4057
+	 * @return string
4058
+	 * @throws EE_Error
4059
+	 */
4060
+	private function _construct_having_clause($having_params)
4061
+	{
4062
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4063
+		if ($SQL) {
4064
+			return " HAVING " . $SQL;
4065
+		}
4066
+		return '';
4067
+	}
4068
+
4069
+
4070
+	/**
4071
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4072
+	 * Event_Meta.meta_value = 'foo'))"
4073
+	 *
4074
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4075
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4076
+	 * @throws EE_Error
4077
+	 * @return string of SQL
4078
+	 */
4079
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4080
+	{
4081
+		$where_clauses = array();
4082
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4083
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4084
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4085
+				switch ($query_param) {
4086
+					case 'not':
4087
+					case 'NOT':
4088
+						$where_clauses[] = "! ("
4089
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4090
+								$glue)
4091
+										   . ")";
4092
+						break;
4093
+					case 'and':
4094
+					case 'AND':
4095
+						$where_clauses[] = " ("
4096
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4097
+								' AND ')
4098
+										   . ")";
4099
+						break;
4100
+					case 'or':
4101
+					case 'OR':
4102
+						$where_clauses[] = " ("
4103
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4104
+								' OR ')
4105
+										   . ")";
4106
+						break;
4107
+				}
4108
+			} else {
4109
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4110
+				//if it's not a normal field, maybe it's a custom selection?
4111
+				if (! $field_obj) {
4112
+					if (isset($this->_custom_selections[$query_param][1])) {
4113
+						$field_obj = $this->_custom_selections[$query_param][1];
4114
+					} else {
4115
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4116
+							"event_espresso"), $query_param));
4117
+					}
4118
+				}
4119
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4120
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4121
+			}
4122
+		}
4123
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4124
+	}
4125
+
4126
+
4127
+
4128
+	/**
4129
+	 * Takes the input parameter and extract the table name (alias) and column name
4130
+	 *
4131
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4132
+	 * @throws EE_Error
4133
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4134
+	 */
4135
+	private function _deduce_column_name_from_query_param($query_param)
4136
+	{
4137
+		$field = $this->_deduce_field_from_query_param($query_param);
4138
+		if ($field) {
4139
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4140
+				$query_param);
4141
+			return $table_alias_prefix . $field->get_qualified_column();
4142
+		}
4143
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4144
+			//maybe it's custom selection item?
4145
+			//if so, just use it as the "column name"
4146
+			return $query_param;
4147
+		}
4148
+		throw new EE_Error(
4149
+			sprintf(
4150
+				__(
4151
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4152
+					"event_espresso"
4153
+				), $query_param, implode(",", $this->_custom_selections)
4154
+			)
4155
+		);
4156
+	}
4157
+
4158
+
4159
+
4160
+	/**
4161
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4162
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4163
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4164
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4165
+	 *
4166
+	 * @param string $condition_query_param_key
4167
+	 * @return string
4168
+	 */
4169
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4170
+	{
4171
+		$pos_of_star = strpos($condition_query_param_key, '*');
4172
+		if ($pos_of_star === false) {
4173
+			return $condition_query_param_key;
4174
+		}
4175
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4176
+		return $condition_query_param_sans_star;
4177
+	}
4178
+
4179
+
4180
+
4181
+	/**
4182
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4183
+	 *
4184
+	 * @param                            mixed      array | string    $op_and_value
4185
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4186
+	 * @throws EE_Error
4187
+	 * @return string
4188
+	 */
4189
+	private function _construct_op_and_value($op_and_value, $field_obj)
4190
+	{
4191
+		if (is_array($op_and_value)) {
4192
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4193
+			if (! $operator) {
4194
+				$php_array_like_string = array();
4195
+				foreach ($op_and_value as $key => $value) {
4196
+					$php_array_like_string[] = "$key=>$value";
4197
+				}
4198
+				throw new EE_Error(
4199
+					sprintf(
4200
+						__(
4201
+							"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))",
4202
+							"event_espresso"
4203
+						),
4204
+						implode(",", $php_array_like_string)
4205
+					)
4206
+				);
4207
+			}
4208
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4209
+		} else {
4210
+			$operator = '=';
4211
+			$value = $op_and_value;
4212
+		}
4213
+		//check to see if the value is actually another field
4214
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4215
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4216
+		}
4217
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4218
+			//in this case, the value should be an array, or at least a comma-separated list
4219
+			//it will need to handle a little differently
4220
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4221
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4222
+			return $operator . SP . $cleaned_value;
4223
+		}
4224
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4225
+			//the value should be an array with count of two.
4226
+			if (count($value) !== 2) {
4227
+				throw new EE_Error(
4228
+					sprintf(
4229
+						__(
4230
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4231
+							'event_espresso'
4232
+						),
4233
+						"BETWEEN"
4234
+					)
4235
+				);
4236
+			}
4237
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4238
+			return $operator . SP . $cleaned_value;
4239
+		}
4240
+		if (in_array($operator, $this->valid_null_style_operators())) {
4241
+			if ($value !== null) {
4242
+				throw new EE_Error(
4243
+					sprintf(
4244
+						__(
4245
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4246
+							"event_espresso"
4247
+						),
4248
+						$value,
4249
+						$operator
4250
+					)
4251
+				);
4252
+			}
4253
+			return $operator;
4254
+		}
4255
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4256
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4257
+			//remove other junk. So just treat it as a string.
4258
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4259
+		}
4260
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4261
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4262
+		}
4263
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4264
+			throw new EE_Error(
4265
+				sprintf(
4266
+					__(
4267
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4268
+						'event_espresso'
4269
+					),
4270
+					$operator,
4271
+					$operator
4272
+				)
4273
+			);
4274
+		}
4275
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4276
+			throw new EE_Error(
4277
+				sprintf(
4278
+					__(
4279
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4280
+						'event_espresso'
4281
+					),
4282
+					$operator,
4283
+					$operator
4284
+				)
4285
+			);
4286
+		}
4287
+		throw new EE_Error(
4288
+			sprintf(
4289
+				__(
4290
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4291
+					"event_espresso"
4292
+				),
4293
+				http_build_query($op_and_value)
4294
+			)
4295
+		);
4296
+	}
4297
+
4298
+
4299
+
4300
+	/**
4301
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4302
+	 *
4303
+	 * @param array                      $values
4304
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4305
+	 *                                              '%s'
4306
+	 * @return string
4307
+	 * @throws EE_Error
4308
+	 */
4309
+	public function _construct_between_value($values, $field_obj)
4310
+	{
4311
+		$cleaned_values = array();
4312
+		foreach ($values as $value) {
4313
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4314
+		}
4315
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4316
+	}
4317
+
4318
+
4319
+
4320
+	/**
4321
+	 * Takes an array or a comma-separated list of $values and cleans them
4322
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4323
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4324
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4325
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4326
+	 *
4327
+	 * @param mixed                      $values    array or comma-separated string
4328
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4329
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4330
+	 * @throws EE_Error
4331
+	 */
4332
+	public function _construct_in_value($values, $field_obj)
4333
+	{
4334
+		//check if the value is a CSV list
4335
+		if (is_string($values)) {
4336
+			//in which case, turn it into an array
4337
+			$values = explode(",", $values);
4338
+		}
4339
+		$cleaned_values = array();
4340
+		foreach ($values as $value) {
4341
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4342
+		}
4343
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4344
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4345
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4346
+		if (empty($cleaned_values)) {
4347
+			$all_fields = $this->field_settings();
4348
+			$a_field = array_shift($all_fields);
4349
+			$main_table = $this->_get_main_table();
4350
+			$cleaned_values[] = "SELECT "
4351
+								. $a_field->get_table_column()
4352
+								. " FROM "
4353
+								. $main_table->get_table_name()
4354
+								. " WHERE FALSE";
4355
+		}
4356
+		return "(" . implode(",", $cleaned_values) . ")";
4357
+	}
4358
+
4359
+
4360
+
4361
+	/**
4362
+	 * @param mixed                      $value
4363
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4364
+	 * @throws EE_Error
4365
+	 * @return false|null|string
4366
+	 */
4367
+	private function _wpdb_prepare_using_field($value, $field_obj)
4368
+	{
4369
+		/** @type WPDB $wpdb */
4370
+		global $wpdb;
4371
+		if ($field_obj instanceof EE_Model_Field_Base) {
4372
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4373
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4374
+		} //$field_obj should really just be a data type
4375
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4376
+			throw new EE_Error(
4377
+				sprintf(
4378
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4379
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4380
+				)
4381
+			);
4382
+		}
4383
+		return $wpdb->prepare($field_obj, $value);
4384
+	}
4385
+
4386
+
4387
+
4388
+	/**
4389
+	 * Takes the input parameter and finds the model field that it indicates.
4390
+	 *
4391
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4392
+	 * @throws EE_Error
4393
+	 * @return EE_Model_Field_Base
4394
+	 */
4395
+	protected function _deduce_field_from_query_param($query_param_name)
4396
+	{
4397
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4398
+		//which will help us find the database table and column
4399
+		$query_param_parts = explode(".", $query_param_name);
4400
+		if (empty($query_param_parts)) {
4401
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4402
+				'event_espresso'), $query_param_name));
4403
+		}
4404
+		$number_of_parts = count($query_param_parts);
4405
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4406
+		if ($number_of_parts === 1) {
4407
+			$field_name = $last_query_param_part;
4408
+			$model_obj = $this;
4409
+		} else {// $number_of_parts >= 2
4410
+			//the last part is the column name, and there are only 2parts. therefore...
4411
+			$field_name = $last_query_param_part;
4412
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4413
+		}
4414
+		try {
4415
+			return $model_obj->field_settings_for($field_name);
4416
+		} catch (EE_Error $e) {
4417
+			return null;
4418
+		}
4419
+	}
4420
+
4421
+
4422
+
4423
+	/**
4424
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4425
+	 * alias and column which corresponds to it
4426
+	 *
4427
+	 * @param string $field_name
4428
+	 * @throws EE_Error
4429
+	 * @return string
4430
+	 */
4431
+	public function _get_qualified_column_for_field($field_name)
4432
+	{
4433
+		$all_fields = $this->field_settings();
4434
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4435
+		if ($field) {
4436
+			return $field->get_qualified_column();
4437
+		}
4438
+		throw new EE_Error(
4439
+			sprintf(
4440
+				__(
4441
+					"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.",
4442
+					'event_espresso'
4443
+				), $field_name, get_class($this)
4444
+			)
4445
+		);
4446
+	}
4447
+
4448
+
4449
+
4450
+	/**
4451
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4452
+	 * Example usage:
4453
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4454
+	 *      array(),
4455
+	 *      ARRAY_A,
4456
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4457
+	 *  );
4458
+	 * is equivalent to
4459
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4460
+	 * and
4461
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4462
+	 *      array(
4463
+	 *          array(
4464
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4465
+	 *          ),
4466
+	 *          ARRAY_A,
4467
+	 *          implode(
4468
+	 *              ', ',
4469
+	 *              array_merge(
4470
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4471
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4472
+	 *              )
4473
+	 *          )
4474
+	 *      )
4475
+	 *  );
4476
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4477
+	 *
4478
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4479
+	 *                                            and the one whose fields you are selecting for example: when querying
4480
+	 *                                            tickets model and selecting fields from the tickets model you would
4481
+	 *                                            leave this parameter empty, because no models are needed to join
4482
+	 *                                            between the queried model and the selected one. Likewise when
4483
+	 *                                            querying the datetime model and selecting fields from the tickets
4484
+	 *                                            model, it would also be left empty, because there is a direct
4485
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4486
+	 *                                            them together. However, when querying from the event model and
4487
+	 *                                            selecting fields from the ticket model, you should provide the string
4488
+	 *                                            'Datetime', indicating that the event model must first join to the
4489
+	 *                                            datetime model in order to find its relation to ticket model.
4490
+	 *                                            Also, when querying from the venue model and selecting fields from
4491
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4492
+	 *                                            indicating you need to join the venue model to the event model,
4493
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4494
+	 *                                            This string is used to deduce the prefix that gets added onto the
4495
+	 *                                            models' tables qualified columns
4496
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4497
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4498
+	 *                                            qualified column names
4499
+	 * @return array|string
4500
+	 */
4501
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4502
+	{
4503
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4504
+		$qualified_columns = array();
4505
+		foreach ($this->field_settings() as $field_name => $field) {
4506
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4507
+		}
4508
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4509
+	}
4510
+
4511
+
4512
+
4513
+	/**
4514
+	 * constructs the select use on special limit joins
4515
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4516
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4517
+	 * (as that is typically where the limits would be set).
4518
+	 *
4519
+	 * @param  string       $table_alias The table the select is being built for
4520
+	 * @param  mixed|string $limit       The limit for this select
4521
+	 * @return string                The final select join element for the query.
4522
+	 */
4523
+	public function _construct_limit_join_select($table_alias, $limit)
4524
+	{
4525
+		$SQL = '';
4526
+		foreach ($this->_tables as $table_obj) {
4527
+			if ($table_obj instanceof EE_Primary_Table) {
4528
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4529
+					? $table_obj->get_select_join_limit($limit)
4530
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4531
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4532
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4533
+					? $table_obj->get_select_join_limit_join($limit)
4534
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4535
+			}
4536
+		}
4537
+		return $SQL;
4538
+	}
4539
+
4540
+
4541
+
4542
+	/**
4543
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4544
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4545
+	 *
4546
+	 * @return string SQL
4547
+	 * @throws EE_Error
4548
+	 */
4549
+	public function _construct_internal_join()
4550
+	{
4551
+		$SQL = $this->_get_main_table()->get_table_sql();
4552
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4553
+		return $SQL;
4554
+	}
4555
+
4556
+
4557
+
4558
+	/**
4559
+	 * Constructs the SQL for joining all the tables on this model.
4560
+	 * Normally $alias should be the primary table's alias, but in cases where
4561
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4562
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4563
+	 * alias, this will construct SQL like:
4564
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4565
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4566
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4567
+	 *
4568
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4569
+	 * @return string
4570
+	 */
4571
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4572
+	{
4573
+		$SQL = '';
4574
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4575
+		foreach ($this->_tables as $table_obj) {
4576
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4577
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4578
+					//so we're joining to this table, meaning the table is already in
4579
+					//the FROM statement, BUT the primary table isn't. So we want
4580
+					//to add the inverse join sql
4581
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4582
+				} else {
4583
+					//just add a regular JOIN to this table from the primary table
4584
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4585
+				}
4586
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4587
+		}
4588
+		return $SQL;
4589
+	}
4590
+
4591
+
4592
+
4593
+	/**
4594
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4595
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4596
+	 * their data type (eg, '%s', '%d', etc)
4597
+	 *
4598
+	 * @return array
4599
+	 */
4600
+	public function _get_data_types()
4601
+	{
4602
+		$data_types = array();
4603
+		foreach ($this->field_settings() as $field_obj) {
4604
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4605
+			/** @var $field_obj EE_Model_Field_Base */
4606
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4607
+		}
4608
+		return $data_types;
4609
+	}
4610
+
4611
+
4612
+
4613
+	/**
4614
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4615
+	 *
4616
+	 * @param string $model_name
4617
+	 * @throws EE_Error
4618
+	 * @return EEM_Base
4619
+	 */
4620
+	public function get_related_model_obj($model_name)
4621
+	{
4622
+		$model_classname = "EEM_" . $model_name;
4623
+		if (! class_exists($model_classname)) {
4624
+			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",
4625
+				'event_espresso'), $model_name, $model_classname));
4626
+		}
4627
+		return call_user_func($model_classname . "::instance");
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * Returns the array of EE_ModelRelations for this model.
4634
+	 *
4635
+	 * @return EE_Model_Relation_Base[]
4636
+	 */
4637
+	public function relation_settings()
4638
+	{
4639
+		return $this->_model_relations;
4640
+	}
4641
+
4642
+
4643
+
4644
+	/**
4645
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4646
+	 * because without THOSE models, this model probably doesn't have much purpose.
4647
+	 * (Eg, without an event, datetimes have little purpose.)
4648
+	 *
4649
+	 * @return EE_Belongs_To_Relation[]
4650
+	 */
4651
+	public function belongs_to_relations()
4652
+	{
4653
+		$belongs_to_relations = array();
4654
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4655
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4656
+				$belongs_to_relations[$model_name] = $relation_obj;
4657
+			}
4658
+		}
4659
+		return $belongs_to_relations;
4660
+	}
4661
+
4662
+
4663
+
4664
+	/**
4665
+	 * Returns the specified EE_Model_Relation, or throws an exception
4666
+	 *
4667
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4668
+	 * @throws EE_Error
4669
+	 * @return EE_Model_Relation_Base
4670
+	 */
4671
+	public function related_settings_for($relation_name)
4672
+	{
4673
+		$relatedModels = $this->relation_settings();
4674
+		if (! array_key_exists($relation_name, $relatedModels)) {
4675
+			throw new EE_Error(
4676
+				sprintf(
4677
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4678
+						'event_espresso'),
4679
+					$relation_name,
4680
+					$this->_get_class_name(),
4681
+					implode(', ', array_keys($relatedModels))
4682
+				)
4683
+			);
4684
+		}
4685
+		return $relatedModels[$relation_name];
4686
+	}
4687
+
4688
+
4689
+
4690
+	/**
4691
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4692
+	 * fields
4693
+	 *
4694
+	 * @param string $fieldName
4695
+	 * @param boolean $include_db_only_fields
4696
+	 * @throws EE_Error
4697
+	 * @return EE_Model_Field_Base
4698
+	 */
4699
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4700
+	{
4701
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4702
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4703
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4704
+				get_class($this)));
4705
+		}
4706
+		return $fieldSettings[$fieldName];
4707
+	}
4708
+
4709
+
4710
+
4711
+	/**
4712
+	 * Checks if this field exists on this model
4713
+	 *
4714
+	 * @param string $fieldName a key in the model's _field_settings array
4715
+	 * @return boolean
4716
+	 */
4717
+	public function has_field($fieldName)
4718
+	{
4719
+		$fieldSettings = $this->field_settings(true);
4720
+		if (isset($fieldSettings[$fieldName])) {
4721
+			return true;
4722
+		}
4723
+		return false;
4724
+	}
4725
+
4726
+
4727
+
4728
+	/**
4729
+	 * Returns whether or not this model has a relation to the specified model
4730
+	 *
4731
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4732
+	 * @return boolean
4733
+	 */
4734
+	public function has_relation($relation_name)
4735
+	{
4736
+		$relations = $this->relation_settings();
4737
+		if (isset($relations[$relation_name])) {
4738
+			return true;
4739
+		}
4740
+		return false;
4741
+	}
4742
+
4743
+
4744
+
4745
+	/**
4746
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747
+	 * Eg, on EE_Answer that would be ANS_ID field object
4748
+	 *
4749
+	 * @param $field_obj
4750
+	 * @return boolean
4751
+	 */
4752
+	public function is_primary_key_field($field_obj)
4753
+	{
4754
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4761
+	 * Eg, on EE_Answer that would be ANS_ID field object
4762
+	 *
4763
+	 * @return EE_Model_Field_Base
4764
+	 * @throws EE_Error
4765
+	 */
4766
+	public function get_primary_key_field()
4767
+	{
4768
+		if ($this->_primary_key_field === null) {
4769
+			foreach ($this->field_settings(true) as $field_obj) {
4770
+				if ($this->is_primary_key_field($field_obj)) {
4771
+					$this->_primary_key_field = $field_obj;
4772
+					break;
4773
+				}
4774
+			}
4775
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4776
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4777
+					get_class($this)));
4778
+			}
4779
+		}
4780
+		return $this->_primary_key_field;
4781
+	}
4782
+
4783
+
4784
+
4785
+	/**
4786
+	 * Returns whether or not not there is a primary key on this model.
4787
+	 * Internally does some caching.
4788
+	 *
4789
+	 * @return boolean
4790
+	 */
4791
+	public function has_primary_key_field()
4792
+	{
4793
+		if ($this->_has_primary_key_field === null) {
4794
+			try {
4795
+				$this->get_primary_key_field();
4796
+				$this->_has_primary_key_field = true;
4797
+			} catch (EE_Error $e) {
4798
+				$this->_has_primary_key_field = false;
4799
+			}
4800
+		}
4801
+		return $this->_has_primary_key_field;
4802
+	}
4803
+
4804
+
4805
+
4806
+	/**
4807
+	 * Finds the first field of type $field_class_name.
4808
+	 *
4809
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4810
+	 *                                 EE_Foreign_Key_Field, etc
4811
+	 * @return EE_Model_Field_Base or null if none is found
4812
+	 */
4813
+	public function get_a_field_of_type($field_class_name)
4814
+	{
4815
+		foreach ($this->field_settings() as $field) {
4816
+			if ($field instanceof $field_class_name) {
4817
+				return $field;
4818
+			}
4819
+		}
4820
+		return null;
4821
+	}
4822
+
4823
+
4824
+
4825
+	/**
4826
+	 * Gets a foreign key field pointing to model.
4827
+	 *
4828
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4829
+	 * @return EE_Foreign_Key_Field_Base
4830
+	 * @throws EE_Error
4831
+	 */
4832
+	public function get_foreign_key_to($model_name)
4833
+	{
4834
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4835
+			foreach ($this->field_settings() as $field) {
4836
+				if (
4837
+					$field instanceof EE_Foreign_Key_Field_Base
4838
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4839
+				) {
4840
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4841
+					break;
4842
+				}
4843
+			}
4844
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4845
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4846
+					'event_espresso'), $model_name, get_class($this)));
4847
+			}
4848
+		}
4849
+		return $this->_cache_foreign_key_to_fields[$model_name];
4850
+	}
4851
+
4852
+
4853
+
4854
+	/**
4855
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4856
+	 *
4857
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4858
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4859
+	 *                            Either one works
4860
+	 * @return string
4861
+	 */
4862
+	public function get_table_for_alias($table_alias)
4863
+	{
4864
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4865
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4866
+	}
4867
+
4868
+
4869
+
4870
+	/**
4871
+	 * Returns a flat array of all field son this model, instead of organizing them
4872
+	 * by table_alias as they are in the constructor.
4873
+	 *
4874
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4875
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4876
+	 */
4877
+	public function field_settings($include_db_only_fields = false)
4878
+	{
4879
+		if ($include_db_only_fields) {
4880
+			if ($this->_cached_fields === null) {
4881
+				$this->_cached_fields = array();
4882
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4883
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4884
+						$this->_cached_fields[$field_name] = $field_obj;
4885
+					}
4886
+				}
4887
+			}
4888
+			return $this->_cached_fields;
4889
+		}
4890
+		if ($this->_cached_fields_non_db_only === null) {
4891
+			$this->_cached_fields_non_db_only = array();
4892
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4893
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4894
+					/** @var $field_obj EE_Model_Field_Base */
4895
+					if (! $field_obj->is_db_only_field()) {
4896
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4897
+					}
4898
+				}
4899
+			}
4900
+		}
4901
+		return $this->_cached_fields_non_db_only;
4902
+	}
4903
+
4904
+
4905
+
4906
+	/**
4907
+	 *        cycle though array of attendees and create objects out of each item
4908
+	 *
4909
+	 * @access        private
4910
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4911
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4912
+	 *                           numerically indexed)
4913
+	 * @throws EE_Error
4914
+	 */
4915
+	protected function _create_objects($rows = array())
4916
+	{
4917
+		$array_of_objects = array();
4918
+		if (empty($rows)) {
4919
+			return array();
4920
+		}
4921
+		$count_if_model_has_no_primary_key = 0;
4922
+		$has_primary_key = $this->has_primary_key_field();
4923
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4924
+		foreach ((array)$rows as $row) {
4925
+			if (empty($row)) {
4926
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4927
+				return array();
4928
+			}
4929
+			//check if we've already set this object in the results array,
4930
+			//in which case there's no need to process it further (again)
4931
+			if ($has_primary_key) {
4932
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4933
+					$row,
4934
+					$primary_key_field->get_qualified_column(),
4935
+					$primary_key_field->get_table_column()
4936
+				);
4937
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4938
+					continue;
4939
+				}
4940
+			}
4941
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4942
+			if (! $classInstance) {
4943
+				throw new EE_Error(
4944
+					sprintf(
4945
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4946
+						$this->get_this_model_name(),
4947
+						http_build_query($row)
4948
+					)
4949
+				);
4950
+			}
4951
+			//set the timezone on the instantiated objects
4952
+			$classInstance->set_timezone($this->_timezone);
4953
+			//make sure if there is any timezone setting present that we set the timezone for the object
4954
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4955
+			$array_of_objects[$key] = $classInstance;
4956
+			//also, for all the relations of type BelongsTo, see if we can cache
4957
+			//those related models
4958
+			//(we could do this for other relations too, but if there are conditions
4959
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4960
+			//so it requires a little more thought than just caching them immediately...)
4961
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4962
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4963
+					//check if this model's INFO is present. If so, cache it on the model
4964
+					$other_model = $relation_obj->get_other_model();
4965
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4966
+					//if we managed to make a model object from the results, cache it on the main model object
4967
+					if ($other_model_obj_maybe) {
4968
+						//set timezone on these other model objects if they are present
4969
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4970
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4971
+					}
4972
+				}
4973
+			}
4974
+		}
4975
+		return $array_of_objects;
4976
+	}
4977
+
4978
+
4979
+
4980
+	/**
4981
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4982
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4983
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4984
+	 * object (as set in the model_field!).
4985
+	 *
4986
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4987
+	 */
4988
+	public function create_default_object()
4989
+	{
4990
+		$this_model_fields_and_values = array();
4991
+		//setup the row using default values;
4992
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4993
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4994
+		}
4995
+		$className = $this->_get_class_name();
4996
+		$classInstance = EE_Registry::instance()
4997
+									->load_class($className, array($this_model_fields_and_values), false, false);
4998
+		return $classInstance;
4999
+	}
5000
+
5001
+
5002
+
5003
+	/**
5004
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5005
+	 *                             or an stdClass where each property is the name of a column,
5006
+	 * @return EE_Base_Class
5007
+	 * @throws EE_Error
5008
+	 */
5009
+	public function instantiate_class_from_array_or_object($cols_n_values)
5010
+	{
5011
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5012
+			$cols_n_values = get_object_vars($cols_n_values);
5013
+		}
5014
+		$primary_key = null;
5015
+		//make sure the array only has keys that are fields/columns on this model
5016
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5017
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5018
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5019
+		}
5020
+		$className = $this->_get_class_name();
5021
+		//check we actually found results that we can use to build our model object
5022
+		//if not, return null
5023
+		if ($this->has_primary_key_field()) {
5024
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5025
+				return null;
5026
+			}
5027
+		} else if ($this->unique_indexes()) {
5028
+			$first_column = reset($this_model_fields_n_values);
5029
+			if (empty($first_column)) {
5030
+				return null;
5031
+			}
5032
+		}
5033
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034
+		if ($primary_key) {
5035
+			$classInstance = $this->get_from_entity_map($primary_key);
5036
+			if (! $classInstance) {
5037
+				$classInstance = EE_Registry::instance()
5038
+											->load_class($className,
5039
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5040
+				// add this new object to the entity map
5041
+				$classInstance = $this->add_to_entity_map($classInstance);
5042
+			}
5043
+		} else {
5044
+			$classInstance = EE_Registry::instance()
5045
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5046
+											true, false);
5047
+		}
5048
+		//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.
5049
+		$this->set_timezone($classInstance->get_timezone());
5050
+		return $classInstance;
5051
+	}
5052
+
5053
+
5054
+
5055
+	/**
5056
+	 * Gets the model object from the  entity map if it exists
5057
+	 *
5058
+	 * @param int|string $id the ID of the model object
5059
+	 * @return EE_Base_Class
5060
+	 */
5061
+	public function get_from_entity_map($id)
5062
+	{
5063
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5064
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5065
+	}
5066
+
5067
+
5068
+
5069
+	/**
5070
+	 * add_to_entity_map
5071
+	 * Adds the object to the model's entity mappings
5072
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5073
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5074
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5075
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5076
+	 *        then this method should be called immediately after the update query
5077
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5078
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5079
+	 *
5080
+	 * @param    EE_Base_Class $object
5081
+	 * @throws EE_Error
5082
+	 * @return \EE_Base_Class
5083
+	 */
5084
+	public function add_to_entity_map(EE_Base_Class $object)
5085
+	{
5086
+		$className = $this->_get_class_name();
5087
+		if (! $object instanceof $className) {
5088
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5089
+				is_object($object) ? get_class($object) : $object, $className));
5090
+		}
5091
+		/** @var $object EE_Base_Class */
5092
+		if (! $object->ID()) {
5093
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5094
+				"event_espresso"), get_class($this)));
5095
+		}
5096
+		// double check it's not already there
5097
+		$classInstance = $this->get_from_entity_map($object->ID());
5098
+		if ($classInstance) {
5099
+			return $classInstance;
5100
+		}
5101
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5102
+		return $object;
5103
+	}
5104
+
5105
+
5106
+
5107
+	/**
5108
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5109
+	 * if no identifier is provided, then the entire entity map is emptied
5110
+	 *
5111
+	 * @param int|string $id the ID of the model object
5112
+	 * @return boolean
5113
+	 */
5114
+	public function clear_entity_map($id = null)
5115
+	{
5116
+		if (empty($id)) {
5117
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5118
+			return true;
5119
+		}
5120
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5121
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5122
+			return true;
5123
+		}
5124
+		return false;
5125
+	}
5126
+
5127
+
5128
+
5129
+	/**
5130
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5131
+	 * Given an array where keys are column (or column alias) names and values,
5132
+	 * returns an array of their corresponding field names and database values
5133
+	 *
5134
+	 * @param array $cols_n_values
5135
+	 * @return array
5136
+	 */
5137
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5138
+	{
5139
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5140
+	}
5141
+
5142
+
5143
+
5144
+	/**
5145
+	 * _deduce_fields_n_values_from_cols_n_values
5146
+	 * Given an array where keys are column (or column alias) names and values,
5147
+	 * returns an array of their corresponding field names and database values
5148
+	 *
5149
+	 * @param string $cols_n_values
5150
+	 * @return array
5151
+	 */
5152
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5153
+	{
5154
+		$this_model_fields_n_values = array();
5155
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5156
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5157
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5158
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5159
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5160
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5161
+					if (! $field_obj->is_db_only_field()) {
5162
+						//prepare field as if its coming from db
5163
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5164
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5165
+					}
5166
+				}
5167
+			} else {
5168
+				//the table's rows existed. Use their values
5169
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5170
+					if (! $field_obj->is_db_only_field()) {
5171
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5172
+							$cols_n_values, $field_obj->get_qualified_column(),
5173
+							$field_obj->get_table_column()
5174
+						);
5175
+					}
5176
+				}
5177
+			}
5178
+		}
5179
+		return $this_model_fields_n_values;
5180
+	}
5181
+
5182
+
5183
+
5184
+	/**
5185
+	 * @param $cols_n_values
5186
+	 * @param $qualified_column
5187
+	 * @param $regular_column
5188
+	 * @return null
5189
+	 */
5190
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5191
+	{
5192
+		$value = null;
5193
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5194
+		//does the field on the model relate to this column retrieved from the db?
5195
+		//or is it a db-only field? (not relating to the model)
5196
+		if (isset($cols_n_values[$qualified_column])) {
5197
+			$value = $cols_n_values[$qualified_column];
5198
+		} elseif (isset($cols_n_values[$regular_column])) {
5199
+			$value = $cols_n_values[$regular_column];
5200
+		}
5201
+		return $value;
5202
+	}
5203
+
5204
+
5205
+
5206
+	/**
5207
+	 * refresh_entity_map_from_db
5208
+	 * Makes sure the model object in the entity map at $id assumes the values
5209
+	 * of the database (opposite of EE_base_Class::save())
5210
+	 *
5211
+	 * @param int|string $id
5212
+	 * @return EE_Base_Class
5213
+	 * @throws EE_Error
5214
+	 */
5215
+	public function refresh_entity_map_from_db($id)
5216
+	{
5217
+		$obj_in_map = $this->get_from_entity_map($id);
5218
+		if ($obj_in_map) {
5219
+			$wpdb_results = $this->_get_all_wpdb_results(
5220
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5221
+			);
5222
+			if ($wpdb_results && is_array($wpdb_results)) {
5223
+				$one_row = reset($wpdb_results);
5224
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5225
+					$obj_in_map->set_from_db($field_name, $db_value);
5226
+				}
5227
+				//clear the cache of related model objects
5228
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5229
+					$obj_in_map->clear_cache($relation_name, null, true);
5230
+				}
5231
+			}
5232
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5233
+			return $obj_in_map;
5234
+		}
5235
+		return $this->get_one_by_ID($id);
5236
+	}
5237
+
5238
+
5239
+
5240
+	/**
5241
+	 * refresh_entity_map_with
5242
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5243
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5244
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5245
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5246
+	 *
5247
+	 * @param int|string    $id
5248
+	 * @param EE_Base_Class $replacing_model_obj
5249
+	 * @return \EE_Base_Class
5250
+	 * @throws EE_Error
5251
+	 */
5252
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5253
+	{
5254
+		$obj_in_map = $this->get_from_entity_map($id);
5255
+		if ($obj_in_map) {
5256
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5257
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5258
+					$obj_in_map->set($field_name, $value);
5259
+				}
5260
+				//make the model object in the entity map's cache match the $replacing_model_obj
5261
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5262
+					$obj_in_map->clear_cache($relation_name, null, true);
5263
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5264
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5265
+					}
5266
+				}
5267
+			}
5268
+			return $obj_in_map;
5269
+		}
5270
+		$this->add_to_entity_map($replacing_model_obj);
5271
+		return $replacing_model_obj;
5272
+	}
5273
+
5274
+
5275
+
5276
+	/**
5277
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5278
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5279
+	 * require_once($this->_getClassName().".class.php");
5280
+	 *
5281
+	 * @return string
5282
+	 */
5283
+	private function _get_class_name()
5284
+	{
5285
+		return "EE_" . $this->get_this_model_name();
5286
+	}
5287
+
5288
+
5289
+
5290
+	/**
5291
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5292
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5293
+	 * it would be 'Events'.
5294
+	 *
5295
+	 * @param int $quantity
5296
+	 * @return string
5297
+	 */
5298
+	public function item_name($quantity = 1)
5299
+	{
5300
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5301
+	}
5302
+
5303
+
5304
+
5305
+	/**
5306
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5307
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5308
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5309
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5310
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5311
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5312
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5313
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5314
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5315
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5316
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5317
+	 *        return $previousReturnValue.$returnString;
5318
+	 * }
5319
+	 * require('EEM_Answer.model.php');
5320
+	 * $answer=EEM_Answer::instance();
5321
+	 * echo $answer->my_callback('monkeys',100);
5322
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5323
+	 *
5324
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5325
+	 * @param array  $args       array of original arguments passed to the function
5326
+	 * @throws EE_Error
5327
+	 * @return mixed whatever the plugin which calls add_filter decides
5328
+	 */
5329
+	public function __call($methodName, $args)
5330
+	{
5331
+		$className = get_class($this);
5332
+		$tagName = "FHEE__{$className}__{$methodName}";
5333
+		if (! has_filter($tagName)) {
5334
+			throw new EE_Error(
5335
+				sprintf(
5336
+					__('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 );',
5337
+						'event_espresso'),
5338
+					$methodName,
5339
+					$className,
5340
+					$tagName,
5341
+					'<br />'
5342
+				)
5343
+			);
5344
+		}
5345
+		return apply_filters($tagName, null, $this, $args);
5346
+	}
5347
+
5348
+
5349
+
5350
+	/**
5351
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5352
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5353
+	 *
5354
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5355
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5356
+	 *                                                       the object's class name
5357
+	 *                                                       or object's ID
5358
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5359
+	 *                                                       exists in the database. If it does not, we add it
5360
+	 * @throws EE_Error
5361
+	 * @return EE_Base_Class
5362
+	 */
5363
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5364
+	{
5365
+		$className = $this->_get_class_name();
5366
+		if ($base_class_obj_or_id instanceof $className) {
5367
+			$model_object = $base_class_obj_or_id;
5368
+		} else {
5369
+			$primary_key_field = $this->get_primary_key_field();
5370
+			if (
5371
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5372
+				&& (
5373
+					is_int($base_class_obj_or_id)
5374
+					|| is_string($base_class_obj_or_id)
5375
+				)
5376
+			) {
5377
+				// assume it's an ID.
5378
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5379
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5380
+			} else if (
5381
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5382
+				&& is_string($base_class_obj_or_id)
5383
+			) {
5384
+				// assume its a string representation of the object
5385
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5386
+			} else {
5387
+				throw new EE_Error(
5388
+					sprintf(
5389
+						__(
5390
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5391
+							'event_espresso'
5392
+						),
5393
+						$base_class_obj_or_id,
5394
+						$this->_get_class_name(),
5395
+						print_r($base_class_obj_or_id, true)
5396
+					)
5397
+				);
5398
+			}
5399
+		}
5400
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5401
+			$model_object->save();
5402
+		}
5403
+		return $model_object;
5404
+	}
5405
+
5406
+
5407
+
5408
+	/**
5409
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5410
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5411
+	 * returns it ID.
5412
+	 *
5413
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5414
+	 * @return int|string depending on the type of this model object's ID
5415
+	 * @throws EE_Error
5416
+	 */
5417
+	public function ensure_is_ID($base_class_obj_or_id)
5418
+	{
5419
+		$className = $this->_get_class_name();
5420
+		if ($base_class_obj_or_id instanceof $className) {
5421
+			/** @var $base_class_obj_or_id EE_Base_Class */
5422
+			$id = $base_class_obj_or_id->ID();
5423
+		} elseif (is_int($base_class_obj_or_id)) {
5424
+			//assume it's an ID
5425
+			$id = $base_class_obj_or_id;
5426
+		} elseif (is_string($base_class_obj_or_id)) {
5427
+			//assume its a string representation of the object
5428
+			$id = $base_class_obj_or_id;
5429
+		} else {
5430
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5431
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5432
+				print_r($base_class_obj_or_id, true)));
5433
+		}
5434
+		return $id;
5435
+	}
5436
+
5437
+
5438
+
5439
+	/**
5440
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5441
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5442
+	 * been sanitized and converted into the appropriate domain.
5443
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5444
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5445
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5446
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5447
+	 * $EVT = EEM_Event::instance(); $old_setting =
5448
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5449
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5450
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5451
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5452
+	 *
5453
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5454
+	 * @return void
5455
+	 */
5456
+	public function assume_values_already_prepared_by_model_object(
5457
+		$values_already_prepared = self::not_prepared_by_model_object
5458
+	) {
5459
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5460
+	}
5461
+
5462
+
5463
+
5464
+	/**
5465
+	 * Read comments for assume_values_already_prepared_by_model_object()
5466
+	 *
5467
+	 * @return int
5468
+	 */
5469
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5470
+	{
5471
+		return $this->_values_already_prepared_by_model_object;
5472
+	}
5473
+
5474
+
5475
+
5476
+	/**
5477
+	 * Gets all the indexes on this model
5478
+	 *
5479
+	 * @return EE_Index[]
5480
+	 */
5481
+	public function indexes()
5482
+	{
5483
+		return $this->_indexes;
5484
+	}
5485
+
5486
+
5487
+
5488
+	/**
5489
+	 * Gets all the Unique Indexes on this model
5490
+	 *
5491
+	 * @return EE_Unique_Index[]
5492
+	 */
5493
+	public function unique_indexes()
5494
+	{
5495
+		$unique_indexes = array();
5496
+		foreach ($this->_indexes as $name => $index) {
5497
+			if ($index instanceof EE_Unique_Index) {
5498
+				$unique_indexes [$name] = $index;
5499
+			}
5500
+		}
5501
+		return $unique_indexes;
5502
+	}
5503
+
5504
+
5505
+
5506
+	/**
5507
+	 * Gets all the fields which, when combined, make the primary key.
5508
+	 * This is usually just an array with 1 element (the primary key), but in cases
5509
+	 * where there is no primary key, it's a combination of fields as defined
5510
+	 * on a primary index
5511
+	 *
5512
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5513
+	 * @throws EE_Error
5514
+	 */
5515
+	public function get_combined_primary_key_fields()
5516
+	{
5517
+		foreach ($this->indexes() as $index) {
5518
+			if ($index instanceof EE_Primary_Key_Index) {
5519
+				return $index->fields();
5520
+			}
5521
+		}
5522
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5523
+	}
5524
+
5525
+
5526
+
5527
+	/**
5528
+	 * Used to build a primary key string (when the model has no primary key),
5529
+	 * which can be used a unique string to identify this model object.
5530
+	 *
5531
+	 * @param array $cols_n_values keys are field names, values are their values
5532
+	 * @return string
5533
+	 * @throws EE_Error
5534
+	 */
5535
+	public function get_index_primary_key_string($cols_n_values)
5536
+	{
5537
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5538
+			$this->get_combined_primary_key_fields());
5539
+		return http_build_query($cols_n_values_for_primary_key_index);
5540
+	}
5541
+
5542
+
5543
+
5544
+	/**
5545
+	 * Gets the field values from the primary key string
5546
+	 *
5547
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5548
+	 * @param string $index_primary_key_string
5549
+	 * @return null|array
5550
+	 * @throws EE_Error
5551
+	 */
5552
+	public function parse_index_primary_key_string($index_primary_key_string)
5553
+	{
5554
+		$key_fields = $this->get_combined_primary_key_fields();
5555
+		//check all of them are in the $id
5556
+		$key_vals_in_combined_pk = array();
5557
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5558
+		foreach ($key_fields as $key_field_name => $field_obj) {
5559
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5560
+				return null;
5561
+			}
5562
+		}
5563
+		return $key_vals_in_combined_pk;
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * verifies that an array of key-value pairs for model fields has a key
5570
+	 * for each field comprising the primary key index
5571
+	 *
5572
+	 * @param array $key_vals
5573
+	 * @return boolean
5574
+	 * @throws EE_Error
5575
+	 */
5576
+	public function has_all_combined_primary_key_fields($key_vals)
5577
+	{
5578
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5579
+		foreach ($keys_it_should_have as $key) {
5580
+			if (! isset($key_vals[$key])) {
5581
+				return false;
5582
+			}
5583
+		}
5584
+		return true;
5585
+	}
5586
+
5587
+
5588
+
5589
+	/**
5590
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5591
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5592
+	 *
5593
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5594
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5595
+	 * @throws EE_Error
5596
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5597
+	 *                                                              indexed)
5598
+	 */
5599
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5600
+	{
5601
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5602
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5603
+		} elseif (is_array($model_object_or_attributes_array)) {
5604
+			$attributes_array = $model_object_or_attributes_array;
5605
+		} else {
5606
+			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",
5607
+				"event_espresso"), $model_object_or_attributes_array));
5608
+		}
5609
+		//even copies obviously won't have the same ID, so remove the primary key
5610
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5611
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5612
+			unset($attributes_array[$this->primary_key_name()]);
5613
+		}
5614
+		if (isset($query_params[0])) {
5615
+			$query_params[0] = array_merge($attributes_array, $query_params);
5616
+		} else {
5617
+			$query_params[0] = $attributes_array;
5618
+		}
5619
+		return $this->get_all($query_params);
5620
+	}
5621
+
5622
+
5623
+
5624
+	/**
5625
+	 * Gets the first copy we find. See get_all_copies for more details
5626
+	 *
5627
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5628
+	 * @param array $query_params
5629
+	 * @return EE_Base_Class
5630
+	 * @throws EE_Error
5631
+	 */
5632
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5633
+	{
5634
+		if (! is_array($query_params)) {
5635
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5636
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5637
+					gettype($query_params)), '4.6.0');
5638
+			$query_params = array();
5639
+		}
5640
+		$query_params['limit'] = 1;
5641
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5642
+		if (is_array($copies)) {
5643
+			return array_shift($copies);
5644
+		}
5645
+		return null;
5646
+	}
5647
+
5648
+
5649
+
5650
+	/**
5651
+	 * Updates the item with the specified id. Ignores default query parameters because
5652
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5653
+	 *
5654
+	 * @param array      $fields_n_values keys are field names, values are their new values
5655
+	 * @param int|string $id              the value of the primary key to update
5656
+	 * @return int number of rows updated
5657
+	 * @throws EE_Error
5658
+	 */
5659
+	public function update_by_ID($fields_n_values, $id)
5660
+	{
5661
+		$query_params = array(
5662
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5663
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5664
+		);
5665
+		return $this->update($fields_n_values, $query_params);
5666
+	}
5667
+
5668
+
5669
+
5670
+	/**
5671
+	 * Changes an operator which was supplied to the models into one usable in SQL
5672
+	 *
5673
+	 * @param string $operator_supplied
5674
+	 * @return string an operator which can be used in SQL
5675
+	 * @throws EE_Error
5676
+	 */
5677
+	private function _prepare_operator_for_sql($operator_supplied)
5678
+	{
5679
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5680
+			: null;
5681
+		if ($sql_operator) {
5682
+			return $sql_operator;
5683
+		}
5684
+		throw new EE_Error(
5685
+			sprintf(
5686
+				__(
5687
+					"The operator '%s' is not in the list of valid operators: %s",
5688
+					"event_espresso"
5689
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5690
+			)
5691
+		);
5692
+	}
5693
+
5694
+
5695
+
5696
+	/**
5697
+	 * Gets the valid operators
5698
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5699
+	 */
5700
+	public function valid_operators(){
5701
+		return $this->_valid_operators;
5702
+	}
5703
+
5704
+
5705
+
5706
+	/**
5707
+	 * Gets the between-style operators (take 2 arguments).
5708
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5709
+	 */
5710
+	public function valid_between_style_operators()
5711
+	{
5712
+		return array_intersect(
5713
+			$this->valid_operators(),
5714
+			$this->_between_style_operators
5715
+		);
5716
+	}
5717
+
5718
+	/**
5719
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5720
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5721
+	 */
5722
+	public function valid_like_style_operators()
5723
+	{
5724
+		return array_intersect(
5725
+			$this->valid_operators(),
5726
+			$this->_like_style_operators
5727
+		);
5728
+	}
5729
+
5730
+	/**
5731
+	 * Gets the "in"-style operators
5732
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5733
+	 */
5734
+	public function valid_in_style_operators()
5735
+	{
5736
+		return array_intersect(
5737
+			$this->valid_operators(),
5738
+			$this->_in_style_operators
5739
+		);
5740
+	}
5741
+
5742
+	/**
5743
+	 * Gets the "null"-style operators (accept no arguments)
5744
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5745
+	 */
5746
+	public function valid_null_style_operators()
5747
+	{
5748
+		return array_intersect(
5749
+			$this->valid_operators(),
5750
+			$this->_null_style_operators
5751
+		);
5752
+	}
5753
+
5754
+	/**
5755
+	 * Gets an array where keys are the primary keys and values are their 'names'
5756
+	 * (as determined by the model object's name() function, which is often overridden)
5757
+	 *
5758
+	 * @param array $query_params like get_all's
5759
+	 * @return string[]
5760
+	 * @throws EE_Error
5761
+	 */
5762
+	public function get_all_names($query_params = array())
5763
+	{
5764
+		$objs = $this->get_all($query_params);
5765
+		$names = array();
5766
+		foreach ($objs as $obj) {
5767
+			$names[$obj->ID()] = $obj->name();
5768
+		}
5769
+		return $names;
5770
+	}
5771
+
5772
+
5773
+
5774
+	/**
5775
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5776
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5777
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5778
+	 * array_keys() on $model_objects.
5779
+	 *
5780
+	 * @param \EE_Base_Class[] $model_objects
5781
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5782
+	 *                                               in the returned array
5783
+	 * @return array
5784
+	 * @throws EE_Error
5785
+	 */
5786
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5787
+	{
5788
+		if (! $this->has_primary_key_field()) {
5789
+			if (WP_DEBUG) {
5790
+				EE_Error::add_error(
5791
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5792
+					__FILE__,
5793
+					__FUNCTION__,
5794
+					__LINE__
5795
+				);
5796
+			}
5797
+		}
5798
+		$IDs = array();
5799
+		foreach ($model_objects as $model_object) {
5800
+			$id = $model_object->ID();
5801
+			if (! $id) {
5802
+				if ($filter_out_empty_ids) {
5803
+					continue;
5804
+				}
5805
+				if (WP_DEBUG) {
5806
+					EE_Error::add_error(
5807
+						__(
5808
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5809
+							'event_espresso'
5810
+						),
5811
+						__FILE__,
5812
+						__FUNCTION__,
5813
+						__LINE__
5814
+					);
5815
+				}
5816
+			}
5817
+			$IDs[] = $id;
5818
+		}
5819
+		return $IDs;
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * Returns the string used in capabilities relating to this model. If there
5826
+	 * are no capabilities that relate to this model returns false
5827
+	 *
5828
+	 * @return string|false
5829
+	 */
5830
+	public function cap_slug()
5831
+	{
5832
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5833
+	}
5834
+
5835
+
5836
+
5837
+	/**
5838
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5839
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5840
+	 * only returns the cap restrictions array in that context (ie, the array
5841
+	 * at that key)
5842
+	 *
5843
+	 * @param string $context
5844
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5845
+	 * @throws EE_Error
5846
+	 */
5847
+	public function cap_restrictions($context = EEM_Base::caps_read)
5848
+	{
5849
+		EEM_Base::verify_is_valid_cap_context($context);
5850
+		//check if we ought to run the restriction generator first
5851
+		if (
5852
+			isset($this->_cap_restriction_generators[$context])
5853
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5854
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5855
+		) {
5856
+			$this->_cap_restrictions[$context] = array_merge(
5857
+				$this->_cap_restrictions[$context],
5858
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5859
+			);
5860
+		}
5861
+		//and make sure we've finalized the construction of each restriction
5862
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5863
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5864
+				$where_conditions_obj->_finalize_construct($this);
5865
+			}
5866
+		}
5867
+		return $this->_cap_restrictions[$context];
5868
+	}
5869
+
5870
+
5871
+
5872
+	/**
5873
+	 * Indicating whether or not this model thinks its a wp core model
5874
+	 *
5875
+	 * @return boolean
5876
+	 */
5877
+	public function is_wp_core_model()
5878
+	{
5879
+		return $this->_wp_core_model;
5880
+	}
5881
+
5882
+
5883
+
5884
+	/**
5885
+	 * Gets all the caps that are missing which impose a restriction on
5886
+	 * queries made in this context
5887
+	 *
5888
+	 * @param string $context one of EEM_Base::caps_ constants
5889
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5890
+	 * @throws EE_Error
5891
+	 */
5892
+	public function caps_missing($context = EEM_Base::caps_read)
5893
+	{
5894
+		$missing_caps = array();
5895
+		$cap_restrictions = $this->cap_restrictions($context);
5896
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5897
+			if (! EE_Capabilities::instance()
5898
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5899
+			) {
5900
+				$missing_caps[$cap] = $restriction_if_no_cap;
5901
+			}
5902
+		}
5903
+		return $missing_caps;
5904
+	}
5905
+
5906
+
5907
+
5908
+	/**
5909
+	 * Gets the mapping from capability contexts to action strings used in capability names
5910
+	 *
5911
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5912
+	 * one of 'read', 'edit', or 'delete'
5913
+	 */
5914
+	public function cap_contexts_to_cap_action_map()
5915
+	{
5916
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5917
+			$this);
5918
+	}
5919
+
5920
+
5921
+
5922
+	/**
5923
+	 * Gets the action string for the specified capability context
5924
+	 *
5925
+	 * @param string $context
5926
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5927
+	 * @throws EE_Error
5928
+	 */
5929
+	public function cap_action_for_context($context)
5930
+	{
5931
+		$mapping = $this->cap_contexts_to_cap_action_map();
5932
+		if (isset($mapping[$context])) {
5933
+			return $mapping[$context];
5934
+		}
5935
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5936
+			return $action;
5937
+		}
5938
+		throw new EE_Error(
5939
+			sprintf(
5940
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5941
+				$context,
5942
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5943
+			)
5944
+		);
5945
+	}
5946
+
5947
+
5948
+
5949
+	/**
5950
+	 * Returns all the capability contexts which are valid when querying models
5951
+	 *
5952
+	 * @return array
5953
+	 */
5954
+	public static function valid_cap_contexts()
5955
+	{
5956
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5957
+			self::caps_read,
5958
+			self::caps_read_admin,
5959
+			self::caps_edit,
5960
+			self::caps_delete,
5961
+		));
5962
+	}
5963
+
5964
+
5965
+
5966
+	/**
5967
+	 * Returns all valid options for 'default_where_conditions'
5968
+	 *
5969
+	 * @return array
5970
+	 */
5971
+	public static function valid_default_where_conditions()
5972
+	{
5973
+		return array(
5974
+			EEM_Base::default_where_conditions_all,
5975
+			EEM_Base::default_where_conditions_this_only,
5976
+			EEM_Base::default_where_conditions_others_only,
5977
+			EEM_Base::default_where_conditions_minimum_all,
5978
+			EEM_Base::default_where_conditions_minimum_others,
5979
+			EEM_Base::default_where_conditions_none
5980
+		);
5981
+	}
5982
+
5983
+	// public static function default_where_conditions_full
5984
+	/**
5985
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5986
+	 *
5987
+	 * @param string $context
5988
+	 * @return bool
5989
+	 * @throws EE_Error
5990
+	 */
5991
+	static public function verify_is_valid_cap_context($context)
5992
+	{
5993
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5994
+		if (in_array($context, $valid_cap_contexts)) {
5995
+			return true;
5996
+		}
5997
+		throw new EE_Error(
5998
+			sprintf(
5999
+				__(
6000
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6001
+					'event_espresso'
6002
+				),
6003
+				$context,
6004
+				'EEM_Base',
6005
+				implode(',', $valid_cap_contexts)
6006
+			)
6007
+		);
6008
+	}
6009
+
6010
+
6011
+
6012
+	/**
6013
+	 * Clears all the models field caches. This is only useful when a sub-class
6014
+	 * might have added a field or something and these caches might be invalidated
6015
+	 */
6016
+	protected function _invalidate_field_caches()
6017
+	{
6018
+		$this->_cache_foreign_key_to_fields = array();
6019
+		$this->_cached_fields = null;
6020
+		$this->_cached_fields_non_db_only = null;
6021
+	}
6022
+
6023
+
6024
+
6025
+	/**
6026
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6027
+	 * (eg "and", "or", "not").
6028
+	 *
6029
+	 * @return array
6030
+	 */
6031
+	public function logic_query_param_keys()
6032
+	{
6033
+		return $this->_logic_query_param_keys;
6034
+	}
6035
+
6036
+
6037
+
6038
+	/**
6039
+	 * Determines whether or not the where query param array key is for a logic query param.
6040
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6041
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6042
+	 *
6043
+	 * @param $query_param_key
6044
+	 * @return bool
6045
+	 */
6046
+	public function is_logic_query_param_key($query_param_key)
6047
+	{
6048
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6049
+			if ($query_param_key === $logic_query_param_key
6050
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6051
+			) {
6052
+				return true;
6053
+			}
6054
+		}
6055
+		return false;
6056
+	}
6057 6057
 
6058 6058
 
6059 6059
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -511,8 +511,8 @@  discard block
 block discarded – undo
511 511
     protected function __construct($timezone = null)
512 512
     {
513 513
         // check that the model has not been loaded too soon
514
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
-            throw new EE_Error (
514
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
515
+            throw new EE_Error(
516 516
                 sprintf(
517 517
                     __('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.',
518 518
                         'event_espresso'),
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
          *
533 533
          * @var EE_Table_Base[] $_tables
534 534
          */
535
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
536 536
         foreach ($this->_tables as $table_alias => $table_obj) {
537 537
             /** @var $table_obj EE_Table_Base */
538 538
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -547,10 +547,10 @@  discard block
 block discarded – undo
547 547
          *
548 548
          * @param EE_Model_Field_Base[] $_fields
549 549
          */
550
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
551 551
         $this->_invalidate_field_caches();
552 552
         foreach ($this->_fields as $table_alias => $fields_for_table) {
553
-            if (! array_key_exists($table_alias, $this->_tables)) {
553
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
554 554
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555 555
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
556 556
             }
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
          *
579 579
          * @param EE_Model_Relation_Base[] $_model_relations
580 580
          */
581
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
582 582
             $this->_model_relations);
583 583
         foreach ($this->_model_relations as $model_name => $relation_obj) {
584 584
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -590,12 +590,12 @@  discard block
 block discarded – undo
590 590
         }
591 591
         $this->set_timezone($timezone);
592 592
         //finalize default where condition strategy, or set default
593
-        if (! $this->_default_where_conditions_strategy) {
593
+        if ( ! $this->_default_where_conditions_strategy) {
594 594
             //nothing was set during child constructor, so set default
595 595
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596 596
         }
597 597
         $this->_default_where_conditions_strategy->_finalize_construct($this);
598
-        if (! $this->_minimum_where_conditions_strategy) {
598
+        if ( ! $this->_minimum_where_conditions_strategy) {
599 599
             //nothing was set during child constructor, so set default
600 600
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601 601
         }
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
         //initialize the standard cap restriction generators if none were specified by the child constructor
609 609
         if ($this->_cap_restriction_generators !== false) {
610 610
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
611
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
612 612
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
613 613
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614 614
                         new EE_Restriction_Generator_Protected(),
@@ -621,10 +621,10 @@  discard block
 block discarded – undo
621 621
         //if there are cap restriction generators, use them to make the default cap restrictions
622 622
         if ($this->_cap_restriction_generators !== false) {
623 623
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
-                if (! $generator_object) {
624
+                if ( ! $generator_object) {
625 625
                     continue;
626 626
                 }
627
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
627
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
628 628
                     throw new EE_Error(
629 629
                         sprintf(
630 630
                             __('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.',
@@ -635,12 +635,12 @@  discard block
 block discarded – undo
635 635
                     );
636 636
                 }
637 637
                 $action = $this->cap_action_for_context($context);
638
-                if (! $generator_object->construction_finalized()) {
638
+                if ( ! $generator_object->construction_finalized()) {
639 639
                     $generator_object->_construct_finalize($this, $action);
640 640
                 }
641 641
             }
642 642
         }
643
-        do_action('AHEE__' . get_class($this) . '__construct__end');
643
+        do_action('AHEE__'.get_class($this).'__construct__end');
644 644
     }
645 645
 
646 646
 
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
      */
654 654
     public static function set_model_query_blog_id($blog_id = 0)
655 655
     {
656
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
656
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
657 657
     }
658 658
 
659 659
 
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
     public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
689 689
     {
690 690
         // check if instance of Espresso_model already exists
691
-        if (! static::$_instance instanceof static) {
691
+        if ( ! static::$_instance instanceof static) {
692 692
             $model_field_factory = self::getModelFieldFactory($model_field_factory);
693 693
             // instantiate Espresso_model
694 694
             static::$_instance = new static($timezone, $model_field_factory);
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
             foreach ($r->getDefaultProperties() as $property => $value) {
743 743
                 //don't set instance to null like it was originally,
744 744
                 //but it's static anyways, and we're ignoring static properties (for now at least)
745
-                if (! isset($static_properties[$property])) {
745
+                if ( ! isset($static_properties[$property])) {
746 746
                     static::$_instance->{$property} = $value;
747 747
                 }
748 748
             }
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
      */
765 765
     private static function getLoader()
766 766
     {
767
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
767
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
768 768
             EEM_Base::$loader = LoaderFactory::getLoader();
769 769
         }
770 770
         return EEM_Base::$loader;
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
      */
785 785
     public function status_array($translated = false)
786 786
     {
787
-        if (! array_key_exists('Status', $this->_model_relations)) {
787
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
788 788
             return array();
789 789
         }
790 790
         $model_name = $this->get_this_model_name();
@@ -987,17 +987,17 @@  discard block
 block discarded – undo
987 987
     public function wp_user_field_name()
988 988
     {
989 989
         try {
990
-            if (! empty($this->_model_chain_to_wp_user)) {
990
+            if ( ! empty($this->_model_chain_to_wp_user)) {
991 991
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
992 992
                 $last_model_name = end($models_to_follow_to_wp_users);
993 993
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
994
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
994
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
995 995
             } else {
996 996
                 $model_with_fk_to_wp_users = $this;
997 997
                 $model_chain_to_wp_user = '';
998 998
             }
999 999
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1000
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1000
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
1001 1001
         } catch (EE_Error $e) {
1002 1002
             return false;
1003 1003
         }
@@ -1068,12 +1068,12 @@  discard block
 block discarded – undo
1068 1068
         // remember the custom selections, if any, and type cast as array
1069 1069
         // (unless $columns_to_select is an object, then just set as an empty array)
1070 1070
         // Note: (array) 'some string' === array( 'some string' )
1071
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1071
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1072 1072
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1073 1073
         $select_expressions = $columns_to_select !== null
1074 1074
             ? $this->_construct_select_from_input($columns_to_select)
1075 1075
             : $this->_construct_default_select_sql($model_query_info);
1076
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1076
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1077 1077
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1078 1078
     }
1079 1079
 
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
         if (is_array($columns_to_select)) {
1119 1119
             $select_sql_array = array();
1120 1120
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1121
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1121
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1122 1122
                     throw new EE_Error(
1123 1123
                         sprintf(
1124 1124
                             __(
@@ -1130,7 +1130,7 @@  discard block
 block discarded – undo
1130 1130
                         )
1131 1131
                     );
1132 1132
                 }
1133
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1133
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1134 1134
                     throw new EE_Error(
1135 1135
                         sprintf(
1136 1136
                             esc_html__(
@@ -1202,7 +1202,7 @@  discard block
 block discarded – undo
1202 1202
      */
1203 1203
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1204 1204
     {
1205
-        if (! isset($query_params[0])) {
1205
+        if ( ! isset($query_params[0])) {
1206 1206
             $query_params[0] = array();
1207 1207
         }
1208 1208
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
      */
1228 1228
     public function get_one($query_params = array())
1229 1229
     {
1230
-        if (! is_array($query_params)) {
1230
+        if ( ! is_array($query_params)) {
1231 1231
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1232 1232
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1233 1233
                     gettype($query_params)), '4.6.0');
@@ -1418,7 +1418,7 @@  discard block
 block discarded – undo
1418 1418
                 return array();
1419 1419
             }
1420 1420
         }
1421
-        if (! is_array($query_params)) {
1421
+        if ( ! is_array($query_params)) {
1422 1422
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1423 1423
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1424 1424
                     gettype($query_params)), '4.6.0');
@@ -1428,7 +1428,7 @@  discard block
 block discarded – undo
1428 1428
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1429 1429
         $query_params['limit'] = $limit;
1430 1430
         //set direction
1431
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1431
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1432 1432
         $query_params['order_by'] = $operand === '>'
1433 1433
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1434 1434
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1506,7 +1506,7 @@  discard block
 block discarded – undo
1506 1506
     {
1507 1507
         $field_settings = $this->field_settings_for($field_name);
1508 1508
         //if not a valid EE_Datetime_Field then throw error
1509
-        if (! $field_settings instanceof EE_Datetime_Field) {
1509
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1510 1510
             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.',
1511 1511
                 'event_espresso'), $field_name));
1512 1512
         }
@@ -1585,7 +1585,7 @@  discard block
 block discarded – undo
1585 1585
         //load EEH_DTT_Helper
1586 1586
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1587 1587
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1588
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1588
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1589 1589
     }
1590 1590
 
1591 1591
 
@@ -1653,7 +1653,7 @@  discard block
 block discarded – undo
1653 1653
      */
1654 1654
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1655 1655
     {
1656
-        if (! is_array($query_params)) {
1656
+        if ( ! is_array($query_params)) {
1657 1657
             EE_Error::doing_it_wrong('EEM_Base::update',
1658 1658
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1659 1659
                     gettype($query_params)), '4.6.0');
@@ -1675,7 +1675,7 @@  discard block
 block discarded – undo
1675 1675
          * @param EEM_Base $model           the model being queried
1676 1676
          * @param array    $query_params    see EEM_Base::get_all()
1677 1677
          */
1678
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1678
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1679 1679
             $query_params);
1680 1680
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1681 1681
         //to do that, for each table, verify that it's PK isn't null.
@@ -1689,7 +1689,7 @@  discard block
 block discarded – undo
1689 1689
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1690 1690
         foreach ($wpdb_select_results as $wpdb_result) {
1691 1691
             // type cast stdClass as array
1692
-            $wpdb_result = (array)$wpdb_result;
1692
+            $wpdb_result = (array) $wpdb_result;
1693 1693
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1694 1694
             if ($this->has_primary_key_field()) {
1695 1695
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1706,13 +1706,13 @@  discard block
 block discarded – undo
1706 1706
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1707 1707
                     //if there is no private key for this table on the results, it means there's no entry
1708 1708
                     //in this table, right? so insert a row in the current table, using any fields available
1709
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1709
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1710 1710
                            && $wpdb_result[$this_table_pk_column])
1711 1711
                     ) {
1712 1712
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1713 1713
                             $main_table_pk_value);
1714 1714
                         //if we died here, report the error
1715
-                        if (! $success) {
1715
+                        if ( ! $success) {
1716 1716
                             return false;
1717 1717
                         }
1718 1718
                     }
@@ -1743,7 +1743,7 @@  discard block
 block discarded – undo
1743 1743
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1744 1744
                 }
1745 1745
             }
1746
-            if (! $model_objs_affected_ids) {
1746
+            if ( ! $model_objs_affected_ids) {
1747 1747
                 //wait wait wait- if nothing was affected let's stop here
1748 1748
                 return 0;
1749 1749
             }
@@ -1770,7 +1770,7 @@  discard block
 block discarded – undo
1770 1770
                . $model_query_info->get_full_join_sql()
1771 1771
                . " SET "
1772 1772
                . $this->_construct_update_sql($fields_n_values)
1773
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1773
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1774 1774
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1775 1775
         /**
1776 1776
          * Action called after a model update call has been made.
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
          * @param int      $rows_affected
1782 1782
          */
1783 1783
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1784
-        return $rows_affected;//how many supposedly got updated
1784
+        return $rows_affected; //how many supposedly got updated
1785 1785
     }
1786 1786
 
1787 1787
 
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
         }
1810 1810
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1811 1811
         $select_expressions = $field->get_qualified_column();
1812
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1812
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1813 1813
         return $this->_do_wpdb_query('get_col', array($SQL));
1814 1814
     }
1815 1815
 
@@ -1827,7 +1827,7 @@  discard block
 block discarded – undo
1827 1827
     {
1828 1828
         $query_params['limit'] = 1;
1829 1829
         $col = $this->get_col($query_params, $field_to_select);
1830
-        if (! empty($col)) {
1830
+        if ( ! empty($col)) {
1831 1831
             return reset($col);
1832 1832
         }
1833 1833
         return null;
@@ -1858,7 +1858,7 @@  discard block
 block discarded – undo
1858 1858
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1859 1859
             $value_sql = $prepared_value === null ? 'NULL'
1860 1860
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1861
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1861
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1862 1862
         }
1863 1863
         return implode(",", $cols_n_values);
1864 1864
     }
@@ -2040,7 +2040,7 @@  discard block
 block discarded – undo
2040 2040
          * @param int      $rows_deleted
2041 2041
          */
2042 2042
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2043
-        return $rows_deleted;//how many supposedly got deleted
2043
+        return $rows_deleted; //how many supposedly got deleted
2044 2044
     }
2045 2045
 
2046 2046
 
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2191 2191
                 //make sure we have unique $ids
2192 2192
                 $ids = array_unique($ids);
2193
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2193
+                $query[] = $column.' IN('.implode(',', $ids).')';
2194 2194
             }
2195 2195
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2196 2196
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2198,9 +2198,9 @@  discard block
 block discarded – undo
2198 2198
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2199 2199
                 $values_for_each_combined_primary_key_for_a_row = array();
2200 2200
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2201
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2201
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2202 2202
                 }
2203
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2203
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2204 2204
             }
2205 2205
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2206 2206
         }
@@ -2216,8 +2216,8 @@  discard block
 block discarded – undo
2216 2216
      */
2217 2217
     public function get_field_by_column($qualified_column_name)
2218 2218
     {
2219
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2220
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2219
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2220
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2221 2221
                return $field_obj;
2222 2222
            }
2223 2223
        }
@@ -2268,9 +2268,9 @@  discard block
 block discarded – undo
2268 2268
                 $column_to_count = '*';
2269 2269
             }
2270 2270
         }
2271
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2272
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2273
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2271
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2272
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2273
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2274 2274
     }
2275 2275
 
2276 2276
 
@@ -2292,14 +2292,14 @@  discard block
 block discarded – undo
2292 2292
             $field_obj = $this->get_primary_key_field();
2293 2293
         }
2294 2294
         $column_to_count = $field_obj->get_qualified_column();
2295
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2295
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2296 2296
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2297 2297
         $data_type = $field_obj->get_wpdb_data_type();
2298 2298
         if ($data_type === '%d' || $data_type === '%s') {
2299
-            return (float)$return_value;
2299
+            return (float) $return_value;
2300 2300
         }
2301 2301
         //must be %f
2302
-        return (float)$return_value;
2302
+        return (float) $return_value;
2303 2303
     }
2304 2304
 
2305 2305
 
@@ -2319,13 +2319,13 @@  discard block
 block discarded – undo
2319 2319
         //if we're in maintenance mode level 2, DON'T run any queries
2320 2320
         //because level 2 indicates the database needs updating and
2321 2321
         //is probably out of sync with the code
2322
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2322
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2323 2323
             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.",
2324 2324
                 "event_espresso")));
2325 2325
         }
2326 2326
         /** @type WPDB $wpdb */
2327 2327
         global $wpdb;
2328
-        if (! method_exists($wpdb, $wpdb_method)) {
2328
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2329 2329
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2330 2330
                 'event_espresso'), $wpdb_method));
2331 2331
         }
@@ -2337,7 +2337,7 @@  discard block
 block discarded – undo
2337 2337
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2338 2338
         if (WP_DEBUG) {
2339 2339
             $wpdb->show_errors($old_show_errors_value);
2340
-            if (! empty($wpdb->last_error)) {
2340
+            if ( ! empty($wpdb->last_error)) {
2341 2341
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2342 2342
             }
2343 2343
             if ($result === false) {
@@ -2398,7 +2398,7 @@  discard block
 block discarded – undo
2398 2398
                     return $result;
2399 2399
                     break;
2400 2400
             }
2401
-            if (! empty($error_message)) {
2401
+            if ( ! empty($error_message)) {
2402 2402
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2403 2403
                 trigger_error($error_message);
2404 2404
             }
@@ -2474,11 +2474,11 @@  discard block
 block discarded – undo
2474 2474
      */
2475 2475
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476 2476
     {
2477
-        return " FROM " . $model_query_info->get_full_join_sql() .
2478
-               $model_query_info->get_where_sql() .
2479
-               $model_query_info->get_group_by_sql() .
2480
-               $model_query_info->get_having_sql() .
2481
-               $model_query_info->get_order_by_sql() .
2477
+        return " FROM ".$model_query_info->get_full_join_sql().
2478
+               $model_query_info->get_where_sql().
2479
+               $model_query_info->get_group_by_sql().
2480
+               $model_query_info->get_having_sql().
2481
+               $model_query_info->get_order_by_sql().
2482 2482
                $model_query_info->get_limit_sql();
2483 2483
     }
2484 2484
 
@@ -2674,12 +2674,12 @@  discard block
 block discarded – undo
2674 2674
         $related_model = $this->get_related_model_obj($model_name);
2675 2675
         //we're just going to use the query params on the related model's normal get_all query,
2676 2676
         //except add a condition to say to match the current mod
2677
-        if (! isset($query_params['default_where_conditions'])) {
2677
+        if ( ! isset($query_params['default_where_conditions'])) {
2678 2678
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679 2679
         }
2680 2680
         $this_model_name = $this->get_this_model_name();
2681 2681
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2682
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2683 2683
         return $related_model->count($query_params, $field_to_count, $distinct);
2684 2684
     }
2685 2685
 
@@ -2699,7 +2699,7 @@  discard block
 block discarded – undo
2699 2699
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700 2700
     {
2701 2701
         $related_model = $this->get_related_model_obj($model_name);
2702
-        if (! is_array($query_params)) {
2702
+        if ( ! is_array($query_params)) {
2703 2703
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2704 2704
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2705 2705
                     gettype($query_params)), '4.6.0');
@@ -2707,12 +2707,12 @@  discard block
 block discarded – undo
2707 2707
         }
2708 2708
         //we're just going to use the query params on the related model's normal get_all query,
2709 2709
         //except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2710
+        if ( ! isset($query_params['default_where_conditions'])) {
2711 2711
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712 2712
         }
2713 2713
         $this_model_name = $this->get_this_model_name();
2714 2714
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2715
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2716 2716
         return $related_model->sum($query_params, $field_to_sum);
2717 2717
     }
2718 2718
 
@@ -2765,7 +2765,7 @@  discard block
 block discarded – undo
2765 2765
                 $field_with_model_name = $field;
2766 2766
             }
2767 2767
         }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2768
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2769 2769
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770 2770
                 $this->get_this_model_name()));
2771 2771
         }
@@ -2798,7 +2798,7 @@  discard block
 block discarded – undo
2798 2798
          * @param array    $fields_n_values keys are the fields and values are their new values
2799 2799
          * @param EEM_Base $model           the model used
2800 2800
          */
2801
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2801
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802 2802
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2803 2803
             $main_table = $this->_get_main_table();
2804 2804
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2905,7 +2905,7 @@  discard block
 block discarded – undo
2905 2905
         }
2906 2906
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907 2907
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2908
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2909 2909
         }
2910 2910
         //if there is nothing to base this search on, then we shouldn't find anything
2911 2911
         if (empty($query_params)) {
@@ -2991,7 +2991,7 @@  discard block
 block discarded – undo
2991 2991
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2992 2992
             //so add the fk to the main table as a column
2993 2993
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2994
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2994
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2995 2995
         }
2996 2996
         //insert the new entry
2997 2997
         $result = $this->_do_wpdb_query('insert',
@@ -3195,7 +3195,7 @@  discard block
 block discarded – undo
3195 3195
                     $query_info_carrier,
3196 3196
                     'group_by'
3197 3197
                 );
3198
-            } elseif (! empty ($query_params['group_by'])) {
3198
+            } elseif ( ! empty ($query_params['group_by'])) {
3199 3199
                 $this->_extract_related_model_info_from_query_param(
3200 3200
                     $query_params['group_by'],
3201 3201
                     $query_info_carrier,
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
                     $query_info_carrier,
3218 3218
                     'order_by'
3219 3219
                 );
3220
-            } elseif (! empty($query_params['order_by'])) {
3220
+            } elseif ( ! empty($query_params['order_by'])) {
3221 3221
                 $this->_extract_related_model_info_from_query_param(
3222 3222
                     $query_params['order_by'],
3223 3223
                     $query_info_carrier,
@@ -3252,8 +3252,8 @@  discard block
 block discarded – undo
3252 3252
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253 3253
         $query_param_type
3254 3254
     ) {
3255
-        if (! empty($sub_query_params)) {
3256
-            $sub_query_params = (array)$sub_query_params;
3255
+        if ( ! empty($sub_query_params)) {
3256
+            $sub_query_params = (array) $sub_query_params;
3257 3257
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258 3258
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259 3259
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3264,7 +3264,7 @@  discard block
 block discarded – undo
3264 3264
                 //of array('Registration.TXN_ID'=>23)
3265 3265
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3266 3266
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3267
-                    if (! is_array($possibly_array_of_params)) {
3267
+                    if ( ! is_array($possibly_array_of_params)) {
3268 3268
                         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'))",
3269 3269
                             "event_espresso"),
3270 3270
                             $param, $possibly_array_of_params));
@@ -3281,7 +3281,7 @@  discard block
 block discarded – undo
3281 3281
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3282 3282
                     //indicating that $possible_array_of_params[1] is actually a field name,
3283 3283
                     //from which we should extract query parameters!
3284
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3284
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3285 3285
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3286 3286
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3287 3287
                     }
@@ -3311,8 +3311,8 @@  discard block
 block discarded – undo
3311 3311
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312 3312
         $query_param_type
3313 3313
     ) {
3314
-        if (! empty($sub_query_params)) {
3315
-            if (! is_array($sub_query_params)) {
3314
+        if ( ! empty($sub_query_params)) {
3315
+            if ( ! is_array($sub_query_params)) {
3316 3316
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3317 3317
                     $sub_query_params));
3318 3318
             }
@@ -3341,7 +3341,7 @@  discard block
 block discarded – undo
3341 3341
      */
3342 3342
     public function _create_model_query_info_carrier($query_params)
3343 3343
     {
3344
-        if (! is_array($query_params)) {
3344
+        if ( ! is_array($query_params)) {
3345 3345
             EE_Error::doing_it_wrong(
3346 3346
                 'EEM_Base::_create_model_query_info_carrier',
3347 3347
                 sprintf(
@@ -3417,7 +3417,7 @@  discard block
 block discarded – undo
3417 3417
         //set limit
3418 3418
         if (array_key_exists('limit', $query_params)) {
3419 3419
             if (is_array($query_params['limit'])) {
3420
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3420
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3421 3421
                     $e = sprintf(
3422 3422
                         __(
3423 3423
                             "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)",
@@ -3425,12 +3425,12 @@  discard block
 block discarded – undo
3425 3425
                         ),
3426 3426
                         http_build_query($query_params['limit'])
3427 3427
                     );
3428
-                    throw new EE_Error($e . "|" . $e);
3428
+                    throw new EE_Error($e."|".$e);
3429 3429
                 }
3430 3430
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3431
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3432
-            } elseif (! empty ($query_params['limit'])) {
3433
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3431
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3432
+            } elseif ( ! empty ($query_params['limit'])) {
3433
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3434 3434
             }
3435 3435
         }
3436 3436
         //set order by
@@ -3462,10 +3462,10 @@  discard block
 block discarded – undo
3462 3462
                 $order_array = array();
3463 3463
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3464 3464
                     $order = $this->_extract_order($order);
3465
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3465
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3466 3466
                 }
3467
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3468
-            } elseif (! empty ($query_params['order_by'])) {
3467
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3468
+            } elseif ( ! empty ($query_params['order_by'])) {
3469 3469
                 $this->_extract_related_model_info_from_query_param(
3470 3470
                     $query_params['order_by'],
3471 3471
                     $query_object,
@@ -3476,18 +3476,18 @@  discard block
 block discarded – undo
3476 3476
                     ? $this->_extract_order($query_params['order'])
3477 3477
                     : 'DESC';
3478 3478
                 $query_object->set_order_by_sql(
3479
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3479
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3480 3480
                 );
3481 3481
             }
3482 3482
         }
3483 3483
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3484
-        if (! array_key_exists('order_by', $query_params)
3484
+        if ( ! array_key_exists('order_by', $query_params)
3485 3485
             && array_key_exists('order', $query_params)
3486 3486
             && ! empty($query_params['order'])
3487 3487
         ) {
3488 3488
             $pk_field = $this->get_primary_key_field();
3489 3489
             $order = $this->_extract_order($query_params['order']);
3490
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3490
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3491 3491
         }
3492 3492
         //set group by
3493 3493
         if (array_key_exists('group_by', $query_params)) {
@@ -3497,10 +3497,10 @@  discard block
 block discarded – undo
3497 3497
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3498 3498
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3499 3499
                 }
3500
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3501
-            } elseif (! empty ($query_params['group_by'])) {
3500
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3501
+            } elseif ( ! empty ($query_params['group_by'])) {
3502 3502
                 $query_object->set_group_by_sql(
3503
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3503
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3504 3504
                 );
3505 3505
             }
3506 3506
         }
@@ -3510,7 +3510,7 @@  discard block
 block discarded – undo
3510 3510
         }
3511 3511
         //now, just verify they didn't pass anything wack
3512 3512
         foreach ($query_params as $query_key => $query_value) {
3513
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3513
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3514 3514
                 throw new EE_Error(
3515 3515
                     sprintf(
3516 3516
                         __(
@@ -3609,22 +3609,22 @@  discard block
 block discarded – undo
3609 3609
         $where_query_params = array()
3610 3610
     ) {
3611 3611
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3612
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3612
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3613 3613
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3614 3614
                 "event_espresso"), $use_default_where_conditions,
3615 3615
                 implode(", ", $allowed_used_default_where_conditions_values)));
3616 3616
         }
3617 3617
         $universal_query_params = array();
3618
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3618
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3619 3619
             $universal_query_params = $this->_get_default_where_conditions();
3620
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3620
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3621 3621
             $universal_query_params = $this->_get_minimum_where_conditions();
3622 3622
         }
3623 3623
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3624 3624
             $related_model = $this->get_related_model_obj($model_name);
3625
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3625
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3626 3626
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3627
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3627
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3628 3628
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3629 3629
             } else {
3630 3630
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3657,7 +3657,7 @@  discard block
 block discarded – undo
3657 3657
      * @param bool $for_this_model false means this is for OTHER related models
3658 3658
      * @return bool
3659 3659
      */
3660
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3660
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3661 3661
     {
3662 3662
         return (
3663 3663
                    $for_this_model
@@ -3736,7 +3736,7 @@  discard block
 block discarded – undo
3736 3736
     ) {
3737 3737
         $null_friendly_where_conditions = array();
3738 3738
         $none_overridden = true;
3739
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3739
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3740 3740
         foreach ($default_where_conditions as $key => $val) {
3741 3741
             if (isset($provided_where_conditions[$key])) {
3742 3742
                 $none_overridden = false;
@@ -3854,7 +3854,7 @@  discard block
 block discarded – undo
3854 3854
             foreach ($tables as $table_obj) {
3855 3855
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3856 3856
                                        . $table_obj->get_fully_qualified_pk_column();
3857
-                if (! in_array($qualified_pk_column, $selects)) {
3857
+                if ( ! in_array($qualified_pk_column, $selects)) {
3858 3858
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3859 3859
                 }
3860 3860
             }
@@ -3948,9 +3948,9 @@  discard block
 block discarded – undo
3948 3948
         //and
3949 3949
         //check if it's a field on a related model
3950 3950
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3951
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3951
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3952 3952
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3953
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3953
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3954 3954
                 if ($query_param === '') {
3955 3955
                     //nothing left to $query_param
3956 3956
                     //we should actually end in a field name, not a model like this!
@@ -4042,7 +4042,7 @@  discard block
 block discarded – undo
4042 4042
     {
4043 4043
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4044 4044
         if ($SQL) {
4045
-            return " WHERE " . $SQL;
4045
+            return " WHERE ".$SQL;
4046 4046
         }
4047 4047
         return '';
4048 4048
     }
@@ -4061,7 +4061,7 @@  discard block
 block discarded – undo
4061 4061
     {
4062 4062
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4063 4063
         if ($SQL) {
4064
-            return " HAVING " . $SQL;
4064
+            return " HAVING ".$SQL;
4065 4065
         }
4066 4066
         return '';
4067 4067
     }
@@ -4080,7 +4080,7 @@  discard block
 block discarded – undo
4080 4080
     {
4081 4081
         $where_clauses = array();
4082 4082
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4083
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4083
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4084 4084
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4085 4085
                 switch ($query_param) {
4086 4086
                     case 'not':
@@ -4108,7 +4108,7 @@  discard block
 block discarded – undo
4108 4108
             } else {
4109 4109
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4110 4110
                 //if it's not a normal field, maybe it's a custom selection?
4111
-                if (! $field_obj) {
4111
+                if ( ! $field_obj) {
4112 4112
                     if (isset($this->_custom_selections[$query_param][1])) {
4113 4113
                         $field_obj = $this->_custom_selections[$query_param][1];
4114 4114
                     } else {
@@ -4117,7 +4117,7 @@  discard block
 block discarded – undo
4117 4117
                     }
4118 4118
                 }
4119 4119
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4120
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4120
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4121 4121
             }
4122 4122
         }
4123 4123
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4138,7 +4138,7 @@  discard block
 block discarded – undo
4138 4138
         if ($field) {
4139 4139
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4140 4140
                 $query_param);
4141
-            return $table_alias_prefix . $field->get_qualified_column();
4141
+            return $table_alias_prefix.$field->get_qualified_column();
4142 4142
         }
4143 4143
         if (array_key_exists($query_param, $this->_custom_selections)) {
4144 4144
             //maybe it's custom selection item?
@@ -4190,7 +4190,7 @@  discard block
 block discarded – undo
4190 4190
     {
4191 4191
         if (is_array($op_and_value)) {
4192 4192
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4193
-            if (! $operator) {
4193
+            if ( ! $operator) {
4194 4194
                 $php_array_like_string = array();
4195 4195
                 foreach ($op_and_value as $key => $value) {
4196 4196
                     $php_array_like_string[] = "$key=>$value";
@@ -4212,14 +4212,14 @@  discard block
 block discarded – undo
4212 4212
         }
4213 4213
         //check to see if the value is actually another field
4214 4214
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4215
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4215
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4216 4216
         }
4217 4217
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4218 4218
             //in this case, the value should be an array, or at least a comma-separated list
4219 4219
             //it will need to handle a little differently
4220 4220
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4221 4221
             //note: $cleaned_value has already been run through $wpdb->prepare()
4222
-            return $operator . SP . $cleaned_value;
4222
+            return $operator.SP.$cleaned_value;
4223 4223
         }
4224 4224
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4225 4225
             //the value should be an array with count of two.
@@ -4235,7 +4235,7 @@  discard block
 block discarded – undo
4235 4235
                 );
4236 4236
             }
4237 4237
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4238
-            return $operator . SP . $cleaned_value;
4238
+            return $operator.SP.$cleaned_value;
4239 4239
         }
4240 4240
         if (in_array($operator, $this->valid_null_style_operators())) {
4241 4241
             if ($value !== null) {
@@ -4255,10 +4255,10 @@  discard block
 block discarded – undo
4255 4255
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4256 4256
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4257 4257
             //remove other junk. So just treat it as a string.
4258
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4258
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4259 4259
         }
4260
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4261
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4260
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4261
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4262 4262
         }
4263 4263
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4264 4264
             throw new EE_Error(
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
                 )
4273 4273
             );
4274 4274
         }
4275
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4275
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4276 4276
             throw new EE_Error(
4277 4277
                 sprintf(
4278 4278
                     __(
@@ -4312,7 +4312,7 @@  discard block
 block discarded – undo
4312 4312
         foreach ($values as $value) {
4313 4313
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4314 4314
         }
4315
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4315
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4316 4316
     }
4317 4317
 
4318 4318
 
@@ -4353,7 +4353,7 @@  discard block
 block discarded – undo
4353 4353
                                 . $main_table->get_table_name()
4354 4354
                                 . " WHERE FALSE";
4355 4355
         }
4356
-        return "(" . implode(",", $cleaned_values) . ")";
4356
+        return "(".implode(",", $cleaned_values).")";
4357 4357
     }
4358 4358
 
4359 4359
 
@@ -4372,7 +4372,7 @@  discard block
 block discarded – undo
4372 4372
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4373 4373
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4374 4374
         } //$field_obj should really just be a data type
4375
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4375
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4376 4376
             throw new EE_Error(
4377 4377
                 sprintf(
4378 4378
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4500,10 +4500,10 @@  discard block
 block discarded – undo
4500 4500
      */
4501 4501
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4502 4502
     {
4503
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4503
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4504 4504
         $qualified_columns = array();
4505 4505
         foreach ($this->field_settings() as $field_name => $field) {
4506
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4506
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4507 4507
         }
4508 4508
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4509 4509
     }
@@ -4527,11 +4527,11 @@  discard block
 block discarded – undo
4527 4527
             if ($table_obj instanceof EE_Primary_Table) {
4528 4528
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4529 4529
                     ? $table_obj->get_select_join_limit($limit)
4530
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4530
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4531 4531
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4532 4532
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4533 4533
                     ? $table_obj->get_select_join_limit_join($limit)
4534
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4534
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4535 4535
             }
4536 4536
         }
4537 4537
         return $SQL;
@@ -4619,12 +4619,12 @@  discard block
 block discarded – undo
4619 4619
      */
4620 4620
     public function get_related_model_obj($model_name)
4621 4621
     {
4622
-        $model_classname = "EEM_" . $model_name;
4623
-        if (! class_exists($model_classname)) {
4622
+        $model_classname = "EEM_".$model_name;
4623
+        if ( ! class_exists($model_classname)) {
4624 4624
             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",
4625 4625
                 'event_espresso'), $model_name, $model_classname));
4626 4626
         }
4627
-        return call_user_func($model_classname . "::instance");
4627
+        return call_user_func($model_classname."::instance");
4628 4628
     }
4629 4629
 
4630 4630
 
@@ -4671,7 +4671,7 @@  discard block
 block discarded – undo
4671 4671
     public function related_settings_for($relation_name)
4672 4672
     {
4673 4673
         $relatedModels = $this->relation_settings();
4674
-        if (! array_key_exists($relation_name, $relatedModels)) {
4674
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4675 4675
             throw new EE_Error(
4676 4676
                 sprintf(
4677 4677
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4699,7 +4699,7 @@  discard block
 block discarded – undo
4699 4699
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4700 4700
     {
4701 4701
         $fieldSettings = $this->field_settings($include_db_only_fields);
4702
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4702
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4703 4703
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4704 4704
                 get_class($this)));
4705 4705
         }
@@ -4772,7 +4772,7 @@  discard block
 block discarded – undo
4772 4772
                     break;
4773 4773
                 }
4774 4774
             }
4775
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4775
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4776 4776
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4777 4777
                     get_class($this)));
4778 4778
             }
@@ -4831,7 +4831,7 @@  discard block
 block discarded – undo
4831 4831
      */
4832 4832
     public function get_foreign_key_to($model_name)
4833 4833
     {
4834
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4834
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4835 4835
             foreach ($this->field_settings() as $field) {
4836 4836
                 if (
4837 4837
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4841,7 +4841,7 @@  discard block
 block discarded – undo
4841 4841
                     break;
4842 4842
                 }
4843 4843
             }
4844
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4844
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4845 4845
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4846 4846
                     'event_espresso'), $model_name, get_class($this)));
4847 4847
             }
@@ -4892,7 +4892,7 @@  discard block
 block discarded – undo
4892 4892
             foreach ($this->_fields as $fields_corresponding_to_table) {
4893 4893
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4894 4894
                     /** @var $field_obj EE_Model_Field_Base */
4895
-                    if (! $field_obj->is_db_only_field()) {
4895
+                    if ( ! $field_obj->is_db_only_field()) {
4896 4896
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4897 4897
                     }
4898 4898
                 }
@@ -4921,7 +4921,7 @@  discard block
 block discarded – undo
4921 4921
         $count_if_model_has_no_primary_key = 0;
4922 4922
         $has_primary_key = $this->has_primary_key_field();
4923 4923
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4924
-        foreach ((array)$rows as $row) {
4924
+        foreach ((array) $rows as $row) {
4925 4925
             if (empty($row)) {
4926 4926
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4927 4927
                 return array();
@@ -4939,7 +4939,7 @@  discard block
 block discarded – undo
4939 4939
                 }
4940 4940
             }
4941 4941
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4942
-            if (! $classInstance) {
4942
+            if ( ! $classInstance) {
4943 4943
                 throw new EE_Error(
4944 4944
                     sprintf(
4945 4945
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5008,7 +5008,7 @@  discard block
 block discarded – undo
5008 5008
      */
5009 5009
     public function instantiate_class_from_array_or_object($cols_n_values)
5010 5010
     {
5011
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5011
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5012 5012
             $cols_n_values = get_object_vars($cols_n_values);
5013 5013
         }
5014 5014
         $primary_key = null;
@@ -5033,7 +5033,7 @@  discard block
 block discarded – undo
5033 5033
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034 5034
         if ($primary_key) {
5035 5035
             $classInstance = $this->get_from_entity_map($primary_key);
5036
-            if (! $classInstance) {
5036
+            if ( ! $classInstance) {
5037 5037
                 $classInstance = EE_Registry::instance()
5038 5038
                                             ->load_class($className,
5039 5039
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5084,12 +5084,12 @@  discard block
 block discarded – undo
5084 5084
     public function add_to_entity_map(EE_Base_Class $object)
5085 5085
     {
5086 5086
         $className = $this->_get_class_name();
5087
-        if (! $object instanceof $className) {
5087
+        if ( ! $object instanceof $className) {
5088 5088
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5089 5089
                 is_object($object) ? get_class($object) : $object, $className));
5090 5090
         }
5091 5091
         /** @var $object EE_Base_Class */
5092
-        if (! $object->ID()) {
5092
+        if ( ! $object->ID()) {
5093 5093
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5094 5094
                 "event_espresso"), get_class($this)));
5095 5095
         }
@@ -5158,7 +5158,7 @@  discard block
 block discarded – undo
5158 5158
             //there is a primary key on this table and its not set. Use defaults for all its columns
5159 5159
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5160 5160
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5161
-                    if (! $field_obj->is_db_only_field()) {
5161
+                    if ( ! $field_obj->is_db_only_field()) {
5162 5162
                         //prepare field as if its coming from db
5163 5163
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5164 5164
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5167,7 +5167,7 @@  discard block
 block discarded – undo
5167 5167
             } else {
5168 5168
                 //the table's rows existed. Use their values
5169 5169
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5170
-                    if (! $field_obj->is_db_only_field()) {
5170
+                    if ( ! $field_obj->is_db_only_field()) {
5171 5171
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5172 5172
                             $cols_n_values, $field_obj->get_qualified_column(),
5173 5173
                             $field_obj->get_table_column()
@@ -5282,7 +5282,7 @@  discard block
 block discarded – undo
5282 5282
      */
5283 5283
     private function _get_class_name()
5284 5284
     {
5285
-        return "EE_" . $this->get_this_model_name();
5285
+        return "EE_".$this->get_this_model_name();
5286 5286
     }
5287 5287
 
5288 5288
 
@@ -5297,7 +5297,7 @@  discard block
 block discarded – undo
5297 5297
      */
5298 5298
     public function item_name($quantity = 1)
5299 5299
     {
5300
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5300
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5301 5301
     }
5302 5302
 
5303 5303
 
@@ -5330,7 +5330,7 @@  discard block
 block discarded – undo
5330 5330
     {
5331 5331
         $className = get_class($this);
5332 5332
         $tagName = "FHEE__{$className}__{$methodName}";
5333
-        if (! has_filter($tagName)) {
5333
+        if ( ! has_filter($tagName)) {
5334 5334
             throw new EE_Error(
5335 5335
                 sprintf(
5336 5336
                     __('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 );',
@@ -5556,7 +5556,7 @@  discard block
 block discarded – undo
5556 5556
         $key_vals_in_combined_pk = array();
5557 5557
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5558 5558
         foreach ($key_fields as $key_field_name => $field_obj) {
5559
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5559
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5560 5560
                 return null;
5561 5561
             }
5562 5562
         }
@@ -5577,7 +5577,7 @@  discard block
 block discarded – undo
5577 5577
     {
5578 5578
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5579 5579
         foreach ($keys_it_should_have as $key) {
5580
-            if (! isset($key_vals[$key])) {
5580
+            if ( ! isset($key_vals[$key])) {
5581 5581
                 return false;
5582 5582
             }
5583 5583
         }
@@ -5631,7 +5631,7 @@  discard block
 block discarded – undo
5631 5631
      */
5632 5632
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5633 5633
     {
5634
-        if (! is_array($query_params)) {
5634
+        if ( ! is_array($query_params)) {
5635 5635
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5636 5636
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5637 5637
                     gettype($query_params)), '4.6.0');
@@ -5697,7 +5697,7 @@  discard block
 block discarded – undo
5697 5697
      * Gets the valid operators
5698 5698
      * @return array keys are accepted strings, values are the SQL they are converted to
5699 5699
      */
5700
-    public function valid_operators(){
5700
+    public function valid_operators() {
5701 5701
         return $this->_valid_operators;
5702 5702
     }
5703 5703
 
@@ -5785,7 +5785,7 @@  discard block
 block discarded – undo
5785 5785
      */
5786 5786
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5787 5787
     {
5788
-        if (! $this->has_primary_key_field()) {
5788
+        if ( ! $this->has_primary_key_field()) {
5789 5789
             if (WP_DEBUG) {
5790 5790
                 EE_Error::add_error(
5791 5791
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5798,7 +5798,7 @@  discard block
 block discarded – undo
5798 5798
         $IDs = array();
5799 5799
         foreach ($model_objects as $model_object) {
5800 5800
             $id = $model_object->ID();
5801
-            if (! $id) {
5801
+            if ( ! $id) {
5802 5802
                 if ($filter_out_empty_ids) {
5803 5803
                     continue;
5804 5804
                 }
@@ -5894,8 +5894,8 @@  discard block
 block discarded – undo
5894 5894
         $missing_caps = array();
5895 5895
         $cap_restrictions = $this->cap_restrictions($context);
5896 5896
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5897
-            if (! EE_Capabilities::instance()
5898
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5897
+            if ( ! EE_Capabilities::instance()
5898
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5899 5899
             ) {
5900 5900
                 $missing_caps[$cap] = $restriction_if_no_cap;
5901 5901
             }
@@ -6047,7 +6047,7 @@  discard block
 block discarded – undo
6047 6047
     {
6048 6048
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6049 6049
             if ($query_param_key === $logic_query_param_key
6050
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6050
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6051 6051
             ) {
6052 6052
                 return true;
6053 6053
             }
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 2 patches
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\services\orm\ModelFieldFactory;
4 4
 
5 5
 if (! defined('EVENT_ESPRESSO_VERSION')) {
6
-    exit('No direct script access allowed');
6
+	exit('No direct script access allowed');
7 7
 }
8 8
 
9 9
 
@@ -19,128 +19,128 @@  discard block
 block discarded – undo
19 19
 class EEM_WP_User extends EEM_Base
20 20
 {
21 21
 
22
-    /**
23
-     * private instance of the EEM_WP_User object
24
-     *
25
-     * @type EEM_WP_User
26
-     */
27
-    protected static $_instance;
28
-
29
-
30
-
31
-    /**
32
-     *    constructor
33
-     *
34
-     * @param null              $timezone
35
-     * @param ModelFieldFactory $model_field_factory
36
-     * @throws EE_Error
37
-     * @throws InvalidArgumentException
38
-     */
39
-    protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
40
-    {
41
-        $this->singular_item = __('WP_User', 'event_espresso');
42
-        $this->plural_item = __('WP_Users', 'event_espresso');
43
-        global $wpdb;
44
-        $this->_tables = array(
45
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
46
-        );
47
-        $this->_fields = array(
48
-            'WP_User' => array(
49
-                'ID'                  => $model_field_factory->createPrimaryKeyIntField(
50
-                    'ID',
51
-                    __('WP_User ID', 'event_espresso')
52
-                ),
53
-                'user_login'          => $model_field_factory->createPlainTextField(
54
-                    'user_login',
55
-                    __('User Login', 'event_espresso'),
56
-                    false
57
-                ),
58
-                'user_pass'           => $model_field_factory->createPlainTextField(
59
-                    'user_pass',
60
-                    __('User Password', 'event_espresso'),
61
-                    false
62
-                ),
63
-                'user_nicename'       => $model_field_factory->createPlainTextField(
64
-                    'user_nicename',
65
-                    __(' User Nice Name', 'event_espresso'),
66
-                    false
67
-                ),
68
-                'user_email'          => $model_field_factory->createEmailField(
69
-                    'user_email',
70
-                    __('User Email', 'event_espresso'),
71
-                    false,
72
-                    null
73
-                ),
74
-                'user_registered'     => $model_field_factory->createDatetimeField(
75
-                    'user_registered',
76
-                    __('Date User Registered', 'event_espresso'),
77
-                    $timezone
78
-                ),
79
-                'user_activation_key' => $model_field_factory->createPlainTextField(
80
-                    'user_activation_key',
81
-                    __('User Activation Key', 'event_espresso'),
82
-                    false
83
-                ),
84
-                'user_status'         => $model_field_factory->createIntegerField(
85
-                    'user_status',
86
-                    __('User Status', 'event_espresso')
87
-                ),
88
-                'display_name'        => $model_field_factory->createPlainTextField(
89
-                    'display_name',
90
-                    __('Display Name', 'event_espresso'),
91
-                    false
92
-                ),
93
-            ),
94
-        );
95
-        $this->_model_relations = array(
96
-            'Attendee'       => new EE_Has_Many_Relation(),
97
-            // all models are related to the change log
98
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
99
-            'Event'          => new EE_Has_Many_Relation(),
100
-            'Payment_Method' => new EE_Has_Many_Relation(),
101
-            'Price'          => new EE_Has_Many_Relation(),
102
-            'Price_Type'     => new EE_Has_Many_Relation(),
103
-            'Question'       => new EE_Has_Many_Relation(),
104
-            'Question_Group' => new EE_Has_Many_Relation(),
105
-            'Ticket'         => new EE_Has_Many_Relation(),
106
-            'Venue'          => new EE_Has_Many_Relation(),
107
-            'Message'        => new EE_Has_Many_Relation(),
108
-        );
109
-        $this->_wp_core_model = true;
110
-        $this->_caps_slug = 'users';
111
-        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read] = 'list';
112
-        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read_admin] = 'list';
113
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
114
-            $this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_WP_User();
115
-        }
116
-        //@todo: account for create_users controls whether they can create users at all
117
-        parent::__construct($timezone);
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * We don't need a foreign key to the WP_User model, we just need its primary key
124
-     *
125
-     * @return string
126
-     * @throws EE_Error
127
-     */
128
-    public function wp_user_field_name()
129
-    {
130
-        return $this->primary_key_name();
131
-    }
132
-
133
-
134
-
135
-    /**
136
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
-     *
138
-     * @return boolean
139
-     */
140
-    public function is_owned()
141
-    {
142
-        return true;
143
-    }
22
+	/**
23
+	 * private instance of the EEM_WP_User object
24
+	 *
25
+	 * @type EEM_WP_User
26
+	 */
27
+	protected static $_instance;
28
+
29
+
30
+
31
+	/**
32
+	 *    constructor
33
+	 *
34
+	 * @param null              $timezone
35
+	 * @param ModelFieldFactory $model_field_factory
36
+	 * @throws EE_Error
37
+	 * @throws InvalidArgumentException
38
+	 */
39
+	protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
40
+	{
41
+		$this->singular_item = __('WP_User', 'event_espresso');
42
+		$this->plural_item = __('WP_Users', 'event_espresso');
43
+		global $wpdb;
44
+		$this->_tables = array(
45
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
46
+		);
47
+		$this->_fields = array(
48
+			'WP_User' => array(
49
+				'ID'                  => $model_field_factory->createPrimaryKeyIntField(
50
+					'ID',
51
+					__('WP_User ID', 'event_espresso')
52
+				),
53
+				'user_login'          => $model_field_factory->createPlainTextField(
54
+					'user_login',
55
+					__('User Login', 'event_espresso'),
56
+					false
57
+				),
58
+				'user_pass'           => $model_field_factory->createPlainTextField(
59
+					'user_pass',
60
+					__('User Password', 'event_espresso'),
61
+					false
62
+				),
63
+				'user_nicename'       => $model_field_factory->createPlainTextField(
64
+					'user_nicename',
65
+					__(' User Nice Name', 'event_espresso'),
66
+					false
67
+				),
68
+				'user_email'          => $model_field_factory->createEmailField(
69
+					'user_email',
70
+					__('User Email', 'event_espresso'),
71
+					false,
72
+					null
73
+				),
74
+				'user_registered'     => $model_field_factory->createDatetimeField(
75
+					'user_registered',
76
+					__('Date User Registered', 'event_espresso'),
77
+					$timezone
78
+				),
79
+				'user_activation_key' => $model_field_factory->createPlainTextField(
80
+					'user_activation_key',
81
+					__('User Activation Key', 'event_espresso'),
82
+					false
83
+				),
84
+				'user_status'         => $model_field_factory->createIntegerField(
85
+					'user_status',
86
+					__('User Status', 'event_espresso')
87
+				),
88
+				'display_name'        => $model_field_factory->createPlainTextField(
89
+					'display_name',
90
+					__('Display Name', 'event_espresso'),
91
+					false
92
+				),
93
+			),
94
+		);
95
+		$this->_model_relations = array(
96
+			'Attendee'       => new EE_Has_Many_Relation(),
97
+			// all models are related to the change log
98
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
99
+			'Event'          => new EE_Has_Many_Relation(),
100
+			'Payment_Method' => new EE_Has_Many_Relation(),
101
+			'Price'          => new EE_Has_Many_Relation(),
102
+			'Price_Type'     => new EE_Has_Many_Relation(),
103
+			'Question'       => new EE_Has_Many_Relation(),
104
+			'Question_Group' => new EE_Has_Many_Relation(),
105
+			'Ticket'         => new EE_Has_Many_Relation(),
106
+			'Venue'          => new EE_Has_Many_Relation(),
107
+			'Message'        => new EE_Has_Many_Relation(),
108
+		);
109
+		$this->_wp_core_model = true;
110
+		$this->_caps_slug = 'users';
111
+		$this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read] = 'list';
112
+		$this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read_admin] = 'list';
113
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
114
+			$this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_WP_User();
115
+		}
116
+		//@todo: account for create_users controls whether they can create users at all
117
+		parent::__construct($timezone);
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
124
+	 *
125
+	 * @return string
126
+	 * @throws EE_Error
127
+	 */
128
+	public function wp_user_field_name()
129
+	{
130
+		return $this->primary_key_name();
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
+	 *
138
+	 * @return boolean
139
+	 */
140
+	public function is_owned()
141
+	{
142
+		return true;
143
+	}
144 144
 
145 145
 
146 146
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@
 block discarded – undo
2 2
 
3 3
 use EventEspresso\core\services\orm\ModelFieldFactory;
4 4
 
5
-if (! defined('EVENT_ESPRESSO_VERSION')) {
5
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
6 6
     exit('No direct script access allowed');
7 7
 }
8 8
 
Please login to merge, or discard this patch.
core/EE_Error.core.php 1 patch
Indentation   +1095 added lines, -1095 removed lines patch added patch discarded remove patch
@@ -5,8 +5,8 @@  discard block
 block discarded – undo
5 5
 // if you're a dev and want to receive all errors via email
6 6
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
7 7
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
8
-    set_error_handler(array('EE_Error', 'error_handler'));
9
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
8
+	set_error_handler(array('EE_Error', 'error_handler'));
9
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
10 10
 }
11 11
 
12 12
 
@@ -23,259 +23,259 @@  discard block
 block discarded – undo
23 23
 {
24 24
 
25 25
 
26
-    /**
27
-     *    name of the file to log exceptions to
28
-     *
29
-     * @var string
30
-     */
31
-    private static $_exception_log_file = 'espresso_error_log.txt';
32
-
33
-    /**
34
-     *    stores details for all exception
35
-     *
36
-     * @var array
37
-     */
38
-    private static $_all_exceptions = array();
39
-
40
-    /**
41
-     *    tracks number of errors
42
-     *
43
-     * @var int
44
-     */
45
-    private static $_error_count = 0;
46
-
47
-    /**
48
-     *    has shutdown action been added ?
49
-     *
50
-     * @var array $_espresso_notices
51
-     */
52
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
53
-
54
-
55
-
56
-    /**
57
-     * @override default exception handling
58
-     * @param string         $message
59
-     * @param int            $code
60
-     * @param Exception|null $previous
61
-     */
62
-    public function __construct($message, $code = 0, Exception $previous = null)
63
-    {
64
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
65
-            parent::__construct($message, $code);
66
-        } else {
67
-            parent::__construct($message, $code, $previous);
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     *    error_handler
75
-     *
76
-     * @param $code
77
-     * @param $message
78
-     * @param $file
79
-     * @param $line
80
-     * @return void
81
-     */
82
-    public static function error_handler($code, $message, $file, $line)
83
-    {
84
-        $type = EE_Error::error_type($code);
85
-        $site = site_url();
86
-        switch ($site) {
87
-            case 'http://ee4.eventespresso.com/' :
88
-            case 'http://ee4decaf.eventespresso.com/' :
89
-            case 'http://ee4hf.eventespresso.com/' :
90
-            case 'http://ee4a.eventespresso.com/' :
91
-            case 'http://ee4ad.eventespresso.com/' :
92
-            case 'http://ee4b.eventespresso.com/' :
93
-            case 'http://ee4bd.eventespresso.com/' :
94
-            case 'http://ee4d.eventespresso.com/' :
95
-            case 'http://ee4dd.eventespresso.com/' :
96
-                $to = '[email protected]';
97
-                break;
98
-            default :
99
-                $to = get_option('admin_email');
100
-        }
101
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
102
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
103
-        if (function_exists('wp_mail')) {
104
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
105
-            wp_mail($to, $subject, $msg);
106
-        }
107
-        echo '<div id="message" class="espresso-notices error"><p>';
108
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
109
-        echo '<br /></p></div>';
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * error_type
116
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
117
-     *
118
-     * @param $code
119
-     * @return string
120
-     */
121
-    public static function error_type($code)
122
-    {
123
-        switch ($code) {
124
-            case E_ERROR: // 1 //
125
-                return 'E_ERROR';
126
-            case E_WARNING: // 2 //
127
-                return 'E_WARNING';
128
-            case E_PARSE: // 4 //
129
-                return 'E_PARSE';
130
-            case E_NOTICE: // 8 //
131
-                return 'E_NOTICE';
132
-            case E_CORE_ERROR: // 16 //
133
-                return 'E_CORE_ERROR';
134
-            case E_CORE_WARNING: // 32 //
135
-                return 'E_CORE_WARNING';
136
-            case E_COMPILE_ERROR: // 64 //
137
-                return 'E_COMPILE_ERROR';
138
-            case E_COMPILE_WARNING: // 128 //
139
-                return 'E_COMPILE_WARNING';
140
-            case E_USER_ERROR: // 256 //
141
-                return 'E_USER_ERROR';
142
-            case E_USER_WARNING: // 512 //
143
-                return 'E_USER_WARNING';
144
-            case E_USER_NOTICE: // 1024 //
145
-                return 'E_USER_NOTICE';
146
-            case E_STRICT: // 2048 //
147
-                return 'E_STRICT';
148
-            case E_RECOVERABLE_ERROR: // 4096 //
149
-                return 'E_RECOVERABLE_ERROR';
150
-            case E_DEPRECATED: // 8192 //
151
-                return 'E_DEPRECATED';
152
-            case E_USER_DEPRECATED: // 16384 //
153
-                return 'E_USER_DEPRECATED';
154
-            case E_ALL: // 16384 //
155
-                return 'E_ALL';
156
-        }
157
-        return '';
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     *    fatal_error_handler
164
-     *
165
-     * @return void
166
-     */
167
-    public static function fatal_error_handler()
168
-    {
169
-        $last_error = error_get_last();
170
-        if ($last_error['type'] === E_ERROR) {
171
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
172
-        }
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * _format_error
179
-     *
180
-     * @param $code
181
-     * @param $message
182
-     * @param $file
183
-     * @param $line
184
-     * @return string
185
-     */
186
-    private static function _format_error($code, $message, $file, $line)
187
-    {
188
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
-        $html .= '</tbody></table>';
194
-        return $html;
195
-    }
196
-
197
-
198
-
199
-    /**
200
-     * set_content_type
201
-     *
202
-     * @param $content_type
203
-     * @return string
204
-     */
205
-    public static function set_content_type($content_type)
206
-    {
207
-        return 'text/html';
208
-    }
209
-
210
-
211
-
212
-    /**
213
-     * @return void
214
-     * @throws EE_Error
215
-     * @throws ReflectionException
216
-     */
217
-    public function get_error()
218
-    {
219
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
220
-            throw $this;
221
-        }
222
-        // get separate user and developer messages if they exist
223
-        $msg = explode('||', $this->getMessage());
224
-        $user_msg = $msg[0];
225
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
226
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
227
-        // add details to _all_exceptions array
228
-        $x_time = time();
229
-        self::$_all_exceptions[$x_time]['name'] = get_class($this);
230
-        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
231
-        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
232
-        self::$_all_exceptions[$x_time]['msg'] = $msg;
233
-        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
234
-        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
235
-        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
236
-        self::$_error_count++;
237
-        //add_action( 'shutdown', array( $this, 'display_errors' ));
238
-        $this->display_errors();
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     *    has_error
245
-     *
246
-     * @param bool   $check_stored
247
-     * @param string $type_to_check
248
-     * @return bool
249
-     */
250
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
251
-    {
252
-        $has_error = isset(self::$_espresso_notices[$type_to_check])
253
-                     && ! empty(self::$_espresso_notices[$type_to_check])
254
-            ? true
255
-            : false;
256
-        if ($check_stored && ! $has_error) {
257
-            $notices = (array)get_option('ee_notices', array());
258
-            foreach ($notices as $type => $notice) {
259
-                if ($type === $type_to_check && $notice) {
260
-                    return true;
261
-                }
262
-            }
263
-        }
264
-        return $has_error;
265
-    }
266
-
267
-
268
-
269
-    /**
270
-     *    display_errors
271
-     *
272
-     * @echo   string
273
-     * @throws \ReflectionException
274
-     */
275
-    public function display_errors()
276
-    {
277
-        $trace_details = '';
278
-        $output = '
26
+	/**
27
+	 *    name of the file to log exceptions to
28
+	 *
29
+	 * @var string
30
+	 */
31
+	private static $_exception_log_file = 'espresso_error_log.txt';
32
+
33
+	/**
34
+	 *    stores details for all exception
35
+	 *
36
+	 * @var array
37
+	 */
38
+	private static $_all_exceptions = array();
39
+
40
+	/**
41
+	 *    tracks number of errors
42
+	 *
43
+	 * @var int
44
+	 */
45
+	private static $_error_count = 0;
46
+
47
+	/**
48
+	 *    has shutdown action been added ?
49
+	 *
50
+	 * @var array $_espresso_notices
51
+	 */
52
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
53
+
54
+
55
+
56
+	/**
57
+	 * @override default exception handling
58
+	 * @param string         $message
59
+	 * @param int            $code
60
+	 * @param Exception|null $previous
61
+	 */
62
+	public function __construct($message, $code = 0, Exception $previous = null)
63
+	{
64
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
65
+			parent::__construct($message, $code);
66
+		} else {
67
+			parent::__construct($message, $code, $previous);
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 *    error_handler
75
+	 *
76
+	 * @param $code
77
+	 * @param $message
78
+	 * @param $file
79
+	 * @param $line
80
+	 * @return void
81
+	 */
82
+	public static function error_handler($code, $message, $file, $line)
83
+	{
84
+		$type = EE_Error::error_type($code);
85
+		$site = site_url();
86
+		switch ($site) {
87
+			case 'http://ee4.eventespresso.com/' :
88
+			case 'http://ee4decaf.eventespresso.com/' :
89
+			case 'http://ee4hf.eventespresso.com/' :
90
+			case 'http://ee4a.eventespresso.com/' :
91
+			case 'http://ee4ad.eventespresso.com/' :
92
+			case 'http://ee4b.eventespresso.com/' :
93
+			case 'http://ee4bd.eventespresso.com/' :
94
+			case 'http://ee4d.eventespresso.com/' :
95
+			case 'http://ee4dd.eventespresso.com/' :
96
+				$to = '[email protected]';
97
+				break;
98
+			default :
99
+				$to = get_option('admin_email');
100
+		}
101
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
102
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
103
+		if (function_exists('wp_mail')) {
104
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
105
+			wp_mail($to, $subject, $msg);
106
+		}
107
+		echo '<div id="message" class="espresso-notices error"><p>';
108
+		echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
109
+		echo '<br /></p></div>';
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * error_type
116
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
117
+	 *
118
+	 * @param $code
119
+	 * @return string
120
+	 */
121
+	public static function error_type($code)
122
+	{
123
+		switch ($code) {
124
+			case E_ERROR: // 1 //
125
+				return 'E_ERROR';
126
+			case E_WARNING: // 2 //
127
+				return 'E_WARNING';
128
+			case E_PARSE: // 4 //
129
+				return 'E_PARSE';
130
+			case E_NOTICE: // 8 //
131
+				return 'E_NOTICE';
132
+			case E_CORE_ERROR: // 16 //
133
+				return 'E_CORE_ERROR';
134
+			case E_CORE_WARNING: // 32 //
135
+				return 'E_CORE_WARNING';
136
+			case E_COMPILE_ERROR: // 64 //
137
+				return 'E_COMPILE_ERROR';
138
+			case E_COMPILE_WARNING: // 128 //
139
+				return 'E_COMPILE_WARNING';
140
+			case E_USER_ERROR: // 256 //
141
+				return 'E_USER_ERROR';
142
+			case E_USER_WARNING: // 512 //
143
+				return 'E_USER_WARNING';
144
+			case E_USER_NOTICE: // 1024 //
145
+				return 'E_USER_NOTICE';
146
+			case E_STRICT: // 2048 //
147
+				return 'E_STRICT';
148
+			case E_RECOVERABLE_ERROR: // 4096 //
149
+				return 'E_RECOVERABLE_ERROR';
150
+			case E_DEPRECATED: // 8192 //
151
+				return 'E_DEPRECATED';
152
+			case E_USER_DEPRECATED: // 16384 //
153
+				return 'E_USER_DEPRECATED';
154
+			case E_ALL: // 16384 //
155
+				return 'E_ALL';
156
+		}
157
+		return '';
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 *    fatal_error_handler
164
+	 *
165
+	 * @return void
166
+	 */
167
+	public static function fatal_error_handler()
168
+	{
169
+		$last_error = error_get_last();
170
+		if ($last_error['type'] === E_ERROR) {
171
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
172
+		}
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * _format_error
179
+	 *
180
+	 * @param $code
181
+	 * @param $message
182
+	 * @param $file
183
+	 * @param $line
184
+	 * @return string
185
+	 */
186
+	private static function _format_error($code, $message, $file, $line)
187
+	{
188
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
+		$html .= '</tbody></table>';
194
+		return $html;
195
+	}
196
+
197
+
198
+
199
+	/**
200
+	 * set_content_type
201
+	 *
202
+	 * @param $content_type
203
+	 * @return string
204
+	 */
205
+	public static function set_content_type($content_type)
206
+	{
207
+		return 'text/html';
208
+	}
209
+
210
+
211
+
212
+	/**
213
+	 * @return void
214
+	 * @throws EE_Error
215
+	 * @throws ReflectionException
216
+	 */
217
+	public function get_error()
218
+	{
219
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
220
+			throw $this;
221
+		}
222
+		// get separate user and developer messages if they exist
223
+		$msg = explode('||', $this->getMessage());
224
+		$user_msg = $msg[0];
225
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
226
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
227
+		// add details to _all_exceptions array
228
+		$x_time = time();
229
+		self::$_all_exceptions[$x_time]['name'] = get_class($this);
230
+		self::$_all_exceptions[$x_time]['file'] = $this->getFile();
231
+		self::$_all_exceptions[$x_time]['line'] = $this->getLine();
232
+		self::$_all_exceptions[$x_time]['msg'] = $msg;
233
+		self::$_all_exceptions[$x_time]['code'] = $this->getCode();
234
+		self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
235
+		self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
236
+		self::$_error_count++;
237
+		//add_action( 'shutdown', array( $this, 'display_errors' ));
238
+		$this->display_errors();
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 *    has_error
245
+	 *
246
+	 * @param bool   $check_stored
247
+	 * @param string $type_to_check
248
+	 * @return bool
249
+	 */
250
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
251
+	{
252
+		$has_error = isset(self::$_espresso_notices[$type_to_check])
253
+					 && ! empty(self::$_espresso_notices[$type_to_check])
254
+			? true
255
+			: false;
256
+		if ($check_stored && ! $has_error) {
257
+			$notices = (array)get_option('ee_notices', array());
258
+			foreach ($notices as $type => $notice) {
259
+				if ($type === $type_to_check && $notice) {
260
+					return true;
261
+				}
262
+			}
263
+		}
264
+		return $has_error;
265
+	}
266
+
267
+
268
+
269
+	/**
270
+	 *    display_errors
271
+	 *
272
+	 * @echo   string
273
+	 * @throws \ReflectionException
274
+	 */
275
+	public function display_errors()
276
+	{
277
+		$trace_details = '';
278
+		$output = '
279 279
 <style type="text/css">
280 280
 	#ee-error-message {
281 281
 		max-width:90% !important;
@@ -331,19 +331,19 @@  discard block
 block discarded – undo
331 331
 	}
332 332
 </style>
333 333
 <div id="ee-error-message" class="error">';
334
-        if (! WP_DEBUG) {
335
-            $output .= '
334
+		if (! WP_DEBUG) {
335
+			$output .= '
336 336
 	<p>';
337
-        }
338
-        // cycle thru errors
339
-        foreach (self::$_all_exceptions as $time => $ex) {
340
-            $error_code = '';
341
-            // process trace info
342
-            if (empty($ex['trace'])) {
343
-                $trace_details .= __('Sorry, but no trace information was available for this exception.',
344
-                    'event_espresso');
345
-            } else {
346
-                $trace_details .= '
337
+		}
338
+		// cycle thru errors
339
+		foreach (self::$_all_exceptions as $time => $ex) {
340
+			$error_code = '';
341
+			// process trace info
342
+			if (empty($ex['trace'])) {
343
+				$trace_details .= __('Sorry, but no trace information was available for this exception.',
344
+					'event_espresso');
345
+			} else {
346
+				$trace_details .= '
347 347
 			<div id="ee-trace-details">
348 348
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
349 349
 				<tr>
@@ -353,43 +353,43 @@  discard block
 block discarded – undo
353 353
 					<th scope="col" align="left">Class</th>
354 354
 					<th scope="col" align="left">Method( arguments )</th>
355 355
 				</tr>';
356
-                $last_on_stack = count($ex['trace']) - 1;
357
-                // reverse array so that stack is in proper chronological order
358
-                $sorted_trace = array_reverse($ex['trace']);
359
-                foreach ($sorted_trace as $nmbr => $trace) {
360
-                    $file = isset($trace['file']) ? $trace['file'] : '';
361
-                    $class = isset($trace['class']) ? $trace['class'] : '';
362
-                    $type = isset($trace['type']) ? $trace['type'] : '';
363
-                    $function = isset($trace['function']) ? $trace['function'] : '';
364
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
365
-                    $line = isset($trace['line']) ? $trace['line'] : '';
366
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
367
-                    if (empty($file) && ! empty($class)) {
368
-                        $a = new ReflectionClass($class);
369
-                        $file = $a->getFileName();
370
-                        if (empty($line) && ! empty($function)) {
371
-                            try {
372
-                                //if $function is a closure, this throws an exception
373
-                                $b = new ReflectionMethod($class, $function);
374
-                                $line = $b->getStartLine();
375
-                            }catch(Exception $closure_exception){
376
-                                $line = 'unknown';
377
-                            }
378
-                        }
379
-                    }
380
-                    if ($nmbr === $last_on_stack) {
381
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
382
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
383
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
384
-                    }
385
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
386
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
387
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
388
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
389
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
390
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
391
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
392
-                    $trace_details .= '
356
+				$last_on_stack = count($ex['trace']) - 1;
357
+				// reverse array so that stack is in proper chronological order
358
+				$sorted_trace = array_reverse($ex['trace']);
359
+				foreach ($sorted_trace as $nmbr => $trace) {
360
+					$file = isset($trace['file']) ? $trace['file'] : '';
361
+					$class = isset($trace['class']) ? $trace['class'] : '';
362
+					$type = isset($trace['type']) ? $trace['type'] : '';
363
+					$function = isset($trace['function']) ? $trace['function'] : '';
364
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
365
+					$line = isset($trace['line']) ? $trace['line'] : '';
366
+					$zebra = ($nmbr % 2) ? ' odd' : '';
367
+					if (empty($file) && ! empty($class)) {
368
+						$a = new ReflectionClass($class);
369
+						$file = $a->getFileName();
370
+						if (empty($line) && ! empty($function)) {
371
+							try {
372
+								//if $function is a closure, this throws an exception
373
+								$b = new ReflectionMethod($class, $function);
374
+								$line = $b->getStartLine();
375
+							}catch(Exception $closure_exception){
376
+								$line = 'unknown';
377
+							}
378
+						}
379
+					}
380
+					if ($nmbr === $last_on_stack) {
381
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
382
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
383
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
384
+					}
385
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
386
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
387
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
388
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
389
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
390
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
391
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
392
+					$trace_details .= '
393 393
 					<tr>
394 394
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
395 395
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -397,674 +397,674 @@  discard block
 block discarded – undo
397 397
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
398 398
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
399 399
 					</tr>';
400
-                }
401
-                $trace_details .= '
400
+				}
401
+				$trace_details .= '
402 402
 			 </table>
403 403
 			</div>';
404
-            }
405
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
406
-            // add generic non-identifying messages for non-privileged users
407
-            if (! WP_DEBUG) {
408
-                $output .= '<span class="ee-error-user-msg-spn">'
409
-                           . trim($ex['msg'])
410
-                           . '</span> &nbsp; <sup>'
411
-                           . $ex['code']
412
-                           . '</sup><br />';
413
-            } else {
414
-                // or helpful developer messages if debugging is on
415
-                $output .= '
404
+			}
405
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
406
+			// add generic non-identifying messages for non-privileged users
407
+			if (! WP_DEBUG) {
408
+				$output .= '<span class="ee-error-user-msg-spn">'
409
+						   . trim($ex['msg'])
410
+						   . '</span> &nbsp; <sup>'
411
+						   . $ex['code']
412
+						   . '</sup><br />';
413
+			} else {
414
+				// or helpful developer messages if debugging is on
415
+				$output .= '
416 416
 		<div class="ee-error-dev-msg-dv">
417 417
 			<p class="ee-error-dev-msg-pg">
418 418
 				<strong class="ee-error-dev-msg-str">An '
419
-                           . $ex['name']
420
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
421
-                           . $ex['code']
422
-                           . '</span><br />
419
+						   . $ex['name']
420
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
421
+						   . $ex['code']
422
+						   . '</span><br />
423 423
 				<span class="big-text">"'
424
-                           . trim($ex['msg'])
425
-                           . '"</span><br/>
424
+						   . trim($ex['msg'])
425
+						   . '"</span><br/>
426 426
 				<a id="display-ee-error-trace-'
427
-                           . self::$_error_count
428
-                           . $time
429
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
430
-                           . self::$_error_count
431
-                           . $time
432
-                           . '">
427
+						   . self::$_error_count
428
+						   . $time
429
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
430
+						   . self::$_error_count
431
+						   . $time
432
+						   . '">
433 433
 					'
434
-                           . __('click to view backtrace and class/method details', 'event_espresso')
435
-                           . '
434
+						   . __('click to view backtrace and class/method details', 'event_espresso')
435
+						   . '
436 436
 				</a><br />
437 437
 				<span class="small-text lt-grey-text">'
438
-                           . $ex['file']
439
-                           . ' &nbsp; ( line no: '
440
-                           . $ex['line']
441
-                           . ' )</span>
438
+						   . $ex['file']
439
+						   . ' &nbsp; ( line no: '
440
+						   . $ex['line']
441
+						   . ' )</span>
442 442
 			</p>
443 443
 			<div id="ee-error-trace-'
444
-                           . self::$_error_count
445
-                           . $time
446
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
444
+						   . self::$_error_count
445
+						   . $time
446
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
447 447
 				'
448
-                           . $trace_details;
449
-                if (! empty($class)) {
450
-                    $output .= '
448
+						   . $trace_details;
449
+				if (! empty($class)) {
450
+					$output .= '
451 451
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
452 452
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
453 453
 						<h3>Class Details</h3>';
454
-                    $a = new ReflectionClass($class);
455
-                    $output .= '
454
+					$a = new ReflectionClass($class);
455
+					$output .= '
456 456
 						<pre>' . $a . '</pre>
457 457
 					</div>
458 458
 				</div>';
459
-                }
460
-                $output .= '
459
+				}
460
+				$output .= '
461 461
 			</div>
462 462
 		</div>
463 463
 		<br />';
464
-            }
465
-            $this->write_to_error_log($time, $ex);
466
-        }
467
-        // remove last linebreak
468
-        $output = substr($output, 0, -6);
469
-        if (! WP_DEBUG) {
470
-            $output .= '
464
+			}
465
+			$this->write_to_error_log($time, $ex);
466
+		}
467
+		// remove last linebreak
468
+		$output = substr($output, 0, -6);
469
+		if (! WP_DEBUG) {
470
+			$output .= '
471 471
 	</p>';
472
-        }
473
-        $output .= '
472
+		}
473
+		$output .= '
474 474
 </div>';
475
-        $output .= self::_print_scripts(true);
476
-        if (defined('DOING_AJAX')) {
477
-            echo wp_json_encode(array('error' => $output));
478
-            exit();
479
-        }
480
-        echo $output;
481
-        die();
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     *    generate string from exception trace args
488
-     *
489
-     * @param array $arguments
490
-     * @param bool  $array
491
-     * @return string
492
-     */
493
-    private function _convert_args_to_string($arguments = array(), $array = false)
494
-    {
495
-        $arg_string = '';
496
-        if (! empty($arguments)) {
497
-            $args = array();
498
-            foreach ($arguments as $arg) {
499
-                if (! empty($arg)) {
500
-                    if (is_string($arg)) {
501
-                        $args[] = " '" . $arg . "'";
502
-                    } elseif (is_array($arg)) {
503
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
504
-                    } elseif ($arg === null) {
505
-                        $args[] = ' NULL';
506
-                    } elseif (is_bool($arg)) {
507
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
508
-                    } elseif (is_object($arg)) {
509
-                        $args[] = ' OBJECT ' . get_class($arg);
510
-                    } elseif (is_resource($arg)) {
511
-                        $args[] = get_resource_type($arg);
512
-                    } else {
513
-                        $args[] = $arg;
514
-                    }
515
-                }
516
-            }
517
-            $arg_string = implode(', ', $args);
518
-        }
519
-        if ($array) {
520
-            $arg_string .= ' )';
521
-        }
522
-        return $arg_string;
523
-    }
524
-
525
-
526
-
527
-    /**
528
-     *    add error message
529
-     *
530
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
531
-     *                            separate messages for user || dev
532
-     * @param        string $file the file that the error occurred in - just use __FILE__
533
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
534
-     * @param        string $line the line number where the error occurred - just use __LINE__
535
-     * @return        void
536
-     */
537
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
538
-    {
539
-        self::_add_notice('errors', $msg, $file, $func, $line);
540
-        self::$_error_count++;
541
-    }
542
-
543
-
544
-
545
-    /**
546
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
547
-     * adds an error
548
-     *
549
-     * @param string $msg
550
-     * @param string $file
551
-     * @param string $func
552
-     * @param string $line
553
-     * @throws EE_Error
554
-     */
555
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
556
-    {
557
-        if (WP_DEBUG) {
558
-            throw new EE_Error($msg);
559
-        }
560
-        EE_Error::add_error($msg, $file, $func, $line);
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     *    add success message
567
-     *
568
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
569
-     *                            separate messages for user || dev
570
-     * @param        string $file the file that the error occurred in - just use __FILE__
571
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
572
-     * @param        string $line the line number where the error occurred - just use __LINE__
573
-     * @return        void
574
-     */
575
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
576
-    {
577
-        self::_add_notice('success', $msg, $file, $func, $line);
578
-    }
579
-
580
-
581
-
582
-    /**
583
-     *    add attention message
584
-     *
585
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
586
-     *                            separate messages for user || dev
587
-     * @param        string $file the file that the error occurred in - just use __FILE__
588
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
589
-     * @param        string $line the line number where the error occurred - just use __LINE__
590
-     * @return        void
591
-     */
592
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
593
-    {
594
-        self::_add_notice('attention', $msg, $file, $func, $line);
595
-    }
596
-
597
-
598
-
599
-    /**
600
-     *    add success message
601
-     *
602
-     * @param        string $type whether the message is for a success or error notification
603
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
604
-     *                            separate messages for user || dev
605
-     * @param        string $file the file that the error occurred in - just use __FILE__
606
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
607
-     * @param        string $line the line number where the error occurred - just use __LINE__
608
-     * @return        void
609
-     */
610
-    private static function _add_notice($type = 'success', $msg = null, $file = null, $func = null, $line = null)
611
-    {
612
-        if (empty($msg)) {
613
-            EE_Error::doing_it_wrong(
614
-                'EE_Error::add_' . $type . '()',
615
-                sprintf(
616
-                    __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
617
-                        'event_espresso'),
618
-                    $type,
619
-                    $file,
620
-                    $line
621
-                ),
622
-                EVENT_ESPRESSO_VERSION
623
-            );
624
-        }
625
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
626
-            EE_Error::doing_it_wrong(
627
-                'EE_Error::add_error()',
628
-                __('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
629
-                    'event_espresso'),
630
-                EVENT_ESPRESSO_VERSION
631
-            );
632
-        }
633
-        // get separate user and developer messages if they exist
634
-        $msg = explode('||', $msg);
635
-        $user_msg = $msg[0];
636
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
637
-        /**
638
-         * Do an action so other code can be triggered when a notice is created
639
-         *
640
-         * @param string $type     can be 'errors', 'attention', or 'success'
641
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
642
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
643
-         * @param string $file     file where error was generated
644
-         * @param string $func     function where error was generated
645
-         * @param string $line     line where error was generated
646
-         */
647
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
648
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
649
-        // add notice if message exists
650
-        if (! empty($msg)) {
651
-            // get error code
652
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
653
-            if (WP_DEBUG && $type === 'errors') {
654
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
655
-            }
656
-            // add notice. Index by code if it's not blank
657
-            if ($notice_code) {
658
-                self::$_espresso_notices[$type][$notice_code] = $msg;
659
-            } else {
660
-                self::$_espresso_notices[$type][] = $msg;
661
-            }
662
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
663
-        }
664
-    }
665
-
666
-
667
-
668
-    /**
669
-     *    in some case it may be necessary to overwrite the existing success messages
670
-     *
671
-     * @return        void
672
-     */
673
-    public static function overwrite_success()
674
-    {
675
-        self::$_espresso_notices['success'] = false;
676
-    }
677
-
678
-
679
-
680
-    /**
681
-     *    in some case it may be necessary to overwrite the existing attention messages
682
-     *
683
-     * @return        void
684
-     */
685
-    public static function overwrite_attention()
686
-    {
687
-        self::$_espresso_notices['attention'] = false;
688
-    }
689
-
690
-
691
-
692
-    /**
693
-     *    in some case it may be necessary to overwrite the existing error messages
694
-     *
695
-     * @return        void
696
-     */
697
-    public static function overwrite_errors()
698
-    {
699
-        self::$_espresso_notices['errors'] = false;
700
-    }
701
-
702
-
703
-
704
-    /**
705
-     *    reset_notices
706
-     *
707
-     * @return void
708
-     */
709
-    public static function reset_notices()
710
-    {
711
-        self::$_espresso_notices['success'] = false;
712
-        self::$_espresso_notices['attention'] = false;
713
-        self::$_espresso_notices['errors'] = false;
714
-    }
715
-
716
-
717
-
718
-    /**
719
-     *    has_errors
720
-     *
721
-     * @return int
722
-     */
723
-    public static function has_notices()
724
-    {
725
-        $has_notices = 0;
726
-        // check for success messages
727
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success']) ? 3
728
-            : $has_notices;
729
-        // check for attention messages
730
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention']) ? 2
731
-            : $has_notices;
732
-        // check for error messages
733
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors']) ? 1
734
-            : $has_notices;
735
-        return $has_notices;
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
742
-     *
743
-     * @since 4.9.0
744
-     * @return array
745
-     */
746
-    public static function get_vanilla_notices()
747
-    {
748
-        return array(
749
-            'success'   => isset(self::$_espresso_notices['success']) ? self::$_espresso_notices['success'] : array(),
750
-            'attention' => isset(self::$_espresso_notices['attention']) ? self::$_espresso_notices['attention']
751
-                : array(),
752
-            'errors'    => isset(self::$_espresso_notices['errors']) ? self::$_espresso_notices['errors'] : array(),
753
-        );
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     *    compile all error or success messages into one string
760
-     *
761
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
762
-     * @param        boolean $format_output     whether or not to format the messages for display in the WP admin
763
-     * @param        boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
764
-     *                                          - ONLY do this just before redirecting
765
-     * @param        boolean $remove_empty      whether or not to unset empty messages
766
-     * @return        array
767
-     */
768
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
769
-    {
770
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
771
-        $success_messages = '';
772
-        $attention_messages = '';
773
-        $error_messages = '';
774
-        $print_scripts = false;
775
-        // either save notices to the db
776
-        if ($save_to_transient) {
777
-            update_option('ee_notices', self::$_espresso_notices);
778
-            return array();
779
-        }
780
-        // grab any notices that have been previously saved
781
-        if ($notices = get_option('ee_notices', false)) {
782
-            foreach ($notices as $type => $notice) {
783
-                if (is_array($notice) && ! empty($notice)) {
784
-                    // make sure that existing notice type is an array
785
-                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
786
-                                                      && ! empty(self::$_espresso_notices[$type])
787
-                        ? self::$_espresso_notices[$type] : array();
788
-                    // merge stored notices with any newly created ones
789
-                    self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
790
-                    $print_scripts = true;
791
-                }
792
-            }
793
-            // now clear any stored notices
794
-            update_option('ee_notices', false);
795
-        }
796
-        // check for success messages
797
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
798
-            // combine messages
799
-            $success_messages .= implode(self::$_espresso_notices['success'], '<br /><br />');
800
-            $print_scripts = true;
801
-        }
802
-        // check for attention messages
803
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
804
-            // combine messages
805
-            $attention_messages .= implode(self::$_espresso_notices['attention'], '<br /><br />');
806
-            $print_scripts = true;
807
-        }
808
-        // check for error messages
809
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
810
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
811
-                ? __('The following errors have occurred:<br />', 'event_espresso')
812
-                : __('An error has occurred:<br />', 'event_espresso');
813
-            // combine messages
814
-            $error_messages .= implode(self::$_espresso_notices['errors'], '<br /><br />');
815
-            $print_scripts = true;
816
-        }
817
-        if ($format_output) {
818
-            $notices = '<div id="espresso-notices">';
819
-            $close = is_admin() ? ''
820
-                : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
821
-            if ($success_messages !== '') {
822
-                $css_id = is_admin() ? 'message' : 'espresso-notices-success';
823
-                $css_class = is_admin() ? 'updated fade' : 'success fade-away';
824
-                //showMessage( $success_messages );
825
-                $notices .= '<div id="'
826
-                            . $css_id
827
-                            . '" class="espresso-notices '
828
-                            . $css_class
829
-                            . '" style="display:none;"><p>'
830
-                            . $success_messages
831
-                            . '</p>'
832
-                            . $close
833
-                            . '</div>';
834
-            }
835
-            if ($attention_messages !== '') {
836
-                $css_id = is_admin() ? 'message' : 'espresso-notices-attention';
837
-                $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
838
-                //showMessage( $error_messages, TRUE );
839
-                $notices .= '<div id="'
840
-                            . $css_id
841
-                            . '" class="espresso-notices '
842
-                            . $css_class
843
-                            . '" style="display:none;"><p>'
844
-                            . $attention_messages
845
-                            . '</p>'
846
-                            . $close
847
-                            . '</div>';
848
-            }
849
-            if ($error_messages !== '') {
850
-                $css_id = is_admin() ? 'message' : 'espresso-notices-error';
851
-                $css_class = is_admin() ? 'error' : 'error fade-away';
852
-                //showMessage( $error_messages, TRUE );
853
-                $notices .= '<div id="'
854
-                            . $css_id
855
-                            . '" class="espresso-notices '
856
-                            . $css_class
857
-                            . '" style="display:none;"><p>'
858
-                            . $error_messages
859
-                            . '</p>'
860
-                            . $close
861
-                            . '</div>';
862
-            }
863
-            $notices .= '</div>';
864
-        } else {
865
-            $notices = array(
866
-                'success'   => $success_messages,
867
-                'attention' => $attention_messages,
868
-                'errors'    => $error_messages,
869
-            );
870
-            if ($remove_empty) {
871
-                // remove empty notices
872
-                foreach ($notices as $type => $notice) {
873
-                    if (empty($notice)) {
874
-                        unset($notices[$type]);
875
-                    }
876
-                }
877
-            }
878
-        }
879
-        if ($print_scripts) {
880
-            self::_print_scripts();
881
-        }
882
-        return $notices;
883
-    }
884
-
885
-
886
-
887
-    /**
888
-     *    add_persistent_admin_notice
889
-     *
890
-     * @param        string $pan_name     the name, or key of the Persistent Admin Notice to be stored
891
-     * @param        string $pan_message  the message to be stored persistently until dismissed
892
-     * @param bool          $force_update allows one to enforce the reappearance of a persistent message.
893
-     * @return        void
894
-     */
895
-    public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
896
-    {
897
-        if (! empty($pan_name) && ! empty($pan_message)) {
898
-            $persistent_admin_notices = get_option('ee_pers_admin_notices', array());
899
-            //maybe initialize persistent_admin_notices
900
-            if (empty($persistent_admin_notices)) {
901
-                add_option('ee_pers_admin_notices', array(), '', 'no');
902
-            }
903
-            $pan_name = sanitize_key($pan_name);
904
-            if (! array_key_exists($pan_name, $persistent_admin_notices) || $force_update) {
905
-                $persistent_admin_notices[$pan_name] = $pan_message;
906
-                update_option('ee_pers_admin_notices', $persistent_admin_notices);
907
-            }
908
-        }
909
-    }
910
-
911
-
912
-
913
-    /**
914
-     *    dismiss_persistent_admin_notice
915
-     *
916
-     * @param        string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
917
-     * @param bool          $purge
918
-     * @param bool          $return_immediately
919
-     * @return        void
920
-     */
921
-    public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return_immediately = false)
922
-    {
923
-        $pan_name = EE_Registry::instance()->REQ->is_set('ee_nag_notice')
924
-            ? EE_Registry::instance()->REQ->get('ee_nag_notice') : $pan_name;
925
-        if (! empty($pan_name)) {
926
-            $persistent_admin_notices = get_option('ee_pers_admin_notices', array());
927
-            // check if notice we wish to dismiss is actually in the $persistent_admin_notices array
928
-            if (is_array($persistent_admin_notices) && isset($persistent_admin_notices[$pan_name])) {
929
-                // completely delete nag notice, or just NULL message so that it can NOT be added again ?
930
-                if ($purge) {
931
-                    unset($persistent_admin_notices[$pan_name]);
932
-                } else {
933
-                    $persistent_admin_notices[$pan_name] = null;
934
-                }
935
-                if (update_option('ee_pers_admin_notices', $persistent_admin_notices) === false) {
936
-                    EE_Error::add_error(sprintf(__('The persistent admin notice for "%s" could not be deleted.',
937
-                        'event_espresso'), $pan_name), __FILE__, __FUNCTION__, __LINE__);
938
-                }
939
-            }
940
-        }
941
-        if ($return_immediately) {
942
-            return;
943
-        }
944
-        if (EE_Registry::instance()->REQ->ajax) {
945
-            // grab any notices and concatenate into string
946
-            echo wp_json_encode(array('errors' => implode('<br />', EE_Error::get_notices(false))));
947
-            exit();
948
-        }
949
-        // save errors to a transient to be displayed on next request (after redirect)
950
-        EE_Error::get_notices(false, true);
951
-        $return_url = EE_Registry::instance()->REQ->is_set('return_url')
952
-            ? EE_Registry::instance()->REQ->get('return_url') : '';
953
-        wp_safe_redirect(urldecode($return_url));
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * display_persistent_admin_notices
960
-     *
961
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
962
-     * @param  string $pan_message the message to be stored persistently until dismissed
963
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
964
-     * @return string
965
-     */
966
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
967
-    {
968
-        if (! empty($pan_name) && ! empty($pan_message)) {
969
-            $args = array(
970
-                'nag_notice'    => $pan_name,
971
-                'return_url'    => urlencode($return_url),
972
-                'ajax_url'      => WP_AJAX_URL,
973
-                'unknown_error' => esc_html__(
974
-                    'An unknown error has occurred on the server while attempting to dismiss this notice.',
975
-                    'event_espresso'
976
-                ),
977
-            );
978
-            EE_Registry::$i18n_js_strings = array_merge(
979
-                EE_Registry::$i18n_js_strings,
980
-                array('ee_dismiss' => $args)
981
-            );
982
-            return '
475
+		$output .= self::_print_scripts(true);
476
+		if (defined('DOING_AJAX')) {
477
+			echo wp_json_encode(array('error' => $output));
478
+			exit();
479
+		}
480
+		echo $output;
481
+		die();
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 *    generate string from exception trace args
488
+	 *
489
+	 * @param array $arguments
490
+	 * @param bool  $array
491
+	 * @return string
492
+	 */
493
+	private function _convert_args_to_string($arguments = array(), $array = false)
494
+	{
495
+		$arg_string = '';
496
+		if (! empty($arguments)) {
497
+			$args = array();
498
+			foreach ($arguments as $arg) {
499
+				if (! empty($arg)) {
500
+					if (is_string($arg)) {
501
+						$args[] = " '" . $arg . "'";
502
+					} elseif (is_array($arg)) {
503
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
504
+					} elseif ($arg === null) {
505
+						$args[] = ' NULL';
506
+					} elseif (is_bool($arg)) {
507
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
508
+					} elseif (is_object($arg)) {
509
+						$args[] = ' OBJECT ' . get_class($arg);
510
+					} elseif (is_resource($arg)) {
511
+						$args[] = get_resource_type($arg);
512
+					} else {
513
+						$args[] = $arg;
514
+					}
515
+				}
516
+			}
517
+			$arg_string = implode(', ', $args);
518
+		}
519
+		if ($array) {
520
+			$arg_string .= ' )';
521
+		}
522
+		return $arg_string;
523
+	}
524
+
525
+
526
+
527
+	/**
528
+	 *    add error message
529
+	 *
530
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
531
+	 *                            separate messages for user || dev
532
+	 * @param        string $file the file that the error occurred in - just use __FILE__
533
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
534
+	 * @param        string $line the line number where the error occurred - just use __LINE__
535
+	 * @return        void
536
+	 */
537
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
538
+	{
539
+		self::_add_notice('errors', $msg, $file, $func, $line);
540
+		self::$_error_count++;
541
+	}
542
+
543
+
544
+
545
+	/**
546
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
547
+	 * adds an error
548
+	 *
549
+	 * @param string $msg
550
+	 * @param string $file
551
+	 * @param string $func
552
+	 * @param string $line
553
+	 * @throws EE_Error
554
+	 */
555
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
556
+	{
557
+		if (WP_DEBUG) {
558
+			throw new EE_Error($msg);
559
+		}
560
+		EE_Error::add_error($msg, $file, $func, $line);
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 *    add success message
567
+	 *
568
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
569
+	 *                            separate messages for user || dev
570
+	 * @param        string $file the file that the error occurred in - just use __FILE__
571
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
572
+	 * @param        string $line the line number where the error occurred - just use __LINE__
573
+	 * @return        void
574
+	 */
575
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
576
+	{
577
+		self::_add_notice('success', $msg, $file, $func, $line);
578
+	}
579
+
580
+
581
+
582
+	/**
583
+	 *    add attention message
584
+	 *
585
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
586
+	 *                            separate messages for user || dev
587
+	 * @param        string $file the file that the error occurred in - just use __FILE__
588
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
589
+	 * @param        string $line the line number where the error occurred - just use __LINE__
590
+	 * @return        void
591
+	 */
592
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
593
+	{
594
+		self::_add_notice('attention', $msg, $file, $func, $line);
595
+	}
596
+
597
+
598
+
599
+	/**
600
+	 *    add success message
601
+	 *
602
+	 * @param        string $type whether the message is for a success or error notification
603
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
604
+	 *                            separate messages for user || dev
605
+	 * @param        string $file the file that the error occurred in - just use __FILE__
606
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
607
+	 * @param        string $line the line number where the error occurred - just use __LINE__
608
+	 * @return        void
609
+	 */
610
+	private static function _add_notice($type = 'success', $msg = null, $file = null, $func = null, $line = null)
611
+	{
612
+		if (empty($msg)) {
613
+			EE_Error::doing_it_wrong(
614
+				'EE_Error::add_' . $type . '()',
615
+				sprintf(
616
+					__('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
617
+						'event_espresso'),
618
+					$type,
619
+					$file,
620
+					$line
621
+				),
622
+				EVENT_ESPRESSO_VERSION
623
+			);
624
+		}
625
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
626
+			EE_Error::doing_it_wrong(
627
+				'EE_Error::add_error()',
628
+				__('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
629
+					'event_espresso'),
630
+				EVENT_ESPRESSO_VERSION
631
+			);
632
+		}
633
+		// get separate user and developer messages if they exist
634
+		$msg = explode('||', $msg);
635
+		$user_msg = $msg[0];
636
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
637
+		/**
638
+		 * Do an action so other code can be triggered when a notice is created
639
+		 *
640
+		 * @param string $type     can be 'errors', 'attention', or 'success'
641
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
642
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
643
+		 * @param string $file     file where error was generated
644
+		 * @param string $func     function where error was generated
645
+		 * @param string $line     line where error was generated
646
+		 */
647
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
648
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
649
+		// add notice if message exists
650
+		if (! empty($msg)) {
651
+			// get error code
652
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
653
+			if (WP_DEBUG && $type === 'errors') {
654
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
655
+			}
656
+			// add notice. Index by code if it's not blank
657
+			if ($notice_code) {
658
+				self::$_espresso_notices[$type][$notice_code] = $msg;
659
+			} else {
660
+				self::$_espresso_notices[$type][] = $msg;
661
+			}
662
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
663
+		}
664
+	}
665
+
666
+
667
+
668
+	/**
669
+	 *    in some case it may be necessary to overwrite the existing success messages
670
+	 *
671
+	 * @return        void
672
+	 */
673
+	public static function overwrite_success()
674
+	{
675
+		self::$_espresso_notices['success'] = false;
676
+	}
677
+
678
+
679
+
680
+	/**
681
+	 *    in some case it may be necessary to overwrite the existing attention messages
682
+	 *
683
+	 * @return        void
684
+	 */
685
+	public static function overwrite_attention()
686
+	{
687
+		self::$_espresso_notices['attention'] = false;
688
+	}
689
+
690
+
691
+
692
+	/**
693
+	 *    in some case it may be necessary to overwrite the existing error messages
694
+	 *
695
+	 * @return        void
696
+	 */
697
+	public static function overwrite_errors()
698
+	{
699
+		self::$_espresso_notices['errors'] = false;
700
+	}
701
+
702
+
703
+
704
+	/**
705
+	 *    reset_notices
706
+	 *
707
+	 * @return void
708
+	 */
709
+	public static function reset_notices()
710
+	{
711
+		self::$_espresso_notices['success'] = false;
712
+		self::$_espresso_notices['attention'] = false;
713
+		self::$_espresso_notices['errors'] = false;
714
+	}
715
+
716
+
717
+
718
+	/**
719
+	 *    has_errors
720
+	 *
721
+	 * @return int
722
+	 */
723
+	public static function has_notices()
724
+	{
725
+		$has_notices = 0;
726
+		// check for success messages
727
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success']) ? 3
728
+			: $has_notices;
729
+		// check for attention messages
730
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention']) ? 2
731
+			: $has_notices;
732
+		// check for error messages
733
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors']) ? 1
734
+			: $has_notices;
735
+		return $has_notices;
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
742
+	 *
743
+	 * @since 4.9.0
744
+	 * @return array
745
+	 */
746
+	public static function get_vanilla_notices()
747
+	{
748
+		return array(
749
+			'success'   => isset(self::$_espresso_notices['success']) ? self::$_espresso_notices['success'] : array(),
750
+			'attention' => isset(self::$_espresso_notices['attention']) ? self::$_espresso_notices['attention']
751
+				: array(),
752
+			'errors'    => isset(self::$_espresso_notices['errors']) ? self::$_espresso_notices['errors'] : array(),
753
+		);
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 *    compile all error or success messages into one string
760
+	 *
761
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
762
+	 * @param        boolean $format_output     whether or not to format the messages for display in the WP admin
763
+	 * @param        boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
764
+	 *                                          - ONLY do this just before redirecting
765
+	 * @param        boolean $remove_empty      whether or not to unset empty messages
766
+	 * @return        array
767
+	 */
768
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
769
+	{
770
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
771
+		$success_messages = '';
772
+		$attention_messages = '';
773
+		$error_messages = '';
774
+		$print_scripts = false;
775
+		// either save notices to the db
776
+		if ($save_to_transient) {
777
+			update_option('ee_notices', self::$_espresso_notices);
778
+			return array();
779
+		}
780
+		// grab any notices that have been previously saved
781
+		if ($notices = get_option('ee_notices', false)) {
782
+			foreach ($notices as $type => $notice) {
783
+				if (is_array($notice) && ! empty($notice)) {
784
+					// make sure that existing notice type is an array
785
+					self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
786
+													  && ! empty(self::$_espresso_notices[$type])
787
+						? self::$_espresso_notices[$type] : array();
788
+					// merge stored notices with any newly created ones
789
+					self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
790
+					$print_scripts = true;
791
+				}
792
+			}
793
+			// now clear any stored notices
794
+			update_option('ee_notices', false);
795
+		}
796
+		// check for success messages
797
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
798
+			// combine messages
799
+			$success_messages .= implode(self::$_espresso_notices['success'], '<br /><br />');
800
+			$print_scripts = true;
801
+		}
802
+		// check for attention messages
803
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
804
+			// combine messages
805
+			$attention_messages .= implode(self::$_espresso_notices['attention'], '<br /><br />');
806
+			$print_scripts = true;
807
+		}
808
+		// check for error messages
809
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
810
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
811
+				? __('The following errors have occurred:<br />', 'event_espresso')
812
+				: __('An error has occurred:<br />', 'event_espresso');
813
+			// combine messages
814
+			$error_messages .= implode(self::$_espresso_notices['errors'], '<br /><br />');
815
+			$print_scripts = true;
816
+		}
817
+		if ($format_output) {
818
+			$notices = '<div id="espresso-notices">';
819
+			$close = is_admin() ? ''
820
+				: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
821
+			if ($success_messages !== '') {
822
+				$css_id = is_admin() ? 'message' : 'espresso-notices-success';
823
+				$css_class = is_admin() ? 'updated fade' : 'success fade-away';
824
+				//showMessage( $success_messages );
825
+				$notices .= '<div id="'
826
+							. $css_id
827
+							. '" class="espresso-notices '
828
+							. $css_class
829
+							. '" style="display:none;"><p>'
830
+							. $success_messages
831
+							. '</p>'
832
+							. $close
833
+							. '</div>';
834
+			}
835
+			if ($attention_messages !== '') {
836
+				$css_id = is_admin() ? 'message' : 'espresso-notices-attention';
837
+				$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
838
+				//showMessage( $error_messages, TRUE );
839
+				$notices .= '<div id="'
840
+							. $css_id
841
+							. '" class="espresso-notices '
842
+							. $css_class
843
+							. '" style="display:none;"><p>'
844
+							. $attention_messages
845
+							. '</p>'
846
+							. $close
847
+							. '</div>';
848
+			}
849
+			if ($error_messages !== '') {
850
+				$css_id = is_admin() ? 'message' : 'espresso-notices-error';
851
+				$css_class = is_admin() ? 'error' : 'error fade-away';
852
+				//showMessage( $error_messages, TRUE );
853
+				$notices .= '<div id="'
854
+							. $css_id
855
+							. '" class="espresso-notices '
856
+							. $css_class
857
+							. '" style="display:none;"><p>'
858
+							. $error_messages
859
+							. '</p>'
860
+							. $close
861
+							. '</div>';
862
+			}
863
+			$notices .= '</div>';
864
+		} else {
865
+			$notices = array(
866
+				'success'   => $success_messages,
867
+				'attention' => $attention_messages,
868
+				'errors'    => $error_messages,
869
+			);
870
+			if ($remove_empty) {
871
+				// remove empty notices
872
+				foreach ($notices as $type => $notice) {
873
+					if (empty($notice)) {
874
+						unset($notices[$type]);
875
+					}
876
+				}
877
+			}
878
+		}
879
+		if ($print_scripts) {
880
+			self::_print_scripts();
881
+		}
882
+		return $notices;
883
+	}
884
+
885
+
886
+
887
+	/**
888
+	 *    add_persistent_admin_notice
889
+	 *
890
+	 * @param        string $pan_name     the name, or key of the Persistent Admin Notice to be stored
891
+	 * @param        string $pan_message  the message to be stored persistently until dismissed
892
+	 * @param bool          $force_update allows one to enforce the reappearance of a persistent message.
893
+	 * @return        void
894
+	 */
895
+	public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
896
+	{
897
+		if (! empty($pan_name) && ! empty($pan_message)) {
898
+			$persistent_admin_notices = get_option('ee_pers_admin_notices', array());
899
+			//maybe initialize persistent_admin_notices
900
+			if (empty($persistent_admin_notices)) {
901
+				add_option('ee_pers_admin_notices', array(), '', 'no');
902
+			}
903
+			$pan_name = sanitize_key($pan_name);
904
+			if (! array_key_exists($pan_name, $persistent_admin_notices) || $force_update) {
905
+				$persistent_admin_notices[$pan_name] = $pan_message;
906
+				update_option('ee_pers_admin_notices', $persistent_admin_notices);
907
+			}
908
+		}
909
+	}
910
+
911
+
912
+
913
+	/**
914
+	 *    dismiss_persistent_admin_notice
915
+	 *
916
+	 * @param        string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
917
+	 * @param bool          $purge
918
+	 * @param bool          $return_immediately
919
+	 * @return        void
920
+	 */
921
+	public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return_immediately = false)
922
+	{
923
+		$pan_name = EE_Registry::instance()->REQ->is_set('ee_nag_notice')
924
+			? EE_Registry::instance()->REQ->get('ee_nag_notice') : $pan_name;
925
+		if (! empty($pan_name)) {
926
+			$persistent_admin_notices = get_option('ee_pers_admin_notices', array());
927
+			// check if notice we wish to dismiss is actually in the $persistent_admin_notices array
928
+			if (is_array($persistent_admin_notices) && isset($persistent_admin_notices[$pan_name])) {
929
+				// completely delete nag notice, or just NULL message so that it can NOT be added again ?
930
+				if ($purge) {
931
+					unset($persistent_admin_notices[$pan_name]);
932
+				} else {
933
+					$persistent_admin_notices[$pan_name] = null;
934
+				}
935
+				if (update_option('ee_pers_admin_notices', $persistent_admin_notices) === false) {
936
+					EE_Error::add_error(sprintf(__('The persistent admin notice for "%s" could not be deleted.',
937
+						'event_espresso'), $pan_name), __FILE__, __FUNCTION__, __LINE__);
938
+				}
939
+			}
940
+		}
941
+		if ($return_immediately) {
942
+			return;
943
+		}
944
+		if (EE_Registry::instance()->REQ->ajax) {
945
+			// grab any notices and concatenate into string
946
+			echo wp_json_encode(array('errors' => implode('<br />', EE_Error::get_notices(false))));
947
+			exit();
948
+		}
949
+		// save errors to a transient to be displayed on next request (after redirect)
950
+		EE_Error::get_notices(false, true);
951
+		$return_url = EE_Registry::instance()->REQ->is_set('return_url')
952
+			? EE_Registry::instance()->REQ->get('return_url') : '';
953
+		wp_safe_redirect(urldecode($return_url));
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * display_persistent_admin_notices
960
+	 *
961
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
962
+	 * @param  string $pan_message the message to be stored persistently until dismissed
963
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
964
+	 * @return string
965
+	 */
966
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
967
+	{
968
+		if (! empty($pan_name) && ! empty($pan_message)) {
969
+			$args = array(
970
+				'nag_notice'    => $pan_name,
971
+				'return_url'    => urlencode($return_url),
972
+				'ajax_url'      => WP_AJAX_URL,
973
+				'unknown_error' => esc_html__(
974
+					'An unknown error has occurred on the server while attempting to dismiss this notice.',
975
+					'event_espresso'
976
+				),
977
+			);
978
+			EE_Registry::$i18n_js_strings = array_merge(
979
+				EE_Registry::$i18n_js_strings,
980
+				array('ee_dismiss' => $args)
981
+			);
982
+			return '
983 983
 			<div id="'
984
-                   . $pan_name
985
-                   . '" class="espresso-notices updated ee-nag-notice clearfix" style="border-left: 4px solid #fcb93c;">
984
+				   . $pan_name
985
+				   . '" class="espresso-notices updated ee-nag-notice clearfix" style="border-left: 4px solid #fcb93c;">
986 986
 				<p>'
987
-                   . $pan_message
988
-                   . '</p>
987
+				   . $pan_message
988
+				   . '</p>
989 989
 				<a class="dismiss-ee-nag-notice hide-if-no-js" style="float: right; cursor: pointer; text-decoration:none;" rel="'
990
-                   . $pan_name
991
-                   . '">
990
+				   . $pan_name
991
+				   . '">
992 992
 					<span class="dashicons dashicons-dismiss" style="position:relative; top:-1px; margin-right:.25em;"></span>'
993
-                   . __('Dismiss', 'event_espresso')
994
-                   . '
993
+				   . __('Dismiss', 'event_espresso')
994
+				   . '
995 995
 				</a>
996 996
 				<div style="clear:both;"></div>
997 997
 			</div>';
998
-        }
999
-        return '';
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     *    get_persistent_admin_notices
1006
-     *
1007
-     * @param string $return_url
1008
-     * @return string
1009
-     */
1010
-    public static function get_persistent_admin_notices($return_url = '')
1011
-    {
1012
-        $notices = '';
1013
-        // check for persistent admin notices
1014
-        //filter the list though so plugins can notify the admin in a different way if they want
1015
-        $persistent_admin_notices = apply_filters(
1016
-            'FHEE__EE_Error__get_persistent_admin_notices',
1017
-            get_option('ee_pers_admin_notices', false),
1018
-            'ee_pers_admin_notices',
1019
-            $return_url
1020
-        );
1021
-        if ($persistent_admin_notices) {
1022
-            // load scripts
1023
-            wp_register_script(
1024
-                'espresso_core',
1025
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1026
-                array('jquery'),
1027
-                EVENT_ESPRESSO_VERSION,
1028
-                true
1029
-            );
1030
-            wp_register_script(
1031
-                'ee_error_js',
1032
-                EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1033
-                array('espresso_core'),
1034
-                EVENT_ESPRESSO_VERSION,
1035
-                true
1036
-            );
1037
-            wp_enqueue_script('ee_error_js');
1038
-            // and display notices
1039
-            foreach ($persistent_admin_notices as $pan_name => $pan_message) {
1040
-                $notices .= self::display_persistent_admin_notices($pan_name, $pan_message, $return_url);
1041
-            }
1042
-        }
1043
-        return $notices;
1044
-    }
1045
-
1046
-
1047
-
1048
-    /**
1049
-     * _print_scripts
1050
-     *
1051
-     * @param    bool $force_print
1052
-     * @return    string
1053
-     */
1054
-    private static function _print_scripts($force_print = false)
1055
-    {
1056
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1057
-            if (wp_script_is('ee_error_js', 'enqueued')) {
1058
-                return '';
1059
-            }
1060
-            if (wp_script_is('ee_error_js', 'registered')) {
1061
-                wp_enqueue_style('espresso_default');
1062
-                wp_enqueue_style('espresso_custom_css');
1063
-                wp_enqueue_script('ee_error_js');
1064
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1065
-            }
1066
-        } else {
1067
-            return '
998
+		}
999
+		return '';
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 *    get_persistent_admin_notices
1006
+	 *
1007
+	 * @param string $return_url
1008
+	 * @return string
1009
+	 */
1010
+	public static function get_persistent_admin_notices($return_url = '')
1011
+	{
1012
+		$notices = '';
1013
+		// check for persistent admin notices
1014
+		//filter the list though so plugins can notify the admin in a different way if they want
1015
+		$persistent_admin_notices = apply_filters(
1016
+			'FHEE__EE_Error__get_persistent_admin_notices',
1017
+			get_option('ee_pers_admin_notices', false),
1018
+			'ee_pers_admin_notices',
1019
+			$return_url
1020
+		);
1021
+		if ($persistent_admin_notices) {
1022
+			// load scripts
1023
+			wp_register_script(
1024
+				'espresso_core',
1025
+				EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1026
+				array('jquery'),
1027
+				EVENT_ESPRESSO_VERSION,
1028
+				true
1029
+			);
1030
+			wp_register_script(
1031
+				'ee_error_js',
1032
+				EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1033
+				array('espresso_core'),
1034
+				EVENT_ESPRESSO_VERSION,
1035
+				true
1036
+			);
1037
+			wp_enqueue_script('ee_error_js');
1038
+			// and display notices
1039
+			foreach ($persistent_admin_notices as $pan_name => $pan_message) {
1040
+				$notices .= self::display_persistent_admin_notices($pan_name, $pan_message, $return_url);
1041
+			}
1042
+		}
1043
+		return $notices;
1044
+	}
1045
+
1046
+
1047
+
1048
+	/**
1049
+	 * _print_scripts
1050
+	 *
1051
+	 * @param    bool $force_print
1052
+	 * @return    string
1053
+	 */
1054
+	private static function _print_scripts($force_print = false)
1055
+	{
1056
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1057
+			if (wp_script_is('ee_error_js', 'enqueued')) {
1058
+				return '';
1059
+			}
1060
+			if (wp_script_is('ee_error_js', 'registered')) {
1061
+				wp_enqueue_style('espresso_default');
1062
+				wp_enqueue_style('espresso_custom_css');
1063
+				wp_enqueue_script('ee_error_js');
1064
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1065
+			}
1066
+		} else {
1067
+			return '
1068 1068
 <script>
1069 1069
 /* <![CDATA[ */
1070 1070
 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -1074,143 +1074,143 @@  discard block
 block discarded – undo
1074 1074
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1075 1075
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1076 1076
 ';
1077
-        }
1078
-        return '';
1079
-    }
1080
-
1081
-
1082
-
1083
-    /**
1084
-     *    enqueue_error_scripts
1085
-     *
1086
-     * @return        void
1087
-     */
1088
-    public static function enqueue_error_scripts()
1089
-    {
1090
-        self::_print_scripts();
1091
-    }
1092
-
1093
-
1094
-
1095
-    /**
1096
-     *    create error code from filepath, function name,
1097
-     *    and line number where exception or error was thrown
1098
-     *
1099
-     * @param string $file
1100
-     * @param string $func
1101
-     * @param string $line
1102
-     * @return string
1103
-     */
1104
-    public static function generate_error_code($file = '', $func = '', $line = '')
1105
-    {
1106
-        $file = explode('.', basename($file));
1107
-        $error_code = ! empty($file[0]) ? $file[0] : '';
1108
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1109
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1110
-        return $error_code;
1111
-    }
1112
-
1113
-
1114
-
1115
-    /**
1116
-     *    write exception details to log file
1117
-     *
1118
-     * @param int   $time
1119
-     * @param array $ex
1120
-     * @param bool  $clear
1121
-     * @return void
1122
-     */
1123
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1124
-    {
1125
-        if (empty($ex)) {
1126
-            return;
1127
-        }
1128
-        if (! $time) {
1129
-            $time = time();
1130
-        }
1131
-        $exception_log = '----------------------------------------------------------------------------------------'
1132
-                         . PHP_EOL;
1133
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1134
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1135
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1136
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1137
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1138
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1139
-        $exception_log .= $ex['string'] . PHP_EOL;
1140
-        $exception_log .= '----------------------------------------------------------------------------------------'
1141
-                          . PHP_EOL;
1142
-        try {
1143
-            EEH_File::ensure_file_exists_and_is_writable(
1144
-                EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1145
-            );
1146
-            EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs');
1147
-            if (! $clear) {
1148
-                //get existing log file and append new log info
1149
-                $exception_log = EEH_File::get_file_contents(
1150
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1151
-                ) . $exception_log;
1152
-            }
1153
-            EEH_File::write_to_file(
1154
-                EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file,
1155
-                $exception_log
1156
-            );
1157
-        } catch (EE_Error $e) {
1158
-            EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1159
-                'event_espresso'), $e->getMessage()));
1160
-            return;
1161
-        }
1162
-    }
1163
-
1164
-
1165
-
1166
-    /**
1167
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1168
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1169
-     * but the code execution is done in a manner that could lead to unexpected results
1170
-     * (i.e. running to early, or too late in WP or EE loading process).
1171
-     * A good test for knowing whether to use this method is:
1172
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1173
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1174
-     * 2. If this is loaded before something else, it won't break anything,
1175
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1176
-     *
1177
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1178
-     * @param string $function      The function that was called
1179
-     * @param string $message       A message explaining what has been done incorrectly
1180
-     * @param string $version       The version of Event Espresso where the error was added
1181
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1182
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1183
-     *                              but not have any notices appear until a later version. This allows developers
1184
-     *                              extra time to update their code before notices appear.
1185
-     * @param int    $error_type
1186
-     */
1187
-    public static function doing_it_wrong(
1188
-        $function,
1189
-        $message,
1190
-        $version,
1191
-        $applies_when = '',
1192
-        $error_type = null
1193
-    ) {
1194
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1195
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1196
-        }
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * Like get_notices, but returns an array of all the notices of the given type.
1203
-     *
1204
-     * @return array {
1205
-     * @type array $success   all the success messages
1206
-     * @type array $errors    all the error messages
1207
-     * @type array $attention all the attention messages
1208
-     * }
1209
-     */
1210
-    public static function get_raw_notices()
1211
-    {
1212
-        return self::$_espresso_notices;
1213
-    }
1077
+		}
1078
+		return '';
1079
+	}
1080
+
1081
+
1082
+
1083
+	/**
1084
+	 *    enqueue_error_scripts
1085
+	 *
1086
+	 * @return        void
1087
+	 */
1088
+	public static function enqueue_error_scripts()
1089
+	{
1090
+		self::_print_scripts();
1091
+	}
1092
+
1093
+
1094
+
1095
+	/**
1096
+	 *    create error code from filepath, function name,
1097
+	 *    and line number where exception or error was thrown
1098
+	 *
1099
+	 * @param string $file
1100
+	 * @param string $func
1101
+	 * @param string $line
1102
+	 * @return string
1103
+	 */
1104
+	public static function generate_error_code($file = '', $func = '', $line = '')
1105
+	{
1106
+		$file = explode('.', basename($file));
1107
+		$error_code = ! empty($file[0]) ? $file[0] : '';
1108
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
1109
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
1110
+		return $error_code;
1111
+	}
1112
+
1113
+
1114
+
1115
+	/**
1116
+	 *    write exception details to log file
1117
+	 *
1118
+	 * @param int   $time
1119
+	 * @param array $ex
1120
+	 * @param bool  $clear
1121
+	 * @return void
1122
+	 */
1123
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1124
+	{
1125
+		if (empty($ex)) {
1126
+			return;
1127
+		}
1128
+		if (! $time) {
1129
+			$time = time();
1130
+		}
1131
+		$exception_log = '----------------------------------------------------------------------------------------'
1132
+						 . PHP_EOL;
1133
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1134
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1135
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1136
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1137
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1138
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
1139
+		$exception_log .= $ex['string'] . PHP_EOL;
1140
+		$exception_log .= '----------------------------------------------------------------------------------------'
1141
+						  . PHP_EOL;
1142
+		try {
1143
+			EEH_File::ensure_file_exists_and_is_writable(
1144
+				EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1145
+			);
1146
+			EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs');
1147
+			if (! $clear) {
1148
+				//get existing log file and append new log info
1149
+				$exception_log = EEH_File::get_file_contents(
1150
+					EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1151
+				) . $exception_log;
1152
+			}
1153
+			EEH_File::write_to_file(
1154
+				EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file,
1155
+				$exception_log
1156
+			);
1157
+		} catch (EE_Error $e) {
1158
+			EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1159
+				'event_espresso'), $e->getMessage()));
1160
+			return;
1161
+		}
1162
+	}
1163
+
1164
+
1165
+
1166
+	/**
1167
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1168
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1169
+	 * but the code execution is done in a manner that could lead to unexpected results
1170
+	 * (i.e. running to early, or too late in WP or EE loading process).
1171
+	 * A good test for knowing whether to use this method is:
1172
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1173
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1174
+	 * 2. If this is loaded before something else, it won't break anything,
1175
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1176
+	 *
1177
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1178
+	 * @param string $function      The function that was called
1179
+	 * @param string $message       A message explaining what has been done incorrectly
1180
+	 * @param string $version       The version of Event Espresso where the error was added
1181
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1182
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1183
+	 *                              but not have any notices appear until a later version. This allows developers
1184
+	 *                              extra time to update their code before notices appear.
1185
+	 * @param int    $error_type
1186
+	 */
1187
+	public static function doing_it_wrong(
1188
+		$function,
1189
+		$message,
1190
+		$version,
1191
+		$applies_when = '',
1192
+		$error_type = null
1193
+	) {
1194
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1195
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1196
+		}
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * Like get_notices, but returns an array of all the notices of the given type.
1203
+	 *
1204
+	 * @return array {
1205
+	 * @type array $success   all the success messages
1206
+	 * @type array $errors    all the error messages
1207
+	 * @type array $attention all the attention messages
1208
+	 * }
1209
+	 */
1210
+	public static function get_raw_notices()
1211
+	{
1212
+		return self::$_espresso_notices;
1213
+	}
1214 1214
 
1215 1215
 
1216 1216
 
@@ -1226,27 +1226,27 @@  discard block
 block discarded – undo
1226 1226
  */
1227 1227
 function espresso_error_enqueue_scripts()
1228 1228
 {
1229
-    // js for error handling
1230
-    wp_register_script(
1231
-        'espresso_core',
1232
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1233
-        array('jquery'),
1234
-        EVENT_ESPRESSO_VERSION,
1235
-        false
1236
-    );
1237
-    wp_register_script(
1238
-        'ee_error_js',
1239
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1240
-        array('espresso_core'),
1241
-        EVENT_ESPRESSO_VERSION,
1242
-        false
1243
-    );
1229
+	// js for error handling
1230
+	wp_register_script(
1231
+		'espresso_core',
1232
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1233
+		array('jquery'),
1234
+		EVENT_ESPRESSO_VERSION,
1235
+		false
1236
+	);
1237
+	wp_register_script(
1238
+		'ee_error_js',
1239
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1240
+		array('espresso_core'),
1241
+		EVENT_ESPRESSO_VERSION,
1242
+		false
1243
+	);
1244 1244
 }
1245 1245
 
1246 1246
 if (is_admin()) {
1247
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1247
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1248 1248
 } else {
1249
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1249
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1250 1250
 }
1251 1251
 
1252 1252
 
Please login to merge, or discard this patch.